const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-UDkgHKae.js","assets/useLeadSiteSearchSuggestions-DgW3whaZ.js","assets/AgentReviewsSection-CTXeVz8u.js","assets/ListingCarouselModule-ZvwbdqyA.js","assets/imageOptimization-Csrlnz8M.js","assets/ExchangeListingsSection-BkYynp1u.js","assets/LeadSiteLuxuryHome-BZ_3gpw_.js","assets/LeadSiteExchangeListings-aF816CdF.js","assets/LeadSiteLuxuryHome-DKt_VWIz.css","assets/LeadSiteLandRanchHome-CbVmqj4F.js","assets/LeadSiteSearch-8-QMc-jX.js","assets/LeadSiteListingCardImage-CP6DLVQ9.js","assets/LeadSiteMap-BPqjUjtA.js","assets/LeadSiteLuxurySearch-Cc65M_pk.js","assets/LeadSiteListingDetail-zycRVvUF.js","assets/ListingVideoTour-BW3t5Gm_.js","assets/useListingVideos-NghEXqev.js","assets/LeadSiteLuxuryListingDetail-PVb4Q5nG.js","assets/LeadSiteBlog-B7znnFJY.js","assets/purify.es-BYftNTi7.js","assets/LeadSiteCityPage-Ca0D4VzK.js","assets/CityFaqSection-DhO1VySE.js","assets/LeadSiteSubdivisionPage-Cd_fARfD.js","assets/LeadSiteFocusPage-ClERW_oh.js","assets/OrgSiteAgents-DzRPSpPp.js","assets/OrgSiteHome-COQ0cB-Q.js","assets/OrgSitePages-CMb_rX1O.js","assets/OrgSiteListings-Cz9-YAuf.js","assets/PublicLiveEvent-B9ffeeU2.js","assets/useLiveEngagement-BB2iARn0.js","assets/LiveEventConsole-tNH8-ST0.js","assets/StagingStudio-2HzapYHG.js","assets/presets-CGXuS9CL.js","assets/download-BqCckdNk.js","assets/BeforeAfterSlider-CD6CTwfn.js","assets/BuyCreditsDialog-CbvniA-Q.js","assets/StagingLibrary-DucD493u.js","assets/StagingCredits-JNBp4UsV.js","assets/StagingSharePage-Dvg8H8F1.js","assets/StagingStudioAdmin-DC8kkLwZ.js","assets/PostcardManager-Y0GA-h5_.js","assets/usePostcardZones-CptURNz_.js","assets/DirectMail-D3Fw3q9m.js","assets/LeadSiteEditor-D9K-EY3S.js","assets/ImageUrlField-npdngGl9.js","assets/HomepageModuleManager-DoeoHIIw.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-CPJCobFl.js","assets/AdminFreeWebsiteOfferStudio-Ba-7iRc3.js","assets/MLSListingDetail-CzU1qDMv.js","assets/EmailCampaigns-DwqXQ4x1.js","assets/sesRequest-DXc_tVVG.js","assets/EmailCampaignComposer-DAt9bsRA.js","assets/EditorModeSelector-DBwgT-BF.js","assets/SharedCampaignTemplates-DuDulfak.js","assets/TemplateEditorDialog-Arp3QtsA.js","assets/AgentTemplates-COndeNzp.js","assets/TheLocalMoveHome-BNzUyAvB.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-BwjCp868.js"])))=>i.map(i=>d[i]); var Bps=Object.defineProperty;var $ft=s=>{throw TypeError(s)};var $ps=(s,t,n)=>t in s?Bps(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var _r=(s,t,n)=>$ps(s,typeof t!="symbol"?t+"":t,n),$8e=(s,t,n)=>t.has(s)||$ft("Cannot "+n);var ye=(s,t,n)=>($8e(s,t,"read from private field"),n?n.call(s):t.get(s)),ys=(s,t,n)=>t.has(s)?$ft("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),Yt=(s,t,n,r)=>($8e(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),ds=(s,t,n)=>($8e(s,t,"access private method"),n);var Z0=(s,t,n,r)=>({set _(a){Yt(s,t,a,n)},get _(){return ye(s,t,r)}});function Ups(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 kp=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ru(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function qps(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 _It={exports:{}},bIe={},wIt={exports:{}},Au={};/** * @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 cae=Symbol.for("react.element"),Vps=Symbol.for("react.portal"),Hps=Symbol.for("react.fragment"),Gps=Symbol.for("react.strict_mode"),Wps=Symbol.for("react.profiler"),Kps=Symbol.for("react.provider"),Yps=Symbol.for("react.context"),Zps=Symbol.for("react.forward_ref"),Xps=Symbol.for("react.suspense"),Qps=Symbol.for("react.memo"),Jps=Symbol.for("react.lazy"),Uft=Symbol.iterator;function egs(s){return s===null||typeof s!="object"?null:(s=Uft&&s[Uft]||s["@@iterator"],typeof s=="function"?s:null)}var jIt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},NIt=Object.assign,kIt={};function RW(s,t,n){this.props=s,this.context=t,this.refs=kIt,this.updater=n||jIt}RW.prototype.isReactComponent={};RW.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")};RW.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function SIt(){}SIt.prototype=RW.prototype;function YQe(s,t,n){this.props=s,this.context=t,this.refs=kIt,this.updater=n||jIt}var ZQe=YQe.prototype=new SIt;ZQe.constructor=YQe;NIt(ZQe,RW.prototype);ZQe.isPureReactComponent=!0;var qft=Array.isArray,CIt=Object.prototype.hasOwnProperty,XQe={current:null},AIt={key:!0,ref:!0,__self:!0,__source:!0};function EIt(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)CIt.call(t,r)&&!AIt.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(fe,re))uea(be,fe)?(ae[te]=be,ae[ue]=re,te=ue):(ae[te]=fe,ae[ve]=re,te=ve);else if(uea(be,re))ae[te]=be,ae[ue]=re,te=ue;else break e}}return le}function a(ae,le){var re=ae.sortIndex-le.sortIndex;return re!==0?re:ae.id-le.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;s.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();s.unstable_now=function(){return l.now()-o}}var c=[],d=[],u=1,h=null,m=3,f=!1,g=!1,x=!1,v=typeof setTimeout=="function"?setTimeout:null,y=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 le=n(d);le!==null;){if(le.callback===null)r(d);else if(le.startTime<=ae)r(d),le.sortIndex=le.expirationTime,t(c,le);else break;le=n(d)}}function S(ae){if(x=!1,w(ae),!g)if(n(c)!==null)g=!0,Z(A);else{var le=n(d);le!==null&&X(S,le.startTime-ae)}}function A(ae,le){g=!1,x&&(x=!1,y(P),P=-1),f=!0;var re=m;try{for(w(le),h=n(c);h!==null&&(!(h.expirationTime>le)||ae&&!O());){var te=h.callback;if(typeof te=="function"){h.callback=null,m=h.priorityLevel;var J=te(h.expirationTime<=le);le=s.unstable_now(),typeof J=="function"?h.callback=J:h===n(c)&&r(c),w(le)}else r(c);h=n(c)}if(h!==null)var ce=!0;else{var ve=n(d);ve!==null&&X(S,ve.startTime-le),ce=!1}return ce}finally{h=null,m=re,f=!1}}var E=!1,I=null,P=-1,R=5,D=-1;function O(){return!(s.unstable_now()-Dae||125te?(ae.sortIndex=re,t(d,ae),n(c)===null&&ae===n(d)&&(x?(y(P),P=-1):x=!0,X(S,re-te))):(ae.sortIndex=J,t(c,ae),g||f||(g=!0,Z(A))),ae},s.unstable_shouldYield=O,s.unstable_wrapCallback=function(ae){var le=m;return function(){var re=m;m=le;try{return ae.apply(this,arguments)}finally{m=re}}}})(LIt);IIt.exports=LIt;var XQ=IIt.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 ugs=j,j2=XQ;function yi(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"),Eqe=Object.prototype.hasOwnProperty,hgs=/^[: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]*$/,Hft={},Gft={};function mgs(s){return Eqe.call(Gft,s)?!0:Eqe.call(Hft,s)?!1:hgs.test(s)?Gft[s]=!0:(Hft[s]=!0,!1)}function fgs(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 pgs(s,t,n,r){if(t===null||typeof t>"u"||fgs(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 I_(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 Nb={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){Nb[s]=new I_(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];Nb[t]=new I_(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){Nb[s]=new I_(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){Nb[s]=new I_(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){Nb[s]=new I_(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){Nb[s]=new I_(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){Nb[s]=new I_(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){Nb[s]=new I_(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){Nb[s]=new I_(s,5,!1,s.toLowerCase(),null,!1,!1)});var JQe=/[\-:]([a-z])/g;function eJe(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(JQe,eJe);Nb[t]=new I_(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(JQe,eJe);Nb[t]=new I_(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(JQe,eJe);Nb[t]=new I_(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){Nb[s]=new I_(s,1,!1,s.toLowerCase(),null,!1,!1)});Nb.xlinkHref=new I_("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){Nb[s]=new I_(s,1,!1,s.toLowerCase(),null,!0,!0)});function tJe(s,t,n,r){var a=Nb.hasOwnProperty(t)?Nb[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{V8e=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?KX(s):""}function ggs(s){switch(s.tag){case 5:return KX(s.type);case 16:return KX("Lazy");case 13:return KX("Suspense");case 19:return KX("SuspenseList");case 0:case 2:case 15:return s=H8e(s.type,!1),s;case 11:return s=H8e(s.type.render,!1),s;case 1:return s=H8e(s.type,!0),s;default:return""}}function Iqe(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 IU:return"Fragment";case PU:return"Portal";case Tqe:return"Profiler";case sJe:return"StrictMode";case Mqe:return"Suspense";case Pqe:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case FIt:return(s.displayName||"Context")+".Consumer";case DIt:return(s._context.displayName||"Context")+".Provider";case nJe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case rJe:return t=s.displayName||null,t!==null?t:Iqe(s.type)||"Memo";case QM:t=s._payload,s=s._init;try{return Iqe(s(t))}catch{}}return null}function xgs(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 Iqe(t);case 8:return t===sJe?"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 xL(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function zIt(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function ygs(s){var t=zIt(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 Wle(s){s._valueTracker||(s._valueTracker=ygs(s))}function BIt(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=zIt(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function FAe(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 Lqe(s,t){var n=t.checked;return Ug({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function Kft(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=xL(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 $It(s,t){t=t.checked,t!=null&&tJe(s,"checked",t,!1)}function Rqe(s,t){$It(s,t);var n=xL(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")?Dqe(s,t.type,n):t.hasOwnProperty("defaultValue")&&Dqe(s,t.type,xL(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function Yft(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 Dqe(s,t,n){(t!=="number"||FAe(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var YX=Array.isArray;function xq(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=Kle.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function _te(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var QQ={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},vgs=["Webkit","ms","Moz","O"];Object.keys(QQ).forEach(function(s){vgs.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),QQ[t]=QQ[s]})});function HIt(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||QQ.hasOwnProperty(s)&&QQ[s]?(""+t).trim():t+"px"}function GIt(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=HIt(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var bgs=Ug({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 zqe(s,t){if(t){if(bgs[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(yi(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(yi(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(yi(61))}if(t.style!=null&&typeof t.style!="object")throw Error(yi(62))}}function Bqe(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 $qe=null;function aJe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var Uqe=null,yq=null,vq=null;function Qft(s){if(s=hae(s)){if(typeof Uqe!="function")throw Error(yi(280));var t=s.stateNode;t&&(t=kIe(t),Uqe(s.stateNode,s.type,t))}}function WIt(s){yq?vq?vq.push(s):vq=[s]:yq=s}function KIt(){if(yq){var s=yq,t=vq;if(vq=yq=null,Qft(s),t)for(s=0;s>>=0,s===0?32:31-(Mgs(s)/Pgs|0)|0}var Yle=64,Zle=4194304;function ZX(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 $Ae(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=ZX(o):(i&=l,i!==0&&(r=ZX(i)))}else l=n&~a,l!==0?r=ZX(l):i!==0&&(r=ZX(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 dae(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-GS(t),s[t]=n}function Dgs(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=eJ),opt=" ",lpt=!1;function fLt(s,t){switch(s){case"keyup":return dxs.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function pLt(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var LU=!1;function hxs(s,t){switch(s){case"compositionend":return pLt(t);case"keypress":return t.which!==32?null:(lpt=!0,opt);case"textInput":return s=t.data,s===opt&&lpt?null:s;default:return null}}function mxs(s,t){if(LU)return s==="compositionend"||!mJe&&fLt(s,t)?(s=hLt(),sme=dJe=dI=null,LU=!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=hpt(n)}}function vLt(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?vLt(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function bLt(){for(var s=window,t=FAe();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=FAe(s.document)}return t}function fJe(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 wxs(s){var t=bLt(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&vLt(n.ownerDocument.documentElement,n)){if(r!==null&&fJe(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=mpt(n,i);var l=mpt(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,RU=null,Kqe=null,sJ=null,Yqe=!1;function fpt(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Yqe||RU==null||RU!==FAe(r)||(r=RU,"selectionStart"in r&&fJe(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}),sJ&&Cte(sJ,r)||(sJ=r,r=VAe(Kqe,"onSelect"),0OU||(s.current=tVe[OU],tVe[OU]=null,OU--)}function Wf(s,t){OU++,tVe[OU]=s.current,s.current=t}var yL={},_1=YL(yL),ww=YL(!1),A7=yL;function rG(s,t){var n=s.type.contextTypes;if(!n)return yL;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 jw(s){return s=s.childContextTypes,s!=null}function GAe(){Sp(ww),Sp(_1)}function _pt(s,t,n){if(_1.current!==yL)throw Error(yi(168));Wf(_1,t),Wf(ww,n)}function ELt(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(yi(108,xgs(s)||"Unknown",a));return Ug({},n,r)}function WAe(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||yL,A7=_1.current,Wf(_1,s),Wf(ww,ww.current),!0}function wpt(s,t,n){var r=s.stateNode;if(!r)throw Error(yi(169));n?(s=ELt(s,t,A7),r.__reactInternalMemoizedMergedChildContext=s,Sp(ww),Sp(_1),Wf(_1,s)):Sp(ww),Wf(ww,n)}var MA=null,SIe=!1,aze=!1;function TLt(s){MA===null?MA=[s]:MA.push(s)}function Lxs(s){SIe=!0,TLt(s)}function ZL(){if(!aze&&MA!==null){aze=!0;var s=0,t=Lm;try{var n=MA;for(Lm=1;s>=l,a-=l,mE=1<<32-GS(t)+a|n<P?(R=I,I=null):R=I.sibling;var D=m(y,I,w[P],S);if(D===null){I===null&&(I=R);break}s&&I&&D.alternate===null&&t(y,I),b=i(D,b,P),E===null?A=D:E.sibling=D,E=D,I=R}if(P===w.length)return n(y,I),Wp&&CR(y,P),A;if(I===null){for(;PP?(R=I,I=null):R=I.sibling;var O=m(y,I,D.value,S);if(O===null){I===null&&(I=R);break}s&&I&&O.alternate===null&&t(y,I),b=i(O,b,P),E===null?A=O:E.sibling=O,E=O,I=R}if(D.done)return n(y,I),Wp&&CR(y,P),A;if(I===null){for(;!D.done;P++,D=w.next())D=h(y,D.value,S),D!==null&&(b=i(D,b,P),E===null?A=D:E.sibling=D,E=D);return Wp&&CR(y,P),A}for(I=r(y,I);!D.done;P++,D=w.next())D=f(I,y,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?A=D:E.sibling=D,E=D);return s&&I.forEach(function(U){return t(y,U)}),Wp&&CR(y,P),A}function v(y,b,w,S){if(typeof w=="object"&&w!==null&&w.type===IU&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case Gle:e:{for(var A=w.key,E=b;E!==null;){if(E.key===A){if(A=w.type,A===IU){if(E.tag===7){n(y,E.sibling),b=a(E,w.props.children),b.return=y,y=b;break e}}else if(E.elementType===A||typeof A=="object"&&A!==null&&A.$$typeof===QM&&kpt(A)===E.type){n(y,E.sibling),b=a(E,w.props),b.ref=dZ(y,E,w),b.return=y,y=b;break e}n(y,E);break}else t(y,E);E=E.sibling}w.type===IU?(b=Tz(w.props.children,y.mode,S,w.key),b.return=y,y=b):(S=dme(w.type,w.key,w.props,null,y.mode,S),S.ref=dZ(y,b,w),S.return=y,y=S)}return l(y);case PU: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(y,b.sibling),b=a(b,w.children||[]),b.return=y,y=b;break e}else{n(y,b);break}else t(y,b);b=b.sibling}b=mze(w,y.mode,S),b.return=y,y=b}return l(y);case QM:return E=w._init,v(y,b,E(w._payload),S)}if(YX(w))return g(y,b,w,S);if(aZ(w))return x(y,b,w,S);nce(y,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,b!==null&&b.tag===6?(n(y,b.sibling),b=a(b,w),b.return=y,y=b):(n(y,b),b=hze(w,y.mode,S),b.return=y,y=b),l(y)):n(y,b)}return v}var iG=LLt(!0),RLt=LLt(!1),ZAe=YL(null),XAe=null,$U=null,yJe=null;function vJe(){yJe=$U=XAe=null}function bJe(s){var t=ZAe.current;Sp(ZAe),s._currentValue=t}function rVe(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 _q(s,t){XAe=s,yJe=$U=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(xw=!0),s.firstContext=null)}function ok(s){var t=s._currentValue;if(yJe!==s)if(s={context:s,memoizedValue:t,next:null},$U===null){if(XAe===null)throw Error(yi(308));$U=s,XAe.dependencies={lanes:0,firstContext:s}}else $U=$U.next=s;return t}var JO=null;function _Je(s){JO===null?JO=[s]:JO.push(s)}function DLt(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,_Je(t)):(n.next=a.next,a.next=n),t.interleaved=n,rT(s,r)}function rT(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 JM=!1;function wJe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function FLt(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 NE(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function TI(s,t,n){var r=s.updateQueue;if(r===null)return null;if(r=r.shared,Nh&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,rT(s,n)}return a=r.interleaved,a===null?(t.next=t,_Je(r)):(t.next=a.next,a.next=t),r.interleaved=t,rT(s,n)}function rme(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,oJe(s,n)}}function Spt(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 QAe(s,t,n,r){var a=s.updateQueue;JM=!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=Ug({},h,m);break e;case 2:JM=!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);M7|=l,s.lanes=l,s.memoizedState=h}}function Cpt(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=oze.transition;oze.transition={};try{s(!1),t()}finally{Lm=n,oze.transition=r}}function e6t(){return lk().memoizedState}function Oxs(s,t,n){var r=PI(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},t6t(s))s6t(t,n);else if(n=DLt(s,t,n,r),n!==null){var a=b_();WS(n,s,r,a),n6t(n,t,r)}}function zxs(s,t,n){var r=PI(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(t6t(s))s6t(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,uC(o,l)){var c=t.interleaved;c===null?(a.next=a,_Je(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=DLt(s,t,a,r),n!==null&&(a=b_(),WS(n,s,r,a),n6t(n,t,r))}}function t6t(s){var t=s.alternate;return s===Ig||t!==null&&t===Ig}function s6t(s,t){nJ=eEe=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function n6t(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,oJe(s,n)}}var tEe={readContext:ok,useCallback:Hb,useContext:Hb,useEffect:Hb,useImperativeHandle:Hb,useInsertionEffect:Hb,useLayoutEffect:Hb,useMemo:Hb,useReducer:Hb,useRef:Hb,useState:Hb,useDebugValue:Hb,useDeferredValue:Hb,useTransition:Hb,useMutableSource:Hb,useSyncExternalStore:Hb,useId:Hb,unstable_isNewReconciler:!1},Bxs={readContext:ok,useCallback:function(s,t){return v5().memoizedState=[s,t===void 0?null:t],s},useContext:ok,useEffect:Ept,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,ime(4194308,4,YLt.bind(null,t,s),n)},useLayoutEffect:function(s,t){return ime(4194308,4,s,t)},useInsertionEffect:function(s,t){return ime(4,2,s,t)},useMemo:function(s,t){var n=v5();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=v5();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=Oxs.bind(null,Ig,s),[r.memoizedState,s]},useRef:function(s){var t=v5();return s={current:s},t.memoizedState=s},useState:Apt,useDebugValue:TJe,useDeferredValue:function(s){return v5().memoizedState=s},useTransition:function(){var s=Apt(!1),t=s[0];return s=Fxs.bind(null,s[1]),v5().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=Ig,a=v5();if(Wp){if(n===void 0)throw Error(yi(407));n=n()}else{if(n=t(),_v===null)throw Error(yi(349));T7&30||$Lt(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,Ept(qLt.bind(null,r,i,s),[s]),r.flags|=2048,Rte(9,ULt.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=v5(),t=_v.identifierPrefix;if(Wp){var n=fE,r=mE;n=(r&~(1<<32-GS(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Ite++,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[a4]=t,s[Tte]=r,m6t(s,t,!1,!1),t.stateNode=s;e:{switch(l=Bqe(n,r),n){case"dialog":xp("cancel",s),xp("close",s),a=r;break;case"iframe":case"object":case"embed":xp("load",s),a=r;break;case"video":case"audio":for(a=0;acG&&(t.flags|=128,r=!0,uZ(i,!1),t.lanes=4194304)}else{if(!r)if(s=JAe(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),uZ(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Wp)return Gb(t),null}else 2*Zx()-i.renderingStartTime>cG&&n!==1073741824&&(t.flags|=128,r=!0,uZ(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=Zx(),t.sibling=null,n=jg.current,Wf(jg,r?n&1|2:n&1),t):(Gb(t),null);case 22:case 23:return DJe(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?zj&1073741824&&(Gb(t),t.subtreeFlags&6&&(t.flags|=8192)):Gb(t),null;case 24:return null;case 25:return null}throw Error(yi(156,t.tag))}function Kxs(s,t){switch(gJe(t),t.tag){case 1:return jw(t.type)&&GAe(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return oG(),Sp(ww),Sp(_1),kJe(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return NJe(t),null;case 13:if(Sp(jg),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(yi(340));aG()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Sp(jg),null;case 4:return oG(),null;case 10:return bJe(t.type._context),null;case 22:case 23:return DJe(),null;case 24:return null;default:return null}}var ace=!1,c1=!1,Yxs=typeof WeakSet=="function"?WeakSet:Set,Mo=null;function UU(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){hx(s,t,r)}else n.current=null}function mVe(s,t,n){try{n()}catch(r){hx(s,t,r)}}var Bpt=!1;function Zxs(s,t){if(Zqe=UAe,s=bLt(),fJe(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(Xqe={focusedElem:s,selectionRange:n},UAe=!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,v=g.memoizedState,y=t.stateNode,b=y.getSnapshotBeforeUpdate(t.elementType===t.type?x:mS(t.type,x),v);y.__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(yi(163))}}catch(S){hx(t,t.return,S)}if(s=t.sibling,s!==null){s.return=t.return,Mo=s;break}Mo=t.return}return g=Bpt,Bpt=!1,g}function rJ(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&&mVe(t,n,i)}a=a.next}while(a!==r)}}function EIe(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 fVe(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 g6t(s){var t=s.alternate;t!==null&&(s.alternate=null,g6t(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[a4],delete t[Tte],delete t[eVe],delete t[Pxs],delete t[Ixs])),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 x6t(s){return s.tag===5||s.tag===3||s.tag===4}function $pt(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||x6t(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 pVe(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=HAe));else if(r!==4&&(s=s.child,s!==null))for(pVe(s,t,n),s=s.sibling;s!==null;)pVe(s,t,n),s=s.sibling}function gVe(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(gVe(s,t,n),s=s.sibling;s!==null;)gVe(s,t,n),s=s.sibling}var eb=null,TS=!1;function mM(s,t,n){for(n=n.child;n!==null;)y6t(s,t,n),n=n.sibling}function y6t(s,t,n){if(N4&&typeof N4.onCommitFiberUnmount=="function")try{N4.onCommitFiberUnmount(_Ie,n)}catch{}switch(n.tag){case 5:c1||UU(n,t);case 6:var r=eb,a=TS;eb=null,mM(s,t,n),eb=r,TS=a,eb!==null&&(TS?(s=eb,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):eb.removeChild(n.stateNode));break;case 18:eb!==null&&(TS?(s=eb,n=n.stateNode,s.nodeType===8?rze(s.parentNode,n):s.nodeType===1&&rze(s,n),kte(s)):rze(eb,n.stateNode));break;case 4:r=eb,a=TS,eb=n.stateNode.containerInfo,TS=!0,mM(s,t,n),eb=r,TS=a;break;case 0:case 11:case 14:case 15:if(!c1&&(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)&&mVe(n,t,l),a=a.next}while(a!==r)}mM(s,t,n);break;case 1:if(!c1&&(UU(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){hx(n,t,o)}mM(s,t,n);break;case 21:mM(s,t,n);break;case 22:n.mode&1?(c1=(r=c1)||n.memoizedState!==null,mM(s,t,n),c1=r):mM(s,t,n);break;default:mM(s,t,n)}}function Upt(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new Yxs),t.forEach(function(r){var a=ays.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function Zk(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=Zx()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Qxs(r/1960))-r,10s?16:s,uI===null)var r=!1;else{if(s=uI,uI=null,rEe=0,Nh&6)throw Error(yi(331));var a=Nh;for(Nh|=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;cZx()-LJe?Ez(s,0):IJe|=n),Nw(s,t)}function S6t(s,t){t===0&&(s.mode&1?(t=Zle,Zle<<=1,!(Zle&130023424)&&(Zle=4194304)):t=1);var n=b_();s=rT(s,t),s!==null&&(dae(s,t,n),Nw(s,n))}function rys(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),S6t(s,n)}function ays(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(yi(314))}r!==null&&r.delete(t),S6t(s,n)}var C6t;C6t=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||ww.current)xw=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return xw=!1,Gxs(s,t,n);xw=!!(s.flags&131072)}else xw=!1,Wp&&t.flags&1048576&&MLt(t,YAe,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;ome(s,t),s=t.pendingProps;var a=rG(t,_1.current);_q(t,n),a=CJe(null,t,r,s,a,n);var i=AJe();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,jw(r)?(i=!0,WAe(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,wJe(t),a.updater=AIe,t.stateNode=a,a._reactInternals=t,iVe(t,r,s,n),t=cVe(null,t,r,!0,i,n)):(t.tag=0,Wp&&i&&pJe(t),r_(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(ome(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=oys(r),s=mS(r,s),a){case 0:t=lVe(null,t,r,s,n);break e;case 1:t=Fpt(null,t,r,s,n);break e;case 11:t=Rpt(null,t,r,s,n);break e;case 14:t=Dpt(null,t,r,mS(r.type,s),n);break e}throw Error(yi(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:mS(r,a),lVe(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:mS(r,a),Fpt(s,t,r,a,n);case 3:e:{if(d6t(t),s===null)throw Error(yi(387));r=t.pendingProps,i=t.memoizedState,a=i.element,FLt(s,t),QAe(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=lG(Error(yi(423)),t),t=Opt(s,t,r,n,a);break e}else if(r!==a){a=lG(Error(yi(424)),t),t=Opt(s,t,r,n,a);break e}else for(Yj=EI(t.stateNode.containerInfo.firstChild),s2=t,Wp=!0,DS=null,n=RLt(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(aG(),r===a){t=aT(s,t,n);break e}r_(s,t,r,n)}t=t.child}return t;case 5:return OLt(t),s===null&&nVe(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,Qqe(r,a)?l=null:i!==null&&Qqe(r,i)&&(t.flags|=32),c6t(s,t),r_(s,t,l,n),t.child;case 6:return s===null&&nVe(t),null;case 13:return u6t(s,t,n);case 4:return jJe(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=iG(t,null,r,n):r_(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:mS(r,a),Rpt(s,t,r,a,n);case 7:return r_(s,t,t.pendingProps,n),t.child;case 8:return r_(s,t,t.pendingProps.children,n),t.child;case 12:return r_(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,Wf(ZAe,r._currentValue),r._currentValue=l,i!==null)if(uC(i.value,l)){if(i.children===a.children&&!ww.current){t=aT(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=NE(-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),rVe(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(yi(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),rVe(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}r_(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,_q(t,n),a=ok(a),r=r(a),t.flags|=1,r_(s,t,r,n),t.child;case 14:return r=t.type,a=mS(r,t.pendingProps),a=mS(r.type,a),Dpt(s,t,r,a,n);case 15:return o6t(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:mS(r,a),ome(s,t),t.tag=1,jw(r)?(s=!0,WAe(t)):s=!1,_q(t,n),r6t(t,r,a),iVe(t,r,a,n),cVe(null,t,r,!0,s,n);case 19:return h6t(s,t,n);case 22:return l6t(s,t,n)}throw Error(yi(156,t.tag))};function A6t(s,t){return tLt(s,t)}function iys(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 zN(s,t,n,r){return new iys(s,t,n,r)}function OJe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function oys(s){if(typeof s=="function")return OJe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===nJe)return 11;if(s===rJe)return 14}return 2}function II(s,t){var n=s.alternate;return n===null?(n=zN(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 dme(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")OJe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case IU:return Tz(n.children,a,i,t);case sJe:l=8,a|=8;break;case Tqe:return s=zN(12,n,t,a|2),s.elementType=Tqe,s.lanes=i,s;case Mqe:return s=zN(13,n,t,a),s.elementType=Mqe,s.lanes=i,s;case Pqe:return s=zN(19,n,t,a),s.elementType=Pqe,s.lanes=i,s;case OIt:return MIe(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case DIt:l=10;break e;case FIt:l=9;break e;case nJe:l=11;break e;case rJe:l=14;break e;case QM:l=16,r=null;break e}throw Error(yi(130,s==null?s:typeof s,""))}return t=zN(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function Tz(s,t,n,r){return s=zN(7,s,r,t),s.lanes=n,s}function MIe(s,t,n,r){return s=zN(22,s,r,t),s.elementType=OIt,s.lanes=n,s.stateNode={isHidden:!1},s}function hze(s,t,n){return s=zN(6,s,null,t),s.lanes=n,s}function mze(s,t,n){return t=zN(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function lys(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=W8e(0),this.expirationTimes=W8e(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=W8e(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function zJe(s,t,n,r,a,i,l,o,c){return s=new lys(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=zN(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},wJe(i),s}function cys(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(P6t)}catch(s){console.error(s)}}P6t(),PIt.exports=L2;var yv=PIt.exports;const I6t=ru(yv);var L6t,Zpt=yv;L6t=Zpt.createRoot,Zpt.hydrateRoot;const fys="modulepreload",pys=function(s){return"/"+s},Xpt={},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=pys(c),c in Xpt)return;Xpt[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":fys,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)})},gys=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),xys=s=>s.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function yys(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")||gys.has(s))}function R6t(s){return D6t(s)!==null}function D6t(s){const t=xys(s);return yys(t)?null:t}const vys=1,bys=1e6;let fze=0;function _ys(){return fze=(fze+1)%Number.MAX_SAFE_INTEGER,fze.toString()}const pze=new Map,Qpt=s=>{if(pze.has(s))return;const t=setTimeout(()=>{pze.delete(s),oJ({type:"REMOVE_TOAST",toastId:s})},bys);pze.set(s,t)},wys=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,vys)};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?Qpt(n):s.toasts.forEach(r=>{Qpt(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)}}},ume=[];let hme={toasts:[]};function oJ(s){hme=wys(hme,s),ume.forEach(t=>{t(hme)})}function _a({...s}){const t=_ys(),n=a=>oJ({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>oJ({type:"DISMISS_TOAST",toastId:t});return oJ({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(hme);return j.useEffect(()=>(ume.push(t),()=>{const n=ume.indexOf(t);n>-1&&ume.splice(n,1)}),[s]),{...s,toast:_a,dismiss:n=>oJ({type:"DISMISS_TOAST",toastId:n})}}var jys=Object.defineProperty,OW=(s,t)=>jys(s,"name",{value:t,configurable:!0}),F6t=!!(typeof window<"u"&&window.document&&window.document.createElement);function Ra(s,t,{checkForDefaultPrevented:n=!0}={}){return OW(function(a){if(s==null||s(a),n===!1||!a||!a.defaultPrevented)return t==null?void 0:t(a)},"handleEvent")}OW(Ra,"composeEventHandlers");function Nys(s){var t;if(!F6t)throw new Error("Cannot access window outside of the DOM");return((t=s==null?void 0:s.ownerDocument)==null?void 0:t.defaultView)??window}OW(Nys,"getOwnerWindow");function _Ve(s){if(!F6t)throw new Error("Cannot access document outside of the DOM");return(s==null?void 0:s.ownerDocument)??document}OW(_Ve,"getOwnerDocument");function O6t(s,t=!1){const{activeElement:n}=_Ve(s);if(!(n!=null&&n.nodeName))return null;if(z6t(n)&&n.contentDocument)return O6t(n.contentDocument.body,t);if(t){const r=n.getAttribute("aria-activedescendant");if(r){const a=_Ve(n).getElementById(r);if(a)return a}}return n}OW(O6t,"getActiveElement");function z6t(s){return s.tagName==="IFRAME"}OW(z6t,"isFrame");var kys=Object.defineProperty,qJe=(s,t)=>kys(s,"name",{value:t,configurable:!0});function wVe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}qJe(wVe,"setRef");function I7(...s){return t=>{let n=!1;const r=s.map(a=>{const i=wVe(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;aSys(s,"name",{value:t,configurable:!0});function Cys(s,t){const n=j.createContext(t);n.displayName=s+"Context";const r=TN(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 TN(a,"useContext"),[r,a]}TN(Cys,"createContext");function ep(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=TN(h=>{var y;const{scope:m,children:f,...g}=h,x=((y=m==null?void 0:m[s])==null?void 0:y[c])||o,v=j.useMemo(()=>g,Object.values(g));return e.jsx(x.Provider,{value:v,children:f})},"Provider");d.displayName=i+"Provider";function u(h,m,f={}){var y;const{optional:g=!1}=f,x=((y=m==null?void 0:m[s])==null?void 0:y[c])||o,v=j.useContext(x);if(v)return v;if(l!==void 0)return l;if(!g)throw new Error(`\`${h}\` must be used within \`${i}\``)}return TN(u,"useContext"),[d,u]}TN(r,"createContext");const a=TN(()=>{const i=n.map(l=>j.createContext(l));return TN(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,B6t(a,...t)]}TN(ep,"createContextScope");function B6t(...s){const t=s[0];if(s.length===1)return t;const n=TN(()=>{const r=s.map(a=>({useScope:a(),scopeName:a.scopeName}));return TN(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}TN(B6t,"composeContextScopes");var Ays=Object.defineProperty,yC=(s,t)=>Ays(s,"name",{value:t,configurable:!0});function hC(s){const t=j.forwardRef((n,r)=>{let{children:a,...i}=n,l=null,o=!1;const c=[];jVe(a)&&typeof lce=="function"&&(a=lce(a._payload)),j.Children.forEach(a,m=>{var f;if(H6t(m)){o=!0;const g=m;let x="child"in g.props?g.props.child:g.props.children;jVe(x)&&typeof lce=="function"&&(x=lce(x._payload)),l=Eys(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?V6t(l):void 0,u=Vo(r,d);if(!l){if(a||a===0)throw new Error(o?Pys(s):Mys(s));return a}const h=q6t(i,l.props??{});return l.type!==j.Fragment&&(h.ref=r?u:d),j.cloneElement(l,h)});return t.displayName=`${s}.Slot`,t}yC(hC,"createSlot");var VJe=hC("Slot"),$6t=Symbol.for("radix.slottable");function U6t(s){const t=yC(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${s}.Slottable`,t.__radixId=$6t,t}yC(U6t,"createSlottable");var Eys=yC((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 q6t(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}}yC(q6t,"mergeProps");function V6t(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)}yC(V6t,"getElementRef");function H6t(s){return j.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===$6t}yC(H6t,"isSlottable");var Tys=Symbol.for("react.lazy");function jVe(s){return s!=null&&typeof s=="object"&&"$$typeof"in s&&s.$$typeof===Tys&&"_payload"in s&&G6t(s._payload)}yC(jVe,"isLazyComponent");function G6t(s){return typeof s=="object"&&s!==null&&"then"in s}yC(G6t,"isPromiseLike");var Mys=yC(s=>`${s} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),Pys=yC(s=>`${s} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),lce=jB[" use ".trim().toString()],Iys=Object.defineProperty,fv=(s,t)=>Iys(s,"name",{value:t,configurable:!0});function SB(s){const t=s+"CollectionProvider",[n,r]=ep(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=fv(x=>{const{scope:v,children:y}=x,b=j.useRef(null),w=j.useRef(new Map).current;return e.jsx(a,{scope:v,itemMap:w,collectionRef:b,children:y})},"CollectionProvider");l.displayName=t;const o=s+"CollectionSlot",c=hC(o),d=j.forwardRef((x,v)=>{const{scope:y,children:b}=x,w=i(o,y),S=Vo(v,w.collectionRef);return e.jsx(c,{ref:S,children:b})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",m=hC(u),f=j.forwardRef((x,v)=>{const{scope:y,children:b,...w}=x,S=j.useRef(null),A=Vo(v,S),E=i(u,y);return j.useEffect(()=>(E.itemMap.set(S,{ref:S,...w}),()=>void E.itemMap.delete(S))),e.jsx(m,{[h]:"",ref:A,children:b})});f.displayName=u;function g(x){const v=i(s+"CollectionConsumer",x);return j.useCallback(()=>{const b=v.collectionRef.current;if(!b)return[];const w=Array.from(b.querySelectorAll(`[${h}]`));return Array.from(v.itemMap.values()).sort((E,I)=>w.indexOf(E.ref.current)-w.indexOf(I.ref.current))},[v.collectionRef,v.itemMap])}return fv(g,"useCollection"),[{Provider:l,Slot:d,ItemSlot:f},g,r]}fv(SB,"createCollection");var Jpt=new WeakMap,Sy,$j,gze=($j=class extends Map{constructor(n){super(n);ys(this,Sy);Yt(this,Sy,[...super.keys()]),Jpt.set(this,!0)}set(n,r){return Jpt.get(this)&&(this.has(n)?ye(this,Sy)[ye(this,Sy).indexOf(n)]=n:ye(this,Sy).push(n)),super.set(n,r),this}insert(n,r,a){const i=this.has(r),l=ye(this,Sy).length,o=HJe(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,Sy)];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 $j(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 $j(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 $j(r)}toReversed(){const n=new $j;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 $j(r)}slice(n,r){const a=new $j;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}},Sy=new WeakMap,fv($j,"OrderedDict"),$j);function mme(s,t){if("at"in Array.prototype)return Array.prototype.at.call(s,t);const n=W6t(s,t);return n===-1?void 0:s[n]}fv(mme,"at");function W6t(s,t){const n=s.length,r=HJe(t),a=r>=0?r:n+r;return a<0||a>=n?-1:a}fv(W6t,"toSafeIndex");function HJe(s){return s!==s||s===0?0:Math.trunc(s)}fv(HJe,"toSafeInteger");function Lys(s){const t=s+"CollectionProvider",[n,r]=ep(t),[a,i]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new gze,setItemMap:fv(()=>{},"setItemMap")}),l=fv(({state:w,...S})=>w?e.jsx(c,{...S,state:w}):e.jsx(o,{...S}),"CollectionProvider");l.displayName=t;const o=fv(w=>{const S=v();return e.jsx(c,{...w,state:S})},"CollectionInit");o.displayName=t+"Init";const c=fv(w=>{const{scope:S,children:A,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=Z6t(()=>{});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:A})},"CollectionProviderImpl");c.displayName=t+"Impl";const d=s+"CollectionSlot",u=hC(d),h=j.forwardRef((w,S)=>{const{scope:A,children:E}=w,I=i(d,A),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=hC(m),x=j.forwardRef((w,S)=>{const{scope:A,children:E,...I}=w,P=j.useRef(null),[R,D]=j.useState(null),O=Vo(S,P,D),U=i(m,A),{setItemMap:W}=U,V=j.useRef(I);K6t(V.current,I)||(V.current=I);const G=V.current;return j.useEffect(()=>{const Z=G;return W(X=>R?X.has(R)?X.set(R,{...Z,element:R}).toSorted(NVe):(X.set(R,{...Z,element:R}),X.toSorted(NVe)):X),()=>{W(X=>!R||!X.has(R)?X:(X.delete(R),new gze(X)))}},[R,G,W]),e.jsx(g,{[f]:"",ref:O,children:E})});x.displayName=m;function v(){return j.useState(new gze)}fv(v,"useInitCollection");function y(w){const{itemMap:S}=i(s+"CollectionConsumer",w);return S}return fv(y,"useCollection"),[{Provider:l,Slot:h,ItemSlot:x},{createCollectionScope:r,useCollection:y,useInitCollection:v}]}fv(Lys,"createCollection");function K6t(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}fv(K6t,"shallowEqual");function Y6t(s,t){return!!(t.compareDocumentPosition(s)&Node.DOCUMENT_POSITION_PRECEDING)}fv(Y6t,"isElementPreceding");function NVe(s,t){return!s[1].element||!t[1].element?0:Y6t(s[1].element,t[1].element)?-1:1}fv(NVe,"sortByDocumentPosition");function Z6t(s){return new MutationObserver(n=>{for(const r of n)if(r.type==="childList"){s();return}})}fv(Z6t,"getChildListObserver");var Rys=Object.defineProperty,Dys=(s,t)=>Rys(s,"name",{value:t,configurable:!0}),Fys=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ei=Fys.reduce((s,t)=>{const n=hC(`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 DIe(s,t){s&&yv.flushSync(()=>s.dispatchEvent(t))}Dys(DIe,"dispatchDiscreteCustomEvent");var Oys=Object.defineProperty,zys=(s,t)=>Oys(s,"name",{value:t,configurable:!0});function Kp(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)},[])}zys(Kp,"useCallbackRef");var Bys=Object.defineProperty,f0=(s,t)=>Bys(s,"name",{value:t,configurable:!0}),kVe="dismissableLayer.update",$ys="dismissableLayer.pointerDownOutside",Uys="dismissableLayer.focusOutside",egt,GJe=j.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),CB=j.forwardRef(f0(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(GJe),[m,f]=j.useState(null),g=(m==null?void 0:m.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,x]=j.useState({}),v=Vo(n,f),y=Array.from(h.layers),[b]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),w=b?y.indexOf(b):-1,S=m?y.indexOf(m):-1,A=h.layersWithOutsidePointerEventsDisabled.size>0,E=S>=w,I=j.useRef(!1),P=Q6t(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=J6t(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===y.length-1:!1,O=Kp(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&&(egt=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),SVe(),()=>{r&&(h.layersWithOutsidePointerEventsDisabled.delete(m),h.layersWithOutsidePointerEventsDisabled.size===0&&(g.body.style.pointerEvents=egt))}},[m,g,r,h]),j.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),SVe())},[m,h]),j.useEffect(()=>{const U=f0(()=>x({}),"handleUpdate");return document.addEventListener(kVe,U),()=>document.removeEventListener(kVe,U)},[]),e.jsx(Ei.div,{...u,ref:v,style:{pointerEvents:A?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")),qys=j.forwardRef(f0(function(t,n){const r=j.useContext(GJe),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 X6t(){const s=j.useContext(GJe),[t,n]=j.useState(null);return j.useEffect(()=>{if(t)return s.dismissableSurfaces.add(t),()=>{s.dismissableSurfaces.delete(t)}},[t,s.dismissableSurfaces]),n}f0(X6t,"useDismissableLayerSurface");var Vys=f0(()=>!0,"IS_TRUE");function Q6t(s,t){const{ownerDocument:n=globalThis==null?void 0:globalThis.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:i,shouldHandlePointerDownOutside:l=Vys}=t,o=Kp(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()}f0(m,"resetOutsideInteraction");function f(){return Array.from(u.current.values()).some(Boolean)}f0(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)}f0(g,"handleInteractionCapture");function x(w){d.current&&u.current.set(w.type,!1)}f0(x,"handleInteractionBubble");const v=f0(w=>{if(w.target&&!c.current){let S=function(){n.removeEventListener("click",h.current);const E=f();m(),E||WJe($ys,o,A,{discrete:!0})};if(f0(S,"handleAndDispatchPointerDownOutsideEvent"),!l(w.target)){n.removeEventListener("click",h.current),m(),c.current=!1;return}const A={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"),y=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const w of y)n.addEventListener(w,g,!0),n.addEventListener(w,x);const b=window.setTimeout(()=>{n.addEventListener("pointerdown",v)},0);return()=>{window.clearTimeout(b),n.removeEventListener("pointerdown",v),n.removeEventListener("click",h.current);for(const w of y)n.removeEventListener(w,g,!0),n.removeEventListener(w,x)}},[n,o,r,a,i,l]),{onPointerDownCapture:f0(()=>c.current=!0,"onPointerDownCapture")}}f0(Q6t,"usePointerDownOutside");function J6t(s,t=globalThis==null?void 0:globalThis.document){const n=Kp(s),r=j.useRef(!1);return j.useEffect(()=>{const a=f0(i=>{i.target&&!r.current&&WJe(Uys,n,{originalEvent:i},{discrete:!1})},"handleFocus");return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,n]),{onFocusCapture:f0(()=>r.current=!0,"onFocusCapture"),onBlurCapture:f0(()=>r.current=!1,"onBlurCapture")}}f0(J6t,"useFocusOutside");function SVe(){const s=new CustomEvent(kVe);document.dispatchEvent(s)}f0(SVe,"dispatchUpdate");function WJe(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?DIe(a,i):a.dispatchEvent(i)}f0(WJe,"handleAndDispatchCustomEvent");var Hys=CB,Gys=qys,Af=globalThis!=null&&globalThis.document?j.useLayoutEffect:()=>{},Wys=Object.defineProperty,Kys=(s,t)=>Wys(s,"name",{value:t,configurable:!0}),fae=j.forwardRef(Kys(function(t,n){var c;const{container:r,...a}=t,[i,l]=j.useState(!1);Af(()=>l(!0),[]);const o=r||i&&((c=globalThis==null?void 0:globalThis.document)==null?void 0:c.body);return o?yv.createPortal(e.jsx(Ei.div,{...a,ref:n}),o):null},"Portal")),Yys=Object.defineProperty,iT=(s,t)=>Yys(s,"name",{value:t,configurable:!0});function eRt(s,t){return j.useReducer((n,r)=>t[n][r]??n,s)}iT(eRt,"useStateMachine");var my=iT(s=>{const{present:t,children:n}=s,r=tRt(t),a=typeof n=="function"?n({present:r.isPresent}):j.Children.only(n),i=sRt(r.ref,nRt(a));return typeof n=="function"||r.isPresent?j.cloneElement(a,{ref:i}):null},"Presence");function tRt(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]=eRt(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??lU(r.current),l.current=void 0):i.current="none"},[c]),Af(()=>{const u=r.current,h=a.current;if(h!==s){const f=i.current,g=lU(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]),Af(()=>{if(t){let u;const h=t.ownerDocument.defaultView??window,m=iT(g=>{const v=lU(r.current).includes(CSS.escape(g.animationName));if(g.target===t&&v&&(d("ANIMATION_END"),!a.current)){const y=t.style.animationFillMode;t.style.animationFillMode="forwards",u=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=y)})}},"handleAnimationEnd"),f=iT(g=>{g.target===t&&(i.current=lU(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=lU(h)}else r.current=null;n(u)},[])}}iT(tRt,"usePresence");function CVe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}iT(CVe,"setRef");function sRt(...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=CVe(l,n);return!a&&typeof o=="function"&&(a=!0),o});if(a)return()=>{for(let l=0;lZys(s,"name",{value:t,configurable:!0}),tgt=jB[" useEffectEvent ".trim().toString()],sgt=jB[" useInsertionEffect ".trim().toString()];function rRt(s){if(typeof tgt=="function")return tgt(s);const t=j.useRef(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof sgt=="function"?sgt(()=>{t.current=s}):Af(()=>{t.current=s}),j.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}Xys(rRt,"useEffectEvent");var Qys=Object.defineProperty,pae=(s,t)=>Qys(s,"name",{value:t,configurable:!0}),Jys=jB[" useInsertionEffect ".trim().toString()]||Af;function dy({prop:s,defaultProp:t,onChange:n=pae(()=>{},"onChange"),caller:r}){const[a,i,l]=aRt({defaultProp:t,onChange:n}),o=s!==void 0,c=o?s:a,d=j.useCallback(u=>{var h;if(o){const m=iRt(u)?u(s):u;m!==s&&((h=l.current)==null||h.call(l,m))}else i(u)},[o,s,i,l]);return[c,d]}pae(dy,"useControllableState");function aRt({defaultProp:s,onChange:t}){const[n,r]=j.useState(s),a=j.useRef(n),i=j.useRef(t);return Jys(()=>{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]}pae(aRt,"useUncontrolledState");function iRt(s){return typeof s=="function"}pae(iRt,"isFunction");var ngt=Symbol("RADIX:SYNC_STATE");function e0s(s,t,n,r){const{prop:a,defaultProp:i,onChange:l,caller:o}=t,c=a!==void 0,d=rRt(l),u=[{...n,state:i}];r&&u.push(r);const[h,m]=j.useReducer((v,y)=>{if(y.type===ngt)return{...v,state:y.state};const b=s(v,y);return c&&!Object.is(b.state,v.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:ngt,state:a})},[a,h.state,c]),[x,m]}pae(e0s,"useControllableStateReducer");var t0s=Object.defineProperty,s0s=(s,t)=>t0s(s,"name",{value:t,configurable:!0}),oRt=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"}),KJe=j.forwardRef(s0s(function(t,n){return e.jsx(Ei.span,{...t,ref:n,style:{...oRt,...t.style}})},"VisuallyHidden")),n0s=KJe,r0s=Object.defineProperty,bf=(s,t)=>r0s(s,"name",{value:t,configurable:!0}),lRt="ToastProvider",[YJe,cRt,a0s]=SB("Toast"),[dRt,VNr]=ep("Toast",[a0s]),[i0s,FIe]=dRt(lRt),o0s=bf(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 \`${lRt}\`. Expected non-empty \`string\`.`),e.jsx(YJe.Provider,{scope:t,children:e.jsx(i0s,{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"),l0s="ToastViewport",c0s=["F8"],AVe="toast.viewportPause",EVe="toast.viewportResume",d0s=j.forwardRef(bf(function(t,n){const{__scopeToast:r,hotkey:a=c0s,label:i="Notifications ({hotkey})",...l}=t,o=FIe(l0s,r),c=cRt(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 y=bf(b=>{var S;a.length!==0&&a.every(A=>b[A]||b.code===A)&&((S=m.current)==null||S.focus())},"handleKeyDown");return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[a]),j.useEffect(()=>{const y=d.current,b=m.current;if(x&&y&&b){const w=bf(()=>{if(!o.isClosePausedRef.current){const I=new CustomEvent(AVe);b.dispatchEvent(I),o.isClosePausedRef.current=!0}},"handlePause"),S=bf(()=>{if(o.isClosePausedRef.current){const I=new CustomEvent(EVe);b.dispatchEvent(I),o.isClosePausedRef.current=!1}},"handleResume"),A=bf(I=>{!y.contains(I.relatedTarget)&&S()},"handleFocusOutResume"),E=bf(()=>{y.contains(document.activeElement)||S()},"handlePointerLeaveResume");return y.addEventListener("focusin",w),y.addEventListener("focusout",A),y.addEventListener("pointermove",w),y.addEventListener("pointerleave",E),window.addEventListener("blur",w),window.addEventListener("focus",S),()=>{y.removeEventListener("focusin",w),y.removeEventListener("focusout",A),y.removeEventListener("pointermove",w),y.removeEventListener("pointerleave",E),window.removeEventListener("blur",w),window.removeEventListener("focus",S)}}},[x,o.isClosePausedRef]);const v=j.useCallback(({tabbingDirection:y})=>{const w=c().map(S=>{const A=S.ref.current,E=[A,...pRt(A)];return y==="forwards"?E:E.reverse()});return(y==="forwards"?w.reverse():w).flat()},[c]);return j.useEffect(()=>{const y=m.current;if(y){const b=bf(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===y&&D){(E=u.current)==null||E.focus();return}const W=v({tabbingDirection:D?"backwards":"forwards"}),V=W.findIndex(G=>G===R);fme(W.slice(V+1))?w.preventDefault():D?(I=u.current)==null||I.focus():(P=h.current)==null||P.focus()}},"handleKeyDown");return y.addEventListener("keydown",b),()=>y.removeEventListener("keydown",b)}},[c,v]),e.jsxs(Gys,{ref:d,role:"region","aria-label":i.replace("{hotkey}",g),tabIndex:-1,style:{pointerEvents:x?void 0:"none"},children:[x&&e.jsx(rgt,{ref:u,onFocusFromOutsideViewport:()=>{const y=v({tabbingDirection:"forwards"});fme(y)}}),e.jsx(YJe.Slot,{scope:r,children:e.jsx(Ei.ol,{tabIndex:-1,...l,ref:f})}),x&&e.jsx(rgt,{ref:h,onFocusFromOutsideViewport:()=>{const y=v({tabbingDirection:"backwards"});fme(y)}})]})},"ToastViewport")),u0s="ToastFocusProxy",rgt=j.forwardRef(bf(function(t,n){const{__scopeToast:r,onFocusFromOutsideViewport:a,...i}=t,l=FIe(u0s,r);return e.jsx(KJe,{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")),OIe="Toast",h0s="toast.swipeStart",m0s="toast.swipeMove",f0s="toast.swipeCancel",p0s="toast.swipeEnd",g0s=j.forwardRef(bf(function(t,n){const{forceMount:r,open:a,defaultOpen:i,onOpenChange:l,...o}=t,[c,d]=dy({prop:a,defaultProp:i??!0,onChange:l,caller:OIe});return e.jsx(my,{present:r||c,children:e.jsx(v0s,{open:c,...o,ref:n,onClose:()=>d(!1),onPause:Kp(t.onPause),onResume:Kp(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")),[x0s,y0s]=dRt(OIe,{onClose(){}}),v0s=j.forwardRef(bf(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,v=FIe(OIe,r),y=cRt(r),[b,w]=j.useState(null),S=Vo(n,w),A=j.useRef(null),E=j.useRef(null),I=i||v.duration,P=j.useRef(0),R=j.useRef(I),D=j.useRef(0),{onToastAdd:O,onToastRemove:U}=v,W=Kp(()=>{var X;(b==null?void 0:b.contains(document.activeElement))&&((X=v.viewport)==null||X.focus()),o()}),V=j.useCallback(Z=>{!Z||Z===1/0||(window.clearTimeout(D.current),P.current=new Date().getTime(),D.current=window.setTimeout(W,Z))},[W]);j.useEffect(()=>{const Z=v.viewport;if(Z){const X=bf(()=>{V(R.current),u==null||u()},"handleResume"),ae=bf(()=>{const le=new Date().getTime()-P.current;R.current=R.current-le,window.clearTimeout(D.current),d==null||d()},"handlePause");return Z.addEventListener(AVe,ae),Z.addEventListener(EVe,X),()=>{Z.removeEventListener(AVe,ae),Z.removeEventListener(EVe,X)}}},[v.viewport,I,d,u,V]),j.useEffect(()=>{l&&!v.isClosePausedRef.current&&V(I)},[l,I,v.isClosePausedRef,V]),j.useEffect(()=>()=>{window.clearTimeout(D.current)},[]),j.useEffect(()=>(O(),()=>U()),[O,U]);const G=j.useMemo(()=>b?ZJe(b):null,[b]);return v.viewport?e.jsxs(e.Fragment,{children:[G&&e.jsx(b0s,{__scopeToast:r,role:"status","aria-live":a==="foreground"?"assertive":"polite",children:G}),e.jsx(x0s,{scope:r,onClose:W,children:yv.createPortal(e.jsx(YJe.ItemSlot,{scope:r,children:e.jsx(Hys,{asChild:!0,onEscapeKeyDown:Ra(c,Z=>{y().some(ae=>{var le;return(le=ae.ref.current)==null?void 0:le.contains(Z.target)})||W()}),children:e.jsx(Ei.li,{tabIndex:0,"data-state":l?"open":"closed","data-swipe-direction":v.swipeDirection,...x,ref:S,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:Ra(t.onKeyDown,Z=>{Z.key==="Escape"&&(c==null||c(Z.nativeEvent),Z.nativeEvent.defaultPrevented||W())}),onPointerDown:Ra(t.onPointerDown,Z=>{Z.button===0&&(A.current={x:Z.clientX,y:Z.clientY})}),onPointerMove:Ra(t.onPointerMove,Z=>{if(!A.current)return;const X=Z.clientX-A.current.x,ae=Z.clientY-A.current.y,le=!!E.current,re=["left","right"].includes(v.swipeDirection),te=["left","up"].includes(v.swipeDirection)?Math.min:Math.max,J=re?te(0,X):0,ce=re?0:te(0,ae),ve=Z.pointerType==="touch"?10:2,fe={x:J,y:ce},ue={originalEvent:Z,delta:fe};le?(E.current=fe,QX(m0s,m,ue,{discrete:!1})):agt(fe,v.swipeDirection,ve)?(E.current=fe,QX(h0s,h,ue,{discrete:!1}),Z.target.setPointerCapture(Z.pointerId)):(Math.abs(X)>ve||Math.abs(ae)>ve)&&(A.current=null)}),onPointerUp:Ra(t.onPointerUp,Z=>{const X=E.current,ae=Z.target;if(ae.hasPointerCapture(Z.pointerId)&&ae.releasePointerCapture(Z.pointerId),E.current=null,A.current=null,X){const le=Z.currentTarget,re={originalEvent:Z,delta:X};agt(X,v.swipeDirection,v.swipeThreshold)?QX(p0s,g,re,{discrete:!0}):QX(f0s,f,re,{discrete:!0}),le.addEventListener("click",te=>te.preventDefault(),{once:!0})}})})})}),v.viewport)})]}):null},"ToastImpl")),b0s=bf(s=>{const{__scopeToast:t,children:n,...r}=s,a=FIe(OIe,t),[i,l]=j.useState(!1),[o,c]=j.useState(!1);return mRt(()=>l(!0)),j.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(fae,{asChild:!0,container:a.announcerContainer||void 0,children:e.jsx(KJe,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},"ToastAnnounce"),_0s=j.forwardRef(bf(function(t,n){const{__scopeToast:r,...a}=t;return e.jsx(Ei.div,{...a,ref:n})},"ToastTitle")),w0s=j.forwardRef(bf(function(t,n){const{__scopeToast:r,...a}=t;return e.jsx(Ei.div,{...a,ref:n})},"ToastDescription")),j0s="ToastAction",N0s=j.forwardRef(bf(function(t,n){const{altText:r,...a}=t;return r.trim()?e.jsx(hRt,{altText:r,asChild:!0,children:e.jsx(uRt,{...a,ref:n})}):(console.error(`Invalid prop \`altText\` supplied to \`${j0s}\`. Expected non-empty \`string\`.`),null)},"ToastAction")),k0s="ToastClose",uRt=j.forwardRef(bf(function(t,n){const{__scopeToast:r,...a}=t,i=y0s(k0s,r);return e.jsx(hRt,{asChild:!0,children:e.jsx(Ei.button,{type:"button",...a,ref:n,onClick:Ra(t.onClick,i.onClose)})})},"ToastClose")),hRt=j.forwardRef(bf(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 ZJe(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),fRt(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(...ZJe(r))}}),t}bf(ZJe,"getAnnounceTextContent");function QX(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?DIe(a,i):a.dispatchEvent(i)}bf(QX,"handleAndDispatchCustomEvent");var agt=bf((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 mRt(s=()=>{}){const t=Kp(s);Af(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}bf(mRt,"useNextFrame");function fRt(s){return s.nodeType===s.ELEMENT_NODE}bf(fRt,"isHTMLElement");function pRt(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:bf(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}bf(pRt,"getTabbableCandidates");function fme(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}bf(fme,"focusFirst");var S0s=o0s,gRt=d0s,xRt=g0s,yRt=_0s,vRt=w0s,bRt=N0s,_Rt=uRt;function wRt(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,ogt=sd,AB=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return ogt(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=igt(u)||igt(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,v]=g;return Array.isArray(v)?v.includes({...i,...o}[x]):{...i,...o}[x]===v})?[...d,h,m]:d},[]);return ogt(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 C0s=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),jRt=(...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 A0s={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 NRt=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,...A0s,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:jRt("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(NRt,{ref:i,iconNode:t,className:jRt(`lucide-${C0s(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 pme=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 gme=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 xme=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 yme=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 rf=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 vme=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 bme=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 ER=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 TR=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 _me=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 MR=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 wme=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 jme=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 Nme=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 kme=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 Sme=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 LI=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 Cme=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 Ame=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 Eme=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 Tme=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 Mme=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 Pme=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 Ime=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 Lme=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 Rme=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 Dme=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 Fme=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 RI=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 DI=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 Ome=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 zme=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 Bme=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 $me=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 Ume=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 qme=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 Vme=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 Hme=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 Gme=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 Wme=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 Kme=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 Yme=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 Zme=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 Xme=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 Qme=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 Jme=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 efe=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 tfe=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 sfe=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 nfe=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 rfe=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 afe=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 ife=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 FI=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 ofe=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 wv=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 lfe=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 cfe=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 dfe=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 ufe=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 hfe=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 mfe=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 ffe=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 pfe=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 gfe=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 xfe=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 yfe=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 PR=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 vfe=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 bfe=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 _fe=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 lJ=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 wfe=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 jfe=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 Nfe=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 IR=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 LR=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 Lg=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 kfe=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 cJ=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 Sfe=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 Va=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 Cfe=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 S4=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 Afe=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 Qa=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 Efe=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 Tfe=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 RR=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 Dy=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 Mfe=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 Pfe=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 Ife=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 DR=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 Mz=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 Lfe=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 Rfe=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 FR=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 Dfe=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 Ffe=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 Ofe=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 zfe=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 Bfe=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 $fe=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 Im=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 Ufe=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 OR=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 qfe=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 Vfe=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 Hfe=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 Gfe=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 PA=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 Wfe=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 Kfe=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 Yfe=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 Zfe=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 Xfe=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 Qfe=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 Jfe=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 epe=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 tpe=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 spe=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 npe=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 rpe=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 ape=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 ipe=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 ope=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 Pz=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 lpe=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 cpe=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 dpe=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 upe=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 hpe=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 C0=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 mpe=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 fpe=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 ppe=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 gpe=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 xpe=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 ype=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 dJ=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 vpe=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 bpe=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 C4=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 _pe=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 n2=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 wpe=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 jpe=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 Npe=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 kpe=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 Spe=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 Cpe=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 KS=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 Ape=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 YS=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 zy=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 zR=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 BR=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 Epe=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 Tpe=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 Mpe=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 Ppe=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 Ipe=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 Lpe=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 Rpe=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 Dpe=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 Fpe=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 Ope=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 zpe=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 Bpe=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 $pe=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 Upe=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 qpe=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 Vpe=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 kE=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 Hpe=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 Gpe=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 Wpe=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 Kpe=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 Ype=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 Zpe=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 Xpe=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 $R=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 Qpe=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 Jpe=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 ege=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 tge=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 sge=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 nge=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 rge=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 age=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 ige=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 oge=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 _x=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 lge=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 cge=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 dge=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 uge=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 hge=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 mge=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 fge=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 pge=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 gge=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 xge=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 OI=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 yge=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 A0=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 vge=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 bge=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 _ge=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 A4=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 uJ=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 wge=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 eP=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 jge=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 Nge=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 kge=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 hJ=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 Sge=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 Cge=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 Age=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 Ege=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 wx=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 Tge=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 Mge=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 Pge=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 Ige=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 Lge=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 wi=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 zI=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 Rge=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 Dge=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 Fge=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 Oge=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 zge=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 Rg=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 r2=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 Bge=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 $ge=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 Uge=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 qge=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 gb=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 Su=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 Vge=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 Wc=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 Hge=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 ZS=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 Gge=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 Wge=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 jq=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 Kge=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 vv=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 Yge=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 Zge=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 Xge=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 Qge=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 mJ=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 Ea=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 Jge=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 jx=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 exe=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 txe=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 sxe=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 nxe=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 rxe=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 UR=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 axe=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 ixe=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 oxe=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 lxe=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 cxe=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 dxe=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 uxe=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 hxe=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 mxe=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 fxe=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 pxe=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 gxe=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 xxe=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 qR=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 VR=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 yxe=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 vxe=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 bxe=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 HR=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 GR=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 WR=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 _xe=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 KR=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 wxe=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 Gl=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 jxe=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 YR=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 Nxe=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 kxe=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 ZR=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 XR=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 Sxe=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 QR=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 JR=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 eD=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 Cxe=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 Iz=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 ma=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 Axe=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 Exe=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 wl=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 Txe=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 Mxe=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 kd=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 xb=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 Pxe=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 Ixe=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 Lxe=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 Rxe=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 Dxe=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 Fxe=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 Oxe=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 kw=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 zxe=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 Lz=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 Bxe=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 $xe=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 Uxe=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 vl=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 tD=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 sD=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 nD=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 rD=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 aD=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 iD=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 oD=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 lD=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 Wl=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 Vr=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 cD=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 dD=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 uD=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 hD=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 qxe=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 mD=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 Vxe=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 Hxe=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 Gxe=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 Wxe=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 Kxe=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 Yxe=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 Zxe=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 fD=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 J5=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 pD=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 Xxe=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 gD=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 xD=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 yD=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 vD=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 ef=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 bD=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 _D=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 wD=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 Qxe=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 jD=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 ND=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 kD=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 ju=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 Dg=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 Jxe=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 eye=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 Nq=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 GN=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 tye=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 Fg=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 sye=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 nye=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 SD=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 CD=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 rye=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 aye=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 iye=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 oye=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 lye=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 cye=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 dye=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 uye=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 hye=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 kq=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 mye=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 fye=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 pye=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 gye=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 xye=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 yye=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 vye=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 bye=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 _ye=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 ca=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 wye=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 jye=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 AD=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 Nye=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 kye=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 Sye=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 Cye=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 Aye=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 Eye=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 Tye=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 Mye=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 Pye=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 Iye=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 Lye=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 Rye=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 tP=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 Dye=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 Fye=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 pE=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 Oye=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 e4=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 SE=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 zye=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 Bye=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 E4=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 $ye=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 fJ=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 ED=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 sP=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 Uye=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 qye=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 Vye=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 Rz=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 Hye=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 Gye=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 Wye=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 Kye=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 Yye=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 TD=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 BI=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 Zye=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 Xye=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 Qye=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 Jye=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 e0e=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 t0e=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 s0e=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 n0e=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 r0e=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 Za=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 a0e=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 i0e=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 o0e=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 pJ=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 l0e=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 c0e=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 d0e=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 u0e=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 h0e=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 m0e=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 f0e=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 p0e=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 jv=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 g0e=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 x0e=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 y0e=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 v0e=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 Og=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 b0e=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 _0e=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 w0e=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 j0e=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 N0e=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 k0e=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 S0e=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 Sq=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 C0e=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 A0e=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 E0e=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 T0e=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 MD=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 M0e=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 P0e=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 I0e=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 L0e=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 R0e=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 D0e=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 F0e=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 O0e=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 z0e=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 B0e=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 $0e=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 U0e=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 q0e=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 V0e=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 H0e=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 G0e=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 W0e=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 K0e=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 Y0e=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 su=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 Z0e=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 X0e=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 WN=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 Q0e=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 ji=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 J0e=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 eve=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 tve=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 sve=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 nve=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 p1=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 rve=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 ave=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 ive=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 ove=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 lve=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 cve=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 kN=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 dve=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 uve=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 hve=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 Cq=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 Xx=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 o_=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 mve=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 fve=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 pve=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 Aq=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 gve=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 xve=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 yve=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 Ir=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 vve=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 Nx=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 Ta=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 Zp=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 bve=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 _ve=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 wve=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 jve=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 Nve=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 kve=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 Sve=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 Cve=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 Ave=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 Eve=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 PD=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 Tve=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 Mve=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 Pve=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 ID=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 LD=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 RD=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 DD=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 Dz=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 gJ=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 Ive=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 Lve=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 Rve=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 FD=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 Dve=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 Fve=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 a2=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 Ove=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 $I=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 zve=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 Bve=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 $ve=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 Uve=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 qve=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 Vve=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 Hve=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 Gve=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 Wve=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 Kve=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 Yve=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 l_=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 OD=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 Eq=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 Zve=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 Xve=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 Qve=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 Jve=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 xJ=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 ebe=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 KN=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 yJ=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 tbe=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 sbe=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 Qr=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 nbe=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 rbe=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 vJ=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 abe=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 ibe=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 bJ=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 obe=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 lbe=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 cbe=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 dbe=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 ube=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 Tq=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 hbe=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 nf=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 mbe=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 Sw=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 fbe=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 pbe=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 gbe=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 xbe=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 ybe=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 vbe=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 bbe=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 _be=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 CE=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 wbe=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 sh=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 jbe=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 Nbe=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 kbe=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 UI=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 Sbe=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 Cbe=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 _J=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 Abe=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 Ebe=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 US=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 Tbe=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 Mbe=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 Pbe=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 Ibe=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 Lbe=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 Rbe=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 Dbe=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 Fbe=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 Obe=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 zD=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 zbe=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 Bbe=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 $be=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 Ube=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 qbe=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 Vbe=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 Hbe=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 Gbe=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 Wbe=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 Kbe=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 Ybe=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 Nv=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 Zbe=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 BD=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 wJ=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 Xbe=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 Qbe=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 Jbe=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 e1e=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 t1e=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 s1e=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 n1e=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 r1e=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 Mq=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 a1e=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 i1e=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 o1e=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 l1e=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 c1e=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 d1e=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 u1e=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 h1e=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 m1e=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 f1e=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 p1e=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 g1e=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 x1e=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 y1e=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 v1e=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 b1e=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 _1e=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 w1e=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 j1e=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 Fz=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 dl=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 N1e=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 k1e=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 $D=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 S1e=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 C1e=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 A1e=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 E1e=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 T1e=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 M1e=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 P1e=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 I1e=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 L1e=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 R1e=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 D1e=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 F1e=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 O1e=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 z1e=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 B1e=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 $1e=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 U1e=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 cl=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 q1e=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 V1e=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 af=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 H1e=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 G1e=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 UD=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 W1e=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 qD=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 Dj=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 K1e=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 zg=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 Y1e=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 Z1e=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 X1e=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 Q1e=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 jJ=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 J1e=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 NJ=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 t4=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 e_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 t_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 Pq=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 yb=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 s_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 n_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 kJ=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 r_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 qI=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 a_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 i_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 Iq=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 Oz=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 Lq=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 o_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 l_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 c_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 d_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 u_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 h_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 m_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 f_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 SJ=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 p_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 g_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 x_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 y_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 v_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 Cw=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 b_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 __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 w_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 j_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 CJ=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 N_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 k_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 VD=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 HD=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 AJ=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 S_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 C_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 A_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 E_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 kv=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 T_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 M_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 Hc=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 P_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 I_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 zz=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 GD=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 WD=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 L_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 Rq=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 XS=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 R_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 Ef=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 AE=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 D_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 F_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 O_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 z_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 i2=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 VI=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 B_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 __=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 $_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 U_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 q_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 V_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 H_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 G_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 W_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 K_e=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 Y_e=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 Z_e=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 Dq=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 X_e=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 Q_e=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 KD=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 J_e=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 ewe=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 twe=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 swe=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 nwe=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 rwe=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 T4=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 HI=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 Xf=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 awe=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 iwe=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 owe=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 o2=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 lwe=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 cwe=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 dwe=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 uwe=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 hwe=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 l2=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 Fq=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 mwe=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 fwe=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 QS=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 pwe=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 nu=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 Sd=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 ly=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 gwe=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 Sv=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 xwe=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 ywe=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 EJ=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 vwe=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 bwe=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 c2=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 TJ=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 _we=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 wwe=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 jwe=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 Nwe=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 kwe=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 Swe=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 E0=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 Ct=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 Cwe=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 Awe=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 Ewe=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 Twe=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 Oq=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 YD=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 MJ=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 ZD=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 jc=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 GI=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 Bz=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 Mwe=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 Pwe=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 Iwe=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 Lwe=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 $z=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 Rwe=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 zq=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 Bq=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 Dwe=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 Fwe=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 Owe=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 WI=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 pn=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 zwe=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 Bwe=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 $we=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 Uwe=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 qwe=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 Vwe=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 Hwe=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 Gwe=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 Wwe=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 Kwe=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 Ywe=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 Zwe=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 ui=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 PJ=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 Uz=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 Xwe=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 IJ=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 qz=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 EE=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 Qwe=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 gm=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 Jwe=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 eje=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 TE=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 Vz=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 tje=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 sje=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 $q=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 nje=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 rje=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 aje=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 LJ=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 ije=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 oje=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 lje=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 Ah=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 cje=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 dje=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 uje=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 hje=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 mje=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 fje=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 RJ=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 pje=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 h4=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 ME=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 DJ=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 gje=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 xje=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 FJ=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 yje=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 no=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 OJ=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 vje=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 XD=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 Hz=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 bje=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 _je=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 wje=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 jje=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 Nje=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 kje=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 Sje=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 Cje=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 YN=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 Aje=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 Eje=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 Tje=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 Mje=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 Pje=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 Ije=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 Uq=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 Lje=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 Rje=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 Dje=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 Gz=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 Fje=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 ZN=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 Oje=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 zje=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 Bje=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 $je=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 Uje=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 zJ=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 qje=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 Pm=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 lb=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 Vje=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 QD=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 Hje=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 Gje=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 Wje=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 Kje=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 Yje=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 Zje=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 Xje=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 Qje=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 Jje=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 e2e=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 t2e=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 s2e=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 BJ=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 n2e=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 r2e=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 a2e=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 qq=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 i2e=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 o2e=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 l2e=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 $J=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 c2e=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 XN=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 d2e=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 u2e=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 h2e=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 m2e=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 f2e=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 p2e=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 g2e=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 x2e=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 y2e=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 FS=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 v2e=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 JD=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 eF=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 b2e=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 _2e=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 w2e=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 j2e=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 N2e=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 k2e=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 S2e=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 C2e=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 A2e=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 E2e=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 T2e=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 M2e=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 ym=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 P2e=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 I2e=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 tF=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 L2e=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 yd=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 R2e=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 sF=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 D2e=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 F2e=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 nF=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 rF=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 aF=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 iF=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 O2e=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 oF=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 z2e=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 B2e=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 $2e=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 lF=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 U2e=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 q2e=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 V2e=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 H2e=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 IA=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 KI=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 G2e=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 W2e=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 kx=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 Cv=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 K2e=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 Y2e=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 _f=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 Z2e=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 PE=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 SN=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 Vq=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 X2e=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 Q2e=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 pi=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 J2e=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 Aw=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 eNe=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 tNe=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 UJ=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 sNe=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 nNe=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 rNe=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 aNe=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 iNe=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 oNe=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 lNe=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 cNe=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 dNe=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 uNe=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 qJ=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 hNe=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 mNe=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 fNe=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 pNe=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 gNe=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 VJ=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 IE=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 xNe=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 yNe=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 vNe=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 bNe=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 HJ=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 Ou=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 _Ne=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 cF=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 QN=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 cn=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 wNe=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 jNe=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 NNe=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 kNe=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 SNe=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 CNe=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 ANe=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 ENe=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 TNe=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 GJ=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 vb=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 MNe=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 LE=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 PNe=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 INe=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 LNe=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 RNe=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 Xp=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 d2=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 DNe=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 Hq=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 FNe=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 ONe=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 zNe=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 BNe=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 bb=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 $Ne=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 UNe=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 qNe=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 VNe=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 HNe=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 GNe=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 WNe=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 KNe=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 YNe=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 ZNe=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 XNe=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 QNe=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 JNe=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 Gq=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 dF=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 eke=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 tke=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 ske=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 nke=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 rke=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 RE=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 ake=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 Wq=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 ike=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 co=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 oke=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 lke=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 cke=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 dke=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 WJ=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 DE=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 uke=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 hke=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 mke=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 Kq=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 fke=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 pke=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 By=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 gke=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 xke=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 uF=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 yke=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 Sx=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 vke=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 Wz=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 bke=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 Yq=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 _ke=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 hF=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 mF=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 wke=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 jke=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 M4=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 Nke=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 kke=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 Ske=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 Cke=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 Ake=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 Eke=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 Tke=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 Mke=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 fF=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 Pke=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 Ike=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 Lke=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 Rke=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 Dke=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 Fke=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 Oke=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 zke=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 Bke=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 $ke=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 Uke=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 qke=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 Vke=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 Hke=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 Gke=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 Zq=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 Wke=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 Kke=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 Yke=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 Zke=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 Xq=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 Xke=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 pF=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 Qke=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 Zr=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 Jke=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 eSe=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 tSe=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 sSe=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 nSe=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 rSe=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 JS=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 Nd=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 aSe=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 Hd=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 KJ=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 iSe=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 oSe=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 Qq=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 lSe=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 Rm=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 cSe=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 dSe=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 uSe=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 Kz=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 hSe=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 Yz=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 gF=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 Tf=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 mSe=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 fSe=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 pSe=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 P4=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 gSe=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 eC=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 xSe=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 ySe=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 vSe=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 bSe=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 Zz=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 _Se=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 wSe=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 jSe=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 NSe=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 kSe=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 SSe=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 CSe=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 ASe=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 YJ=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 ESe=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 TSe=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 ZJ=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 MSe=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 PSe=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 ISe=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 LSe=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 YI=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 xF=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 RSe=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 DSe=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 g1=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 FSe=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 OSe=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 zSe=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 Zj=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 Jq=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 BSe=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 $Se=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 USe=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 ZI=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 wn=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 qSe=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 VSe=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 HSe=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 GSe=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 WSe=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 KSe=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 YSe=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 XI=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 yF=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 vF=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 bF=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 _F=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 wF=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 jF=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 NF=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 kF=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 SF=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 CF=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 AF=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 EF=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 TF=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 MF=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 PF=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 f5=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 qj=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 IF=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 LF=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 RF=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 DF=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 FF=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 OF=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 ZSe=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 XSe=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 zF=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 BF=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 $F=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 UF=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 qF=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 VF=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 HF=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 GF=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 WF=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 KF=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 YF=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 ZF=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 XF=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 QF=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 JF=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 bp=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 eO=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 tO=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 sO=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 nO=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 rO=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 aO=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 QSe=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 iO=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 oO=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 lO=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 cO=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 dO=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 JSe=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 eCe=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 uO=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 hO=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 mO=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 fO=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 w_=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 tCe=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 sCe=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 nCe=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 rCe=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 aCe=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 ei=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 iCe=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 oCe=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 lCe=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 cCe=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 Xz=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 eV=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 dCe=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 uCe=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 XJ=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 hCe=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 mCe=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 fCe=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 pCe=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 gCe=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 JN=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 xCe=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 yCe=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 vCe=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 bCe=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 _Ce=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 wCe=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 jCe=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 NCe=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 kCe=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 tV=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 SCe=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 CCe=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 ACe=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 ECe=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 TCe=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 MCe=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 sV=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 PCe=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 nV=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 ICe=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 Cp=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 QJ=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 LCe=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 RCe=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 DCe=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 FCe=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 OCe=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 zCe=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 ph=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 BCe=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 $Ce=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 UCe=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 qCe=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 pO=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 VCe=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 HCe=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 rV=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 GCe=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 WCe=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 KCe=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 gO=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 YCe=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 ZCe=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 XCe=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 QCe=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 JCe=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 JJ=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 $y=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 e5e=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 t5e=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 s5e=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 n5e=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 r5e=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 a5e=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 Qz=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 i5e=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 o5e=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 l5e=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 c5e=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 d5e=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 u5e=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 h5e=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 m5e=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 f5e=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 p5e=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 g5e=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 x5e=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 y5e=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 v5e=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 b5e=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 _5e=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 w5e=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 j5e=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 N5e=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 xO=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 qn=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 k5e=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 S5e=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 yO=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 QI=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 C5e=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 A5e=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 tC=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 E5e=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 Zl=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 Al=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 T5e=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 M5e=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 eee=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 P5e=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 I5e=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 vO=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 L5e=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 R5e=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 tee=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 D5e=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 aV=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 F5e=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 O5e=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 Jz=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 see=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 z5e=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 FE=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 B5e=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 $5e=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 U5e=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 bO=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 q5e=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 e7=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 iV=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 V5e=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 u2=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 nee=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 oV=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 H5e=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 lc=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 nP=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 _O=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 wO=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 G5e=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 jO=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 lV=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 NO=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 rP=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 W5e=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 cV=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 x0=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 Yn=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 kO=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 SO=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 K5e=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 dV=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 Y5e=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 Z5e=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 X5e=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 Q5e=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 J5e=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 e4e=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 fa=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 t4e=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 s4e=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 n4e=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 r4e=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 a4e=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 ree=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 i4e=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 aee=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 o4e=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 l4e=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 c4e=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 CO=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 t7=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 d4e=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 Qx=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 u4e=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 h4e=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 m4e=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 f4e=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 p4e=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 g4e=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 x4e=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 y4e=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 v4e=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 b4e=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 _4e=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 w4e=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 j4e=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 N4e=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 k4e=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 S4e=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 C4e=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 A4e=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 E4e=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 T4e=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 M4e=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 P4e=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 s7=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 I4e=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 L4e=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 I4=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 mr=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 uV=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 R4e=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 Qp=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 JI=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 hV=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 E0s=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:pme,AArrowUp:gme,ALargeSmall:xme,Accessibility:yme,Activity:rf,AirVent:vme,Airplay:bme,AlarmClock:wme,AlarmClockCheck:ER,AlarmClockMinus:TR,AlarmClockOff:_me,AlarmClockPlus:MR,AlarmSmoke:jme,Album:Nme,AlignCenter:LI,AlignCenterHorizontal:kme,AlignCenterVertical:Sme,AlignEndHorizontal:Cme,AlignEndVertical:Ame,AlignHorizontalDistributeCenter:Eme,AlignHorizontalDistributeEnd:Tme,AlignHorizontalDistributeStart:Mme,AlignHorizontalJustifyCenter:Pme,AlignHorizontalJustifyEnd:Ime,AlignHorizontalJustifyStart:Lme,AlignHorizontalSpaceAround:Rme,AlignHorizontalSpaceBetween:Dme,AlignJustify:Fme,AlignLeft:RI,AlignRight:DI,AlignStartHorizontal:Ome,AlignStartVertical:zme,AlignVerticalDistributeCenter:Bme,AlignVerticalDistributeEnd:$me,AlignVerticalDistributeStart:Ume,AlignVerticalJustifyCenter:qme,AlignVerticalJustifyEnd:Vme,AlignVerticalJustifyStart:Hme,AlignVerticalSpaceAround:Gme,AlignVerticalSpaceBetween:Wme,Ambulance:Kme,Ampersand:Yme,Ampersands:Zme,Amphora:Xme,Anchor:Qme,Angry:Jme,Annoyed:efe,Antenna:tfe,Anvil:sfe,Aperture:nfe,AppWindow:afe,AppWindowMac:rfe,Apple:ife,Archive:wv,ArchiveRestore:FI,ArchiveX:ofe,Armchair:lfe,ArrowBigDown:dfe,ArrowBigDownDash:cfe,ArrowBigLeft:hfe,ArrowBigLeftDash:ufe,ArrowBigRight:ffe,ArrowBigRightDash:mfe,ArrowBigUp:gfe,ArrowBigUpDash:pfe,ArrowDown:Lg,ArrowDown01:xfe,ArrowDown10:yfe,ArrowDownAZ:PR,ArrowDownFromLine:vfe,ArrowDownLeft:bfe,ArrowDownNarrowWide:_fe,ArrowDownRight:lJ,ArrowDownToDot:wfe,ArrowDownToLine:jfe,ArrowDownUp:Nfe,ArrowDownWideNarrow:IR,ArrowDownZA:LR,ArrowLeft:Va,ArrowLeftFromLine:kfe,ArrowLeftRight:cJ,ArrowLeftToLine:Sfe,ArrowRight:Qa,ArrowRightFromLine:Cfe,ArrowRightLeft:S4,ArrowRightToLine:Afe,ArrowUp:Zf,ArrowUp01:Efe,ArrowUp10:Tfe,ArrowUpAZ:RR,ArrowUpDown:Dy,ArrowUpFromDot:Mfe,ArrowUpFromLine:Pfe,ArrowUpLeft:Ife,ArrowUpNarrowWide:DR,ArrowUpRight:Mz,ArrowUpToLine:Lfe,ArrowUpWideNarrow:Rfe,ArrowUpZA:FR,ArrowsUpFromLine:Dfe,Asterisk:Ffe,AtSign:Ofe,Atom:zfe,AudioLines:Bfe,AudioWaveform:$fe,Award:Im,Axe:Ufe,Axis3d:OR,Baby:qfe,Backpack:Vfe,Badge:ipe,BadgeAlert:Hfe,BadgeCent:Gfe,BadgeCheck:PA,BadgeDollarSign:Wfe,BadgeEuro:Kfe,BadgeHelp:Yfe,BadgeIndianRupee:Zfe,BadgeInfo:Xfe,BadgeJapaneseYen:Qfe,BadgeMinus:Jfe,BadgePercent:epe,BadgePlus:tpe,BadgePoundSterling:spe,BadgeRussianRuble:npe,BadgeSwissFranc:rpe,BadgeX:ape,BaggageClaim:ope,Ban:Pz,Banana:lpe,Bandage:cpe,Banknote:dpe,Barcode:upe,Baseline:hpe,Bath:C0,Battery:ype,BatteryCharging:mpe,BatteryFull:fpe,BatteryLow:ppe,BatteryMedium:gpe,BatteryWarning:xpe,Beaker:dJ,Bean:bpe,BeanOff:vpe,Bed:n2,BedDouble:C4,BedSingle:_pe,Beef:wpe,Beer:Npe,BeerOff:jpe,Bell:zy,BellDot:kpe,BellElectric:Spe,BellMinus:Cpe,BellOff:KS,BellPlus:Ape,BellRing:YS,BetweenHorizontalEnd:zR,BetweenHorizontalStart:BR,BetweenVerticalEnd:Epe,BetweenVerticalStart:Tpe,BicepsFlexed:Mpe,Bike:Ppe,Binary:Ipe,Binoculars:Lpe,Biohazard:Rpe,Bird:Dpe,Bitcoin:Fpe,Blend:Ope,Blinds:zpe,Blocks:Bpe,Bluetooth:Vpe,BluetoothConnected:$pe,BluetoothOff:Upe,BluetoothSearching:qpe,Bold:kE,Bolt:Hpe,Bomb:Gpe,Bone:Wpe,Book:pge,BookA:Kpe,BookAudio:Ype,BookCheck:Zpe,BookCopy:Xpe,BookDashed:$R,BookDown:Qpe,BookHeadphones:Jpe,BookHeart:ege,BookImage:tge,BookKey:sge,BookLock:nge,BookMarked:rge,BookMinus:age,BookOpen:_x,BookOpenCheck:ige,BookOpenText:oge,BookPlus:lge,BookText:cge,BookType:dge,BookUp:hge,BookUp2:uge,BookUser:mge,BookX:fge,Bookmark:A0,BookmarkCheck:gge,BookmarkMinus:xge,BookmarkPlus:OI,BookmarkX:yge,BoomBox:vge,Bot:A4,BotMessageSquare:bge,BotOff:_ge,Box:uJ,Boxes:wge,Braces:eP,Brackets:jge,Brain:hJ,BrainCircuit:Nge,BrainCog:kge,BrickWall:Sge,Briefcase:wx,BriefcaseBusiness:Cge,BriefcaseConveyorBelt:Age,BriefcaseMedical:Ege,BringToFront:Tge,Brush:Mge,Bug:Lge,BugOff:Pge,BugPlay:Ige,Building:zI,Building2:wi,Bus:Dge,BusFront:Rge,Cable:Oge,CableCar:Fge,Cake:Rg,CakeSlice:zge,Calculator:r2,Calendar:Ea,Calendar1:Bge,CalendarArrowDown:$ge,CalendarArrowUp:Uge,CalendarCheck:gb,CalendarCheck2:qge,CalendarClock:Su,CalendarCog:Vge,CalendarDays:Wc,CalendarFold:Hge,CalendarHeart:ZS,CalendarMinus:Wge,CalendarMinus2:Gge,CalendarOff:jq,CalendarPlus:vv,CalendarPlus2:Kge,CalendarRange:Yge,CalendarSearch:Zge,CalendarSync:Xge,CalendarX:mJ,CalendarX2:Qge,Camera:jx,CameraOff:Jge,Candy:sxe,CandyCane:exe,CandyOff:txe,Cannabis:nxe,Captions:UR,CaptionsOff:rxe,Car:oxe,CarFront:axe,CarTaxiFront:ixe,Caravan:lxe,Carrot:cxe,CaseLower:dxe,CaseSensitive:uxe,CaseUpper:hxe,CassetteTape:mxe,Cast:fxe,Castle:pxe,Cat:gxe,Cctv:xxe,ChartArea:qR,ChartBar:HR,ChartBarBig:VR,ChartBarDecreasing:yxe,ChartBarIncreasing:vxe,ChartBarStacked:bxe,ChartCandlestick:GR,ChartColumn:Gl,ChartColumnBig:WR,ChartColumnDecreasing:_xe,ChartColumnIncreasing:KR,ChartColumnStacked:wxe,ChartGantt:jxe,ChartLine:YR,ChartNetwork:Nxe,ChartNoAxesColumn:XR,ChartNoAxesColumnDecreasing:kxe,ChartNoAxesColumnIncreasing:ZR,ChartNoAxesCombined:Sxe,ChartNoAxesGantt:QR,ChartPie:JR,ChartScatter:eD,ChartSpline:Cxe,Check:ma,CheckCheck:Iz,ChefHat:Axe,Cherry:Exe,ChevronDown:wl,ChevronFirst:Txe,ChevronLast:Mxe,ChevronLeft:kd,ChevronRight:Di,ChevronUp:xb,ChevronsDown:Ixe,ChevronsDownUp:Pxe,ChevronsLeft:Dxe,ChevronsLeftRight:Rxe,ChevronsLeftRightEllipsis:Lxe,ChevronsRight:Oxe,ChevronsRightLeft:Fxe,ChevronsUp:zxe,ChevronsUpDown:kw,Chrome:Lz,Church:Bxe,Cigarette:Uxe,CigaretteOff:$xe,Circle:Dg,CircleAlert:vl,CircleArrowDown:tD,CircleArrowLeft:sD,CircleArrowOutDownLeft:nD,CircleArrowOutDownRight:rD,CircleArrowOutUpLeft:aD,CircleArrowOutUpRight:iD,CircleArrowRight:oD,CircleArrowUp:lD,CircleCheck:Vr,CircleCheckBig:Wl,CircleChevronDown:cD,CircleChevronLeft:dD,CircleChevronRight:uD,CircleChevronUp:hD,CircleDashed:qxe,CircleDivide:mD,CircleDollarSign:Vxe,CircleDot:Gxe,CircleDotDashed:Hxe,CircleEllipsis:Wxe,CircleEqual:Kxe,CircleFadingArrowUp:Yxe,CircleFadingPlus:Zxe,CircleGauge:fD,CircleHelp:J5,CircleMinus:pD,CircleOff:Xxe,CircleParking:xD,CircleParkingOff:gD,CirclePause:yD,CirclePercent:vD,CirclePlay:ef,CirclePlus:bD,CirclePower:_D,CircleSlash:Qxe,CircleSlash2:wD,CircleStop:jD,CircleUser:kD,CircleUserRound:ND,CircleX:ju,CircuitBoard:Jxe,Citrus:eye,Clapperboard:Nq,Clipboard:oye,ClipboardCheck:GN,ClipboardCopy:tye,ClipboardList:Fg,ClipboardMinus:sye,ClipboardPaste:nye,ClipboardPen:CD,ClipboardPenLine:SD,ClipboardPlus:rye,ClipboardType:aye,ClipboardX:iye,Clock:ca,Clock1:lye,Clock10:cye,Clock11:dye,Clock12:uye,Clock2:hye,Clock3:kq,Clock4:mye,Clock5:fye,Clock6:pye,Clock7:gye,Clock8:xye,Clock9:yye,ClockAlert:vye,ClockArrowDown:bye,ClockArrowUp:_ye,Cloud:Dye,CloudAlert:wye,CloudCog:jye,CloudDownload:AD,CloudDrizzle:Nye,CloudFog:kye,CloudHail:Sye,CloudLightning:Cye,CloudMoon:Eye,CloudMoonRain:Aye,CloudOff:Tye,CloudRain:Pye,CloudRainWind:Mye,CloudSnow:Iye,CloudSun:Rye,CloudSunRain:Lye,CloudUpload:tP,Cloudy:Fye,Clover:pE,Club:Oye,Code:SE,CodeXml:e4,Codepen:zye,Codesandbox:Bye,Coffee:E4,Cog:$ye,Coins:fJ,Columns2:ED,Columns3:sP,Columns4:Uye,Combine:qye,Command:Vye,Compass:Rz,Component:Hye,Computer:Gye,ConciergeBell:Wye,Cone:Kye,Construction:Yye,Contact:BI,ContactRound:TD,Container:Zye,Contrast:Xye,Cookie:Qye,CookingPot:Jye,Copy:Za,CopyCheck:e0e,CopyMinus:t0e,CopyPlus:s0e,CopySlash:n0e,CopyX:r0e,Copyleft:a0e,Copyright:i0e,CornerDownLeft:o0e,CornerDownRight:pJ,CornerLeftDown:l0e,CornerLeftUp:c0e,CornerRightDown:d0e,CornerRightUp:u0e,CornerUpLeft:h0e,CornerUpRight:m0e,Cpu:f0e,CreativeCommons:p0e,CreditCard:jv,Croissant:g0e,Crop:x0e,Cross:y0e,Crosshair:v0e,Crown:Og,Cuboid:b0e,CupSoda:_0e,Currency:w0e,Cylinder:j0e,Dam:N0e,Database:Sq,DatabaseBackup:k0e,DatabaseZap:S0e,Delete:C0e,Dessert:A0e,Diameter:E0e,Diamond:P0e,DiamondMinus:T0e,DiamondPercent:MD,DiamondPlus:M0e,Dice1:I0e,Dice2:L0e,Dice3:R0e,Dice4:D0e,Dice5:F0e,Dice6:O0e,Dices:z0e,Diff:B0e,Disc:V0e,Disc2:$0e,Disc3:U0e,DiscAlbum:q0e,Divide:H0e,Dna:W0e,DnaOff:G0e,Dock:K0e,Dog:Y0e,DollarSign:su,Donut:Z0e,DoorClosed:X0e,DoorOpen:WN,Dot:Q0e,Download:ji,DraftingCompass:J0e,Drama:eve,Dribbble:tve,Drill:sve,Droplet:nve,Droplets:p1,Drum:rve,Drumstick:ave,Dumbbell:ive,Ear:lve,EarOff:ove,Earth:kN,EarthLock:cve,Eclipse:dve,Egg:Cq,EggFried:uve,EggOff:hve,Ellipsis:o_,EllipsisVertical:Xx,Equal:pve,EqualApproximately:mve,EqualNot:fve,Eraser:Aq,EthernetPort:gve,Euro:xve,Expand:yve,ExternalLink:Ir,Eye:Ta,EyeClosed:vve,EyeOff:Nx,Facebook:Zp,Factory:bve,Fan:_ve,FastForward:wve,Feather:jve,Fence:Nve,FerrisWheel:kve,Figma:Sve,File:Tq,FileArchive:Cve,FileAudio:Eve,FileAudio2:Ave,FileAxis3d:PD,FileBadge:Mve,FileBadge2:Tve,FileBox:Pve,FileChartColumn:LD,FileChartColumnIncreasing:ID,FileChartLine:RD,FileChartPie:DD,FileCheck:gJ,FileCheck2:Dz,FileClock:Ive,FileCode:Rve,FileCode2:Lve,FileCog:FD,FileDiff:Dve,FileDigit:Fve,FileDown:a2,FileHeart:Ove,FileImage:$I,FileInput:zve,FileJson:$ve,FileJson2:Bve,FileKey:qve,FileKey2:Uve,FileLock:Hve,FileLock2:Vve,FileMinus:Wve,FileMinus2:Gve,FileMusic:Kve,FileOutput:Yve,FilePen:OD,FilePenLine:l_,FilePlus:Zve,FilePlus2:Eq,FileQuestion:Xve,FileScan:Qve,FileSearch:xJ,FileSearch2:Jve,FileSliders:ebe,FileSpreadsheet:KN,FileStack:yJ,FileSymlink:tbe,FileTerminal:sbe,FileText:Qr,FileType:rbe,FileType2:nbe,FileUp:vJ,FileUser:abe,FileVideo:bJ,FileVideo2:ibe,FileVolume:lbe,FileVolume2:obe,FileWarning:cbe,FileX:ube,FileX2:dbe,Files:hbe,Film:nf,Filter:Sw,FilterX:mbe,Fingerprint:fbe,FireExtinguisher:pbe,Fish:ybe,FishOff:gbe,FishSymbol:xbe,Flag:CE,FlagOff:vbe,FlagTriangleLeft:bbe,FlagTriangleRight:_be,Flame:sh,FlameKindling:wbe,Flashlight:Nbe,FlashlightOff:jbe,FlaskConical:UI,FlaskConicalOff:kbe,FlaskRound:Sbe,FlipHorizontal:_J,FlipHorizontal2:Cbe,FlipVertical:Ebe,FlipVertical2:Abe,Flower:Tbe,Flower2:US,Focus:Mbe,FoldHorizontal:Pbe,FoldVertical:Ibe,Folder:Mq,FolderArchive:Lbe,FolderCheck:Rbe,FolderClock:Dbe,FolderClosed:Fbe,FolderCode:Obe,FolderCog:zD,FolderDot:zbe,FolderDown:Bbe,FolderGit:Ube,FolderGit2:$be,FolderHeart:qbe,FolderInput:Vbe,FolderKanban:Hbe,FolderKey:Gbe,FolderLock:Wbe,FolderMinus:Kbe,FolderOpen:Nv,FolderOpenDot:Ybe,FolderOutput:Zbe,FolderPen:BD,FolderPlus:wJ,FolderRoot:Xbe,FolderSearch:Jbe,FolderSearch2:Qbe,FolderSymlink:e1e,FolderSync:t1e,FolderTree:s1e,FolderUp:n1e,FolderX:r1e,Folders:a1e,Footprints:i1e,Forklift:o1e,Forward:l1e,Frame:c1e,Framer:d1e,Frown:u1e,Fuel:h1e,Fullscreen:m1e,GalleryHorizontal:p1e,GalleryHorizontalEnd:f1e,GalleryThumbnails:g1e,GalleryVertical:y1e,GalleryVerticalEnd:x1e,Gamepad:b1e,Gamepad2:v1e,Gauge:_1e,Gavel:w1e,Gem:j1e,Ghost:Fz,Gift:dl,GitBranch:k1e,GitBranchPlus:N1e,GitCommitHorizontal:$D,GitCommitVertical:S1e,GitCompare:A1e,GitCompareArrows:C1e,GitFork:E1e,GitGraph:T1e,GitMerge:M1e,GitPullRequest:F1e,GitPullRequestArrow:P1e,GitPullRequestClosed:I1e,GitPullRequestCreate:R1e,GitPullRequestCreateArrow:L1e,GitPullRequestDraft:D1e,Github:O1e,Gitlab:z1e,GlassWater:B1e,Glasses:$1e,Globe:cl,GlobeLock:U1e,Goal:q1e,Grab:V1e,GraduationCap:af,Grape:H1e,Grid2x2:qD,Grid2x2Check:G1e,Grid2x2Plus:UD,Grid2x2X:W1e,Grid3x3:Dj,Grip:Y1e,GripHorizontal:K1e,GripVertical:zg,Group:Z1e,Guitar:X1e,Ham:Q1e,Hammer:jJ,Hand:Pq,HandCoins:J1e,HandHeart:NJ,HandHelping:t4,HandMetal:e_e,HandPlatter:t_e,Handshake:yb,HardDrive:kJ,HardDriveDownload:s_e,HardDriveUpload:n_e,HardHat:r_e,Hash:qI,Haze:a_e,HdmiPort:i_e,Heading:d_e,Heading1:Iq,Heading2:Oz,Heading3:Lq,Heading4:o_e,Heading5:l_e,Heading6:c_e,HeadphoneOff:u_e,Headphones:h_e,Headset:m_e,Heart:Jo,HeartCrack:f_e,HeartHandshake:SJ,HeartOff:p_e,HeartPulse:g_e,Heater:x_e,Hexagon:y_e,Highlighter:v_e,History:Cw,Hop:__e,HopOff:b_e,Hospital:w_e,Hotel:j_e,Hourglass:CJ,House:va,HousePlug:N_e,HousePlus:k_e,IceCreamBowl:VD,IceCreamCone:HD,IdCard:AJ,Image:Hc,ImageDown:S_e,ImageMinus:C_e,ImageOff:A_e,ImagePlay:E_e,ImagePlus:kv,ImageUp:T_e,ImageUpscale:M_e,Images:P_e,Import:I_e,Inbox:zz,IndentDecrease:GD,IndentIncrease:WD,IndianRupee:L_e,Infinity:Rq,Info:XS,InspectionPanel:R_e,Instagram:Ef,Italic:AE,IterationCcw:D_e,IterationCw:F_e,JapaneseYen:O_e,Joystick:z_e,Kanban:i2,Key:__,KeyRound:VI,KeySquare:B_e,Keyboard:q_e,KeyboardMusic:$_e,KeyboardOff:U_e,Lamp:Y_e,LampCeiling:V_e,LampDesk:H_e,LampFloor:G_e,LampWallDown:W_e,LampWallUp:K_e,LandPlot:Z_e,Landmark:Dq,Languages:X_e,Laptop:J_e,LaptopMinimal:KD,LaptopMinimalCheck:Q_e,Lasso:twe,LassoSelect:ewe,Laugh:swe,Layers:T4,Layers2:nwe,Layers3:rwe,LayoutDashboard:HI,LayoutGrid:Xf,LayoutList:awe,LayoutPanelLeft:iwe,LayoutPanelTop:owe,LayoutTemplate:o2,Leaf:lwe,LeafyGreen:cwe,Lectern:dwe,LetterText:uwe,Library:l2,LibraryBig:hwe,LifeBuoy:Fq,Ligature:mwe,Lightbulb:QS,LightbulbOff:fwe,Link:Sd,Link2:nu,Link2Off:pwe,Linkedin:ly,List:E0,ListCheck:gwe,ListChecks:Sv,ListCollapse:xwe,ListEnd:ywe,ListFilter:EJ,ListMinus:vwe,ListMusic:bwe,ListOrdered:c2,ListPlus:TJ,ListRestart:_we,ListStart:wwe,ListTodo:jwe,ListTree:Nwe,ListVideo:kwe,ListX:Swe,Loader:Awe,LoaderCircle:Ct,LoaderPinwheel:Cwe,Locate:Oq,LocateFixed:Ewe,LocateOff:Twe,Lock:jc,LockKeyhole:MJ,LockKeyholeOpen:YD,LockOpen:ZD,LogIn:GI,LogOut:Bz,Logs:Mwe,Lollipop:Pwe,Luggage:Iwe,Magnet:Lwe,Mail:pn,MailCheck:$z,MailMinus:Rwe,MailOpen:zq,MailPlus:Bq,MailQuestion:Dwe,MailSearch:Fwe,MailWarning:Owe,MailX:WI,Mailbox:zwe,Mails:Bwe,Map:Uz,MapPin:ui,MapPinCheck:Uwe,MapPinCheckInside:$we,MapPinHouse:qwe,MapPinMinus:Hwe,MapPinMinusInside:Vwe,MapPinOff:Gwe,MapPinPlus:Kwe,MapPinPlusInside:Wwe,MapPinX:Zwe,MapPinXInside:Ywe,MapPinned:PJ,Martini:Xwe,Maximize:qz,Maximize2:IJ,Medal:EE,Megaphone:gm,MegaphoneOff:Qwe,Meh:Jwe,MemoryStick:eje,Menu:TE,Merge:Vz,MessageCircle:Ah,MessageCircleCode:tje,MessageCircleDashed:sje,MessageCircleHeart:$q,MessageCircleMore:nje,MessageCircleOff:rje,MessageCirclePlus:aje,MessageCircleQuestion:LJ,MessageCircleReply:ije,MessageCircleWarning:oje,MessageCircleX:lje,MessageSquare:no,MessageSquareCode:cje,MessageSquareDashed:dje,MessageSquareDiff:uje,MessageSquareDot:hje,MessageSquareHeart:mje,MessageSquareLock:fje,MessageSquareMore:RJ,MessageSquareOff:pje,MessageSquarePlus:h4,MessageSquareQuote:ME,MessageSquareReply:DJ,MessageSquareShare:gje,MessageSquareText:xje,MessageSquareWarning:FJ,MessageSquareX:yje,MessagesSquare:OJ,Mic:Hz,MicOff:vje,MicVocal:XD,Microchip:bje,Microscope:_je,Microwave:wje,Milestone:jje,Milk:kje,MilkOff:Nje,Minimize:Cje,Minimize2:Sje,Minus:YN,Monitor:ZN,MonitorCheck:Aje,MonitorCog:Eje,MonitorDot:Tje,MonitorDown:Mje,MonitorOff:Pje,MonitorPause:Ije,MonitorPlay:Uq,MonitorSmartphone:Lje,MonitorSpeaker:Rje,MonitorStop:Dje,MonitorUp:Gz,MonitorX:Fje,Moon:zje,MoonStar:Oje,Mountain:$je,MountainSnow:Bje,Mouse:Vje,MouseOff:Uje,MousePointer:lb,MousePointer2:zJ,MousePointerBan:qje,MousePointerClick:Pm,Move:BJ,Move3d:QD,MoveDiagonal:Gje,MoveDiagonal2:Hje,MoveDown:Yje,MoveDownLeft:Wje,MoveDownRight:Kje,MoveHorizontal:Zje,MoveLeft:Xje,MoveRight:Qje,MoveUp:t2e,MoveUpLeft:Jje,MoveUpRight:e2e,MoveVertical:s2e,Music:qq,Music2:n2e,Music3:r2e,Music4:a2e,Navigation:$J,Navigation2:o2e,Navigation2Off:i2e,NavigationOff:l2e,Network:c2e,Newspaper:XN,Nfc:d2e,Notebook:f2e,NotebookPen:u2e,NotebookTabs:h2e,NotebookText:m2e,NotepadText:g2e,NotepadTextDashed:p2e,Nut:y2e,NutOff:x2e,Octagon:b2e,OctagonAlert:FS,OctagonMinus:v2e,OctagonPause:JD,OctagonX:eF,Omega:_2e,Option:w2e,Orbit:j2e,Origami:N2e,Package:ym,Package2:k2e,PackageCheck:S2e,PackageMinus:C2e,PackageOpen:A2e,PackagePlus:E2e,PackageSearch:T2e,PackageX:M2e,PaintBucket:P2e,PaintRoller:I2e,Paintbrush:L2e,PaintbrushVertical:tF,Palette:yd,PanelBottom:F2e,PanelBottomClose:R2e,PanelBottomDashed:sF,PanelBottomOpen:D2e,PanelLeft:iF,PanelLeftClose:nF,PanelLeftDashed:rF,PanelLeftOpen:aF,PanelRight:B2e,PanelRightClose:O2e,PanelRightDashed:oF,PanelRightOpen:z2e,PanelTop:q2e,PanelTopClose:$2e,PanelTopDashed:lF,PanelTopOpen:U2e,PanelsLeftBottom:V2e,PanelsRightBottom:H2e,PanelsTopLeft:IA,Paperclip:KI,Parentheses:G2e,ParkingMeter:W2e,PartyPopper:kx,Pause:Cv,PawPrint:K2e,PcCase:Y2e,Pen:SN,PenLine:_f,PenOff:Z2e,PenTool:PE,Pencil:pi,PencilLine:Vq,PencilOff:X2e,PencilRuler:Q2e,Pentagon:J2e,Percent:Aw,PersonStanding:eNe,PhilippinePeso:tNe,Phone:Da,PhoneCall:UJ,PhoneForwarded:sNe,PhoneIncoming:nNe,PhoneMissed:rNe,PhoneOff:aNe,PhoneOutgoing:iNe,Pi:oNe,Piano:lNe,Pickaxe:cNe,PictureInPicture:uNe,PictureInPicture2:dNe,PiggyBank:qJ,Pilcrow:fNe,PilcrowLeft:hNe,PilcrowRight:mNe,Pill:gNe,PillBottle:pNe,Pin:IE,PinOff:VJ,Pipette:xNe,Pizza:yNe,Plane:HJ,PlaneLanding:vNe,PlaneTakeoff:bNe,Play:Ou,Plug:QN,Plug2:_Ne,PlugZap:cF,Plus:cn,Pocket:jNe,PocketKnife:wNe,Podcast:NNe,Pointer:SNe,PointerOff:kNe,Popcorn:CNe,Popsicle:ANe,PoundSterling:ENe,Power:GJ,PowerOff:TNe,Presentation:vb,Printer:LE,PrinterCheck:MNe,Projector:PNe,Proportions:INe,Puzzle:LNe,Pyramid:RNe,QrCode:Xp,Quote:d2,Rabbit:DNe,Radar:Hq,Radiation:FNe,Radical:ONe,Radio:bb,RadioReceiver:zNe,RadioTower:BNe,Radius:$Ne,RailSymbol:UNe,Rainbow:qNe,Rat:VNe,Ratio:HNe,Receipt:Gq,ReceiptCent:GNe,ReceiptEuro:WNe,ReceiptIndianRupee:KNe,ReceiptJapaneseYen:YNe,ReceiptPoundSterling:ZNe,ReceiptRussianRuble:XNe,ReceiptSwissFranc:QNe,ReceiptText:JNe,RectangleEllipsis:dF,RectangleHorizontal:eke,RectangleVertical:tke,Recycle:ske,Redo:RE,Redo2:nke,RedoDot:rke,RefreshCcw:Wq,RefreshCcwDot:ake,RefreshCw:co,RefreshCwOff:ike,Refrigerator:oke,Regex:lke,RemoveFormatting:cke,Repeat:DE,Repeat1:dke,Repeat2:WJ,Replace:hke,ReplaceAll:uke,Reply:Kq,ReplyAll:mke,Rewind:fke,Ribbon:pke,Rocket:By,RockingChair:gke,RollerCoaster:xke,Rotate3d:uF,RotateCcw:Sx,RotateCcwSquare:yke,RotateCw:Wz,RotateCwSquare:vke,Route:Yq,RouteOff:bke,Router:_ke,Rows2:hF,Rows3:mF,Rows4:wke,Rss:jke,Ruler:M4,RussianRuble:Nke,Sailboat:kke,Salad:Ske,Sandwich:Cke,Satellite:Eke,SatelliteDish:Ake,Save:tl,SaveAll:Tke,SaveOff:Mke,Scale:Pke,Scale3d:fF,Scaling:Ike,Scan:$ke,ScanBarcode:Lke,ScanEye:Rke,ScanFace:Dke,ScanLine:Fke,ScanQrCode:Oke,ScanSearch:zke,ScanText:Bke,School:Uke,Scissors:Vke,ScissorsLineDashed:qke,ScreenShare:Gke,ScreenShareOff:Hke,Scroll:Wke,ScrollText:Zq,Search:Kr,SearchCheck:Kke,SearchCode:Yke,SearchSlash:Zke,SearchX:Xq,Section:Xke,Send:Zr,SendHorizontal:pF,SendToBack:Qke,SeparatorHorizontal:Jke,SeparatorVertical:eSe,Server:rSe,ServerCog:tSe,ServerCrash:sSe,ServerOff:nSe,Settings:Nd,Settings2:JS,Shapes:aSe,Share:KJ,Share2:Hd,Sheet:iSe,Shell:oSe,Shield:Tf,ShieldAlert:Qq,ShieldBan:lSe,ShieldCheck:Rm,ShieldEllipsis:cSe,ShieldHalf:dSe,ShieldMinus:uSe,ShieldOff:Kz,ShieldPlus:hSe,ShieldQuestion:Yz,ShieldX:gF,Ship:fSe,ShipWheel:mSe,Shirt:pSe,ShoppingBag:P4,ShoppingBasket:gSe,ShoppingCart:eC,Shovel:xSe,ShowerHead:ySe,Shrink:vSe,Shrub:bSe,Shuffle:Zz,Sigma:_Se,Signal:SSe,SignalHigh:wSe,SignalLow:jSe,SignalMedium:NSe,SignalZero:kSe,Signature:CSe,Signpost:YJ,SignpostBig:ASe,Siren:ESe,SkipBack:TSe,SkipForward:ZJ,Skull:MSe,Slack:PSe,Slash:ISe,Slice:LSe,SlidersHorizontal:YI,SlidersVertical:xF,Smartphone:g1,SmartphoneCharging:RSe,SmartphoneNfc:DSe,Smile:OSe,SmilePlus:FSe,Snail:zSe,Snowflake:Zj,Sofa:Jq,Soup:BSe,Space:$Se,Spade:USe,Sparkle:ZI,Sparkles:wn,Speaker:qSe,Speech:VSe,SpellCheck:GSe,SpellCheck2:HSe,Spline:WSe,Split:KSe,SprayCan:YSe,Sprout:XI,Square:w_,SquareActivity:yF,SquareArrowDown:_F,SquareArrowDownLeft:vF,SquareArrowDownRight:bF,SquareArrowLeft:wF,SquareArrowOutDownLeft:jF,SquareArrowOutDownRight:NF,SquareArrowOutUpLeft:kF,SquareArrowOutUpRight:SF,SquareArrowRight:CF,SquareArrowUp:TF,SquareArrowUpLeft:AF,SquareArrowUpRight:EF,SquareAsterisk:MF,SquareBottomDashedScissors:PF,SquareChartGantt:f5,SquareCheck:IF,SquareCheckBig:qj,SquareChevronDown:LF,SquareChevronLeft:RF,SquareChevronRight:DF,SquareChevronUp:FF,SquareCode:OF,SquareDashed:$F,SquareDashedBottom:XSe,SquareDashedBottomCode:ZSe,SquareDashedKanban:zF,SquareDashedMousePointer:BF,SquareDivide:UF,SquareDot:qF,SquareEqual:VF,SquareFunction:HF,SquareKanban:GF,SquareLibrary:WF,SquareM:KF,SquareMenu:YF,SquareMinus:ZF,SquareMousePointer:XF,SquareParking:JF,SquareParkingOff:QF,SquarePen:bp,SquarePercent:eO,SquarePi:tO,SquarePilcrow:sO,SquarePlay:nO,SquarePlus:rO,SquarePower:aO,SquareRadical:QSe,SquareScissors:iO,SquareSigma:oO,SquareSlash:lO,SquareSplitHorizontal:cO,SquareSplitVertical:dO,SquareSquare:JSe,SquareStack:eCe,SquareTerminal:uO,SquareUser:mO,SquareUserRound:hO,SquareX:fO,Squircle:tCe,Squirrel:sCe,Stamp:nCe,Star:ei,StarHalf:rCe,StarOff:aCe,StepBack:iCe,StepForward:oCe,Stethoscope:lCe,Sticker:cCe,StickyNote:Xz,Store:eV,StretchHorizontal:dCe,StretchVertical:uCe,Strikethrough:XJ,Subscript:hCe,Sun:JN,SunDim:mCe,SunMedium:fCe,SunMoon:pCe,SunSnow:gCe,Sunrise:xCe,Sunset:yCe,Superscript:vCe,SwatchBook:bCe,SwissFranc:_Ce,SwitchCamera:wCe,Sword:jCe,Swords:NCe,Syringe:kCe,Table:sV,Table2:tV,TableCellsMerge:SCe,TableCellsSplit:CCe,TableColumnsSplit:ACe,TableOfContents:ECe,TableProperties:TCe,TableRowsSplit:MCe,Tablet:nV,TabletSmartphone:PCe,Tablets:ICe,Tag:Cp,Tags:QJ,Tally1:LCe,Tally2:RCe,Tally3:DCe,Tally4:FCe,Tally5:OCe,Tangent:zCe,Target:ph,Telescope:BCe,Tent:UCe,TentTree:$Ce,Terminal:qCe,TestTube:VCe,TestTubeDiagonal:pO,TestTubes:HCe,Text:YCe,TextCursor:GCe,TextCursorInput:rV,TextQuote:WCe,TextSearch:KCe,TextSelect:gO,Theater:ZCe,Thermometer:JCe,ThermometerSnowflake:XCe,ThermometerSun:QCe,ThumbsDown:JJ,ThumbsUp:$y,Ticket:Qz,TicketCheck:e5e,TicketMinus:t5e,TicketPercent:s5e,TicketPlus:n5e,TicketSlash:r5e,TicketX:a5e,Tickets:o5e,TicketsPlane:i5e,Timer:d5e,TimerOff:l5e,TimerReset:c5e,ToggleLeft:u5e,ToggleRight:h5e,Toilet:m5e,Tornado:f5e,Torus:p5e,Touchpad:x5e,TouchpadOff:g5e,TowerControl:y5e,ToyBrick:v5e,Tractor:b5e,TrafficCone:_5e,TrainFront:j5e,TrainFrontTunnel:w5e,TrainTrack:N5e,TramFront:xO,Trash:k5e,Trash2:qn,TreeDeciduous:S5e,TreePalm:yO,TreePine:QI,Trees:C5e,Trello:A5e,TrendingDown:tC,TrendingUp:Zl,TrendingUpDown:E5e,Triangle:M5e,TriangleAlert:Al,TriangleRight:T5e,Trophy:Kl,Truck:eee,Turtle:P5e,Tv:L5e,TvMinimal:vO,TvMinimalPlay:I5e,Twitch:R5e,Twitter:tee,Type:aV,TypeOutline:D5e,Umbrella:O5e,UmbrellaOff:F5e,Underline:Jz,Undo:FE,Undo2:see,UndoDot:z5e,UnfoldHorizontal:B5e,UnfoldVertical:$5e,Ungroup:U5e,University:bO,Unlink:e7,Unlink2:q5e,Unplug:iV,Upload:ni,Usb:V5e,User:sl,UserCheck:u2,UserCog:nee,UserMinus:oV,UserPen:H5e,UserPlus:lc,UserRound:rP,UserRoundCheck:nP,UserRoundCog:_O,UserRoundMinus:wO,UserRoundPen:G5e,UserRoundPlus:jO,UserRoundSearch:lV,UserRoundX:NO,UserSearch:W5e,UserX:cV,Users:Yn,UsersRound:x0,Utensils:SO,UtensilsCrossed:kO,UtilityPole:K5e,Variable:dV,Vault:Y5e,Vegan:Z5e,VenetianMask:X5e,Vibrate:J5e,VibrateOff:Q5e,Video:fa,VideoOff:e4e,Videotape:t4e,View:s4e,Voicemail:n4e,Volleyball:r4e,Volume:o4e,Volume1:a4e,Volume2:ree,VolumeOff:i4e,VolumeX:aee,Vote:l4e,Wallet:t7,WalletCards:c4e,WalletMinimal:CO,Wallpaper:d4e,Wand:u4e,WandSparkles:Qx,Warehouse:h4e,WashingMachine:m4e,Watch:f4e,Waves:p4e,Waypoints:g4e,Webcam:x4e,Webhook:v4e,WebhookOff:y4e,Weight:b4e,Wheat:w4e,WheatOff:_4e,WholeWord:j4e,Wifi:A4e,WifiHigh:N4e,WifiLow:k4e,WifiOff:S4e,WifiZero:C4e,Wind:T4e,WindArrowDown:E4e,Wine:P4e,WineOff:M4e,Workflow:s7,Worm:I4e,WrapText:L4e,Wrench:I4,X:mr,Youtube:uV,Zap:Qp,ZapOff:R4e,ZoomIn:JI,ZoomOut:hV},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 zIe=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:pme,AArrowDownIcon:pme,AArrowUp:gme,AArrowUpIcon:gme,ALargeSmall:xme,ALargeSmallIcon:xme,Accessibility:yme,AccessibilityIcon:yme,Activity:rf,ActivityIcon:rf,ActivitySquare:yF,ActivitySquareIcon:yF,AirVent:vme,AirVentIcon:vme,Airplay:bme,AirplayIcon:bme,AlarmCheck:ER,AlarmCheckIcon:ER,AlarmClock:wme,AlarmClockCheck:ER,AlarmClockCheckIcon:ER,AlarmClockIcon:wme,AlarmClockMinus:TR,AlarmClockMinusIcon:TR,AlarmClockOff:_me,AlarmClockOffIcon:_me,AlarmClockPlus:MR,AlarmClockPlusIcon:MR,AlarmMinus:TR,AlarmMinusIcon:TR,AlarmPlus:MR,AlarmPlusIcon:MR,AlarmSmoke:jme,AlarmSmokeIcon:jme,Album:Nme,AlbumIcon:Nme,AlertCircle:vl,AlertCircleIcon:vl,AlertOctagon:FS,AlertOctagonIcon:FS,AlertTriangle:Al,AlertTriangleIcon:Al,AlignCenter:LI,AlignCenterHorizontal:kme,AlignCenterHorizontalIcon:kme,AlignCenterIcon:LI,AlignCenterVertical:Sme,AlignCenterVerticalIcon:Sme,AlignEndHorizontal:Cme,AlignEndHorizontalIcon:Cme,AlignEndVertical:Ame,AlignEndVerticalIcon:Ame,AlignHorizontalDistributeCenter:Eme,AlignHorizontalDistributeCenterIcon:Eme,AlignHorizontalDistributeEnd:Tme,AlignHorizontalDistributeEndIcon:Tme,AlignHorizontalDistributeStart:Mme,AlignHorizontalDistributeStartIcon:Mme,AlignHorizontalJustifyCenter:Pme,AlignHorizontalJustifyCenterIcon:Pme,AlignHorizontalJustifyEnd:Ime,AlignHorizontalJustifyEndIcon:Ime,AlignHorizontalJustifyStart:Lme,AlignHorizontalJustifyStartIcon:Lme,AlignHorizontalSpaceAround:Rme,AlignHorizontalSpaceAroundIcon:Rme,AlignHorizontalSpaceBetween:Dme,AlignHorizontalSpaceBetweenIcon:Dme,AlignJustify:Fme,AlignJustifyIcon:Fme,AlignLeft:RI,AlignLeftIcon:RI,AlignRight:DI,AlignRightIcon:DI,AlignStartHorizontal:Ome,AlignStartHorizontalIcon:Ome,AlignStartVertical:zme,AlignStartVerticalIcon:zme,AlignVerticalDistributeCenter:Bme,AlignVerticalDistributeCenterIcon:Bme,AlignVerticalDistributeEnd:$me,AlignVerticalDistributeEndIcon:$me,AlignVerticalDistributeStart:Ume,AlignVerticalDistributeStartIcon:Ume,AlignVerticalJustifyCenter:qme,AlignVerticalJustifyCenterIcon:qme,AlignVerticalJustifyEnd:Vme,AlignVerticalJustifyEndIcon:Vme,AlignVerticalJustifyStart:Hme,AlignVerticalJustifyStartIcon:Hme,AlignVerticalSpaceAround:Gme,AlignVerticalSpaceAroundIcon:Gme,AlignVerticalSpaceBetween:Wme,AlignVerticalSpaceBetweenIcon:Wme,Ambulance:Kme,AmbulanceIcon:Kme,Ampersand:Yme,AmpersandIcon:Yme,Ampersands:Zme,AmpersandsIcon:Zme,Amphora:Xme,AmphoraIcon:Xme,Anchor:Qme,AnchorIcon:Qme,Angry:Jme,AngryIcon:Jme,Annoyed:efe,AnnoyedIcon:efe,Antenna:tfe,AntennaIcon:tfe,Anvil:sfe,AnvilIcon:sfe,Aperture:nfe,ApertureIcon:nfe,AppWindow:afe,AppWindowIcon:afe,AppWindowMac:rfe,AppWindowMacIcon:rfe,Apple:ife,AppleIcon:ife,Archive:wv,ArchiveIcon:wv,ArchiveRestore:FI,ArchiveRestoreIcon:FI,ArchiveX:ofe,ArchiveXIcon:ofe,AreaChart:qR,AreaChartIcon:qR,Armchair:lfe,ArmchairIcon:lfe,ArrowBigDown:dfe,ArrowBigDownDash:cfe,ArrowBigDownDashIcon:cfe,ArrowBigDownIcon:dfe,ArrowBigLeft:hfe,ArrowBigLeftDash:ufe,ArrowBigLeftDashIcon:ufe,ArrowBigLeftIcon:hfe,ArrowBigRight:ffe,ArrowBigRightDash:mfe,ArrowBigRightDashIcon:mfe,ArrowBigRightIcon:ffe,ArrowBigUp:gfe,ArrowBigUpDash:pfe,ArrowBigUpDashIcon:pfe,ArrowBigUpIcon:gfe,ArrowDown:Lg,ArrowDown01:xfe,ArrowDown01Icon:xfe,ArrowDown10:yfe,ArrowDown10Icon:yfe,ArrowDownAZ:PR,ArrowDownAZIcon:PR,ArrowDownAz:PR,ArrowDownAzIcon:PR,ArrowDownCircle:tD,ArrowDownCircleIcon:tD,ArrowDownFromLine:vfe,ArrowDownFromLineIcon:vfe,ArrowDownIcon:Lg,ArrowDownLeft:bfe,ArrowDownLeftFromCircle:nD,ArrowDownLeftFromCircleIcon:nD,ArrowDownLeftFromSquare:jF,ArrowDownLeftFromSquareIcon:jF,ArrowDownLeftIcon:bfe,ArrowDownLeftSquare:vF,ArrowDownLeftSquareIcon:vF,ArrowDownNarrowWide:_fe,ArrowDownNarrowWideIcon:_fe,ArrowDownRight:lJ,ArrowDownRightFromCircle:rD,ArrowDownRightFromCircleIcon:rD,ArrowDownRightFromSquare:NF,ArrowDownRightFromSquareIcon:NF,ArrowDownRightIcon:lJ,ArrowDownRightSquare:bF,ArrowDownRightSquareIcon:bF,ArrowDownSquare:_F,ArrowDownSquareIcon:_F,ArrowDownToDot:wfe,ArrowDownToDotIcon:wfe,ArrowDownToLine:jfe,ArrowDownToLineIcon:jfe,ArrowDownUp:Nfe,ArrowDownUpIcon:Nfe,ArrowDownWideNarrow:IR,ArrowDownWideNarrowIcon:IR,ArrowDownZA:LR,ArrowDownZAIcon:LR,ArrowDownZa:LR,ArrowDownZaIcon:LR,ArrowLeft:Va,ArrowLeftCircle:sD,ArrowLeftCircleIcon:sD,ArrowLeftFromLine:kfe,ArrowLeftFromLineIcon:kfe,ArrowLeftIcon:Va,ArrowLeftRight:cJ,ArrowLeftRightIcon:cJ,ArrowLeftSquare:wF,ArrowLeftSquareIcon:wF,ArrowLeftToLine:Sfe,ArrowLeftToLineIcon:Sfe,ArrowRight:Qa,ArrowRightCircle:oD,ArrowRightCircleIcon:oD,ArrowRightFromLine:Cfe,ArrowRightFromLineIcon:Cfe,ArrowRightIcon:Qa,ArrowRightLeft:S4,ArrowRightLeftIcon:S4,ArrowRightSquare:CF,ArrowRightSquareIcon:CF,ArrowRightToLine:Afe,ArrowRightToLineIcon:Afe,ArrowUp:Zf,ArrowUp01:Efe,ArrowUp01Icon:Efe,ArrowUp10:Tfe,ArrowUp10Icon:Tfe,ArrowUpAZ:RR,ArrowUpAZIcon:RR,ArrowUpAz:RR,ArrowUpAzIcon:RR,ArrowUpCircle:lD,ArrowUpCircleIcon:lD,ArrowUpDown:Dy,ArrowUpDownIcon:Dy,ArrowUpFromDot:Mfe,ArrowUpFromDotIcon:Mfe,ArrowUpFromLine:Pfe,ArrowUpFromLineIcon:Pfe,ArrowUpIcon:Zf,ArrowUpLeft:Ife,ArrowUpLeftFromCircle:aD,ArrowUpLeftFromCircleIcon:aD,ArrowUpLeftFromSquare:kF,ArrowUpLeftFromSquareIcon:kF,ArrowUpLeftIcon:Ife,ArrowUpLeftSquare:AF,ArrowUpLeftSquareIcon:AF,ArrowUpNarrowWide:DR,ArrowUpNarrowWideIcon:DR,ArrowUpRight:Mz,ArrowUpRightFromCircle:iD,ArrowUpRightFromCircleIcon:iD,ArrowUpRightFromSquare:SF,ArrowUpRightFromSquareIcon:SF,ArrowUpRightIcon:Mz,ArrowUpRightSquare:EF,ArrowUpRightSquareIcon:EF,ArrowUpSquare:TF,ArrowUpSquareIcon:TF,ArrowUpToLine:Lfe,ArrowUpToLineIcon:Lfe,ArrowUpWideNarrow:Rfe,ArrowUpWideNarrowIcon:Rfe,ArrowUpZA:FR,ArrowUpZAIcon:FR,ArrowUpZa:FR,ArrowUpZaIcon:FR,ArrowsUpFromLine:Dfe,ArrowsUpFromLineIcon:Dfe,Asterisk:Ffe,AsteriskIcon:Ffe,AsteriskSquare:MF,AsteriskSquareIcon:MF,AtSign:Ofe,AtSignIcon:Ofe,Atom:zfe,AtomIcon:zfe,AudioLines:Bfe,AudioLinesIcon:Bfe,AudioWaveform:$fe,AudioWaveformIcon:$fe,Award:Im,AwardIcon:Im,Axe:Ufe,AxeIcon:Ufe,Axis3D:OR,Axis3DIcon:OR,Axis3d:OR,Axis3dIcon:OR,Baby:qfe,BabyIcon:qfe,Backpack:Vfe,BackpackIcon:Vfe,Badge:ipe,BadgeAlert:Hfe,BadgeAlertIcon:Hfe,BadgeCent:Gfe,BadgeCentIcon:Gfe,BadgeCheck:PA,BadgeCheckIcon:PA,BadgeDollarSign:Wfe,BadgeDollarSignIcon:Wfe,BadgeEuro:Kfe,BadgeEuroIcon:Kfe,BadgeHelp:Yfe,BadgeHelpIcon:Yfe,BadgeIcon:ipe,BadgeIndianRupee:Zfe,BadgeIndianRupeeIcon:Zfe,BadgeInfo:Xfe,BadgeInfoIcon:Xfe,BadgeJapaneseYen:Qfe,BadgeJapaneseYenIcon:Qfe,BadgeMinus:Jfe,BadgeMinusIcon:Jfe,BadgePercent:epe,BadgePercentIcon:epe,BadgePlus:tpe,BadgePlusIcon:tpe,BadgePoundSterling:spe,BadgePoundSterlingIcon:spe,BadgeRussianRuble:npe,BadgeRussianRubleIcon:npe,BadgeSwissFranc:rpe,BadgeSwissFrancIcon:rpe,BadgeX:ape,BadgeXIcon:ape,BaggageClaim:ope,BaggageClaimIcon:ope,Ban:Pz,BanIcon:Pz,Banana:lpe,BananaIcon:lpe,Bandage:cpe,BandageIcon:cpe,Banknote:dpe,BanknoteIcon:dpe,BarChart:ZR,BarChart2:XR,BarChart2Icon:XR,BarChart3:Gl,BarChart3Icon:Gl,BarChart4:KR,BarChart4Icon:KR,BarChartBig:WR,BarChartBigIcon:WR,BarChartHorizontal:HR,BarChartHorizontalBig:VR,BarChartHorizontalBigIcon:VR,BarChartHorizontalIcon:HR,BarChartIcon:ZR,Barcode:upe,BarcodeIcon:upe,Baseline:hpe,BaselineIcon:hpe,Bath:C0,BathIcon:C0,Battery:ype,BatteryCharging:mpe,BatteryChargingIcon:mpe,BatteryFull:fpe,BatteryFullIcon:fpe,BatteryIcon:ype,BatteryLow:ppe,BatteryLowIcon:ppe,BatteryMedium:gpe,BatteryMediumIcon:gpe,BatteryWarning:xpe,BatteryWarningIcon:xpe,Beaker:dJ,BeakerIcon:dJ,Bean:bpe,BeanIcon:bpe,BeanOff:vpe,BeanOffIcon:vpe,Bed:n2,BedDouble:C4,BedDoubleIcon:C4,BedIcon:n2,BedSingle:_pe,BedSingleIcon:_pe,Beef:wpe,BeefIcon:wpe,Beer:Npe,BeerIcon:Npe,BeerOff:jpe,BeerOffIcon:jpe,Bell:zy,BellDot:kpe,BellDotIcon:kpe,BellElectric:Spe,BellElectricIcon:Spe,BellIcon:zy,BellMinus:Cpe,BellMinusIcon:Cpe,BellOff:KS,BellOffIcon:KS,BellPlus:Ape,BellPlusIcon:Ape,BellRing:YS,BellRingIcon:YS,BetweenHorizonalEnd:zR,BetweenHorizonalEndIcon:zR,BetweenHorizonalStart:BR,BetweenHorizonalStartIcon:BR,BetweenHorizontalEnd:zR,BetweenHorizontalEndIcon:zR,BetweenHorizontalStart:BR,BetweenHorizontalStartIcon:BR,BetweenVerticalEnd:Epe,BetweenVerticalEndIcon:Epe,BetweenVerticalStart:Tpe,BetweenVerticalStartIcon:Tpe,BicepsFlexed:Mpe,BicepsFlexedIcon:Mpe,Bike:Ppe,BikeIcon:Ppe,Binary:Ipe,BinaryIcon:Ipe,Binoculars:Lpe,BinocularsIcon:Lpe,Biohazard:Rpe,BiohazardIcon:Rpe,Bird:Dpe,BirdIcon:Dpe,Bitcoin:Fpe,BitcoinIcon:Fpe,Blend:Ope,BlendIcon:Ope,Blinds:zpe,BlindsIcon:zpe,Blocks:Bpe,BlocksIcon:Bpe,Bluetooth:Vpe,BluetoothConnected:$pe,BluetoothConnectedIcon:$pe,BluetoothIcon:Vpe,BluetoothOff:Upe,BluetoothOffIcon:Upe,BluetoothSearching:qpe,BluetoothSearchingIcon:qpe,Bold:kE,BoldIcon:kE,Bolt:Hpe,BoltIcon:Hpe,Bomb:Gpe,BombIcon:Gpe,Bone:Wpe,BoneIcon:Wpe,Book:pge,BookA:Kpe,BookAIcon:Kpe,BookAudio:Ype,BookAudioIcon:Ype,BookCheck:Zpe,BookCheckIcon:Zpe,BookCopy:Xpe,BookCopyIcon:Xpe,BookDashed:$R,BookDashedIcon:$R,BookDown:Qpe,BookDownIcon:Qpe,BookHeadphones:Jpe,BookHeadphonesIcon:Jpe,BookHeart:ege,BookHeartIcon:ege,BookIcon:pge,BookImage:tge,BookImageIcon:tge,BookKey:sge,BookKeyIcon:sge,BookLock:nge,BookLockIcon:nge,BookMarked:rge,BookMarkedIcon:rge,BookMinus:age,BookMinusIcon:age,BookOpen:_x,BookOpenCheck:ige,BookOpenCheckIcon:ige,BookOpenIcon:_x,BookOpenText:oge,BookOpenTextIcon:oge,BookPlus:lge,BookPlusIcon:lge,BookTemplate:$R,BookTemplateIcon:$R,BookText:cge,BookTextIcon:cge,BookType:dge,BookTypeIcon:dge,BookUp:hge,BookUp2:uge,BookUp2Icon:uge,BookUpIcon:hge,BookUser:mge,BookUserIcon:mge,BookX:fge,BookXIcon:fge,Bookmark:A0,BookmarkCheck:gge,BookmarkCheckIcon:gge,BookmarkIcon:A0,BookmarkMinus:xge,BookmarkMinusIcon:xge,BookmarkPlus:OI,BookmarkPlusIcon:OI,BookmarkX:yge,BookmarkXIcon:yge,BoomBox:vge,BoomBoxIcon:vge,Bot:A4,BotIcon:A4,BotMessageSquare:bge,BotMessageSquareIcon:bge,BotOff:_ge,BotOffIcon:_ge,Box:uJ,BoxIcon:uJ,BoxSelect:$F,BoxSelectIcon:$F,Boxes:wge,BoxesIcon:wge,Braces:eP,BracesIcon:eP,Brackets:jge,BracketsIcon:jge,Brain:hJ,BrainCircuit:Nge,BrainCircuitIcon:Nge,BrainCog:kge,BrainCogIcon:kge,BrainIcon:hJ,BrickWall:Sge,BrickWallIcon:Sge,Briefcase:wx,BriefcaseBusiness:Cge,BriefcaseBusinessIcon:Cge,BriefcaseConveyorBelt:Age,BriefcaseConveyorBeltIcon:Age,BriefcaseIcon:wx,BriefcaseMedical:Ege,BriefcaseMedicalIcon:Ege,BringToFront:Tge,BringToFrontIcon:Tge,Brush:Mge,BrushIcon:Mge,Bug:Lge,BugIcon:Lge,BugOff:Pge,BugOffIcon:Pge,BugPlay:Ige,BugPlayIcon:Ige,Building:zI,Building2:wi,Building2Icon:wi,BuildingIcon:zI,Bus:Dge,BusFront:Rge,BusFrontIcon:Rge,BusIcon:Dge,Cable:Oge,CableCar:Fge,CableCarIcon:Fge,CableIcon:Oge,Cake:Rg,CakeIcon:Rg,CakeSlice:zge,CakeSliceIcon:zge,Calculator:r2,CalculatorIcon:r2,Calendar:Ea,Calendar1:Bge,Calendar1Icon:Bge,CalendarArrowDown:$ge,CalendarArrowDownIcon:$ge,CalendarArrowUp:Uge,CalendarArrowUpIcon:Uge,CalendarCheck:gb,CalendarCheck2:qge,CalendarCheck2Icon:qge,CalendarCheckIcon:gb,CalendarClock:Su,CalendarClockIcon:Su,CalendarCog:Vge,CalendarCogIcon:Vge,CalendarDays:Wc,CalendarDaysIcon:Wc,CalendarFold:Hge,CalendarFoldIcon:Hge,CalendarHeart:ZS,CalendarHeartIcon:ZS,CalendarIcon:Ea,CalendarMinus:Wge,CalendarMinus2:Gge,CalendarMinus2Icon:Gge,CalendarMinusIcon:Wge,CalendarOff:jq,CalendarOffIcon:jq,CalendarPlus:vv,CalendarPlus2:Kge,CalendarPlus2Icon:Kge,CalendarPlusIcon:vv,CalendarRange:Yge,CalendarRangeIcon:Yge,CalendarSearch:Zge,CalendarSearchIcon:Zge,CalendarSync:Xge,CalendarSyncIcon:Xge,CalendarX:mJ,CalendarX2:Qge,CalendarX2Icon:Qge,CalendarXIcon:mJ,Camera:jx,CameraIcon:jx,CameraOff:Jge,CameraOffIcon:Jge,CandlestickChart:GR,CandlestickChartIcon:GR,Candy:sxe,CandyCane:exe,CandyCaneIcon:exe,CandyIcon:sxe,CandyOff:txe,CandyOffIcon:txe,Cannabis:nxe,CannabisIcon:nxe,Captions:UR,CaptionsIcon:UR,CaptionsOff:rxe,CaptionsOffIcon:rxe,Car:oxe,CarFront:axe,CarFrontIcon:axe,CarIcon:oxe,CarTaxiFront:ixe,CarTaxiFrontIcon:ixe,Caravan:lxe,CaravanIcon:lxe,Carrot:cxe,CarrotIcon:cxe,CaseLower:dxe,CaseLowerIcon:dxe,CaseSensitive:uxe,CaseSensitiveIcon:uxe,CaseUpper:hxe,CaseUpperIcon:hxe,CassetteTape:mxe,CassetteTapeIcon:mxe,Cast:fxe,CastIcon:fxe,Castle:pxe,CastleIcon:pxe,Cat:gxe,CatIcon:gxe,Cctv:xxe,CctvIcon:xxe,ChartArea:qR,ChartAreaIcon:qR,ChartBar:HR,ChartBarBig:VR,ChartBarBigIcon:VR,ChartBarDecreasing:yxe,ChartBarDecreasingIcon:yxe,ChartBarIcon:HR,ChartBarIncreasing:vxe,ChartBarIncreasingIcon:vxe,ChartBarStacked:bxe,ChartBarStackedIcon:bxe,ChartCandlestick:GR,ChartCandlestickIcon:GR,ChartColumn:Gl,ChartColumnBig:WR,ChartColumnBigIcon:WR,ChartColumnDecreasing:_xe,ChartColumnDecreasingIcon:_xe,ChartColumnIcon:Gl,ChartColumnIncreasing:KR,ChartColumnIncreasingIcon:KR,ChartColumnStacked:wxe,ChartColumnStackedIcon:wxe,ChartGantt:jxe,ChartGanttIcon:jxe,ChartLine:YR,ChartLineIcon:YR,ChartNetwork:Nxe,ChartNetworkIcon:Nxe,ChartNoAxesColumn:XR,ChartNoAxesColumnDecreasing:kxe,ChartNoAxesColumnDecreasingIcon:kxe,ChartNoAxesColumnIcon:XR,ChartNoAxesColumnIncreasing:ZR,ChartNoAxesColumnIncreasingIcon:ZR,ChartNoAxesCombined:Sxe,ChartNoAxesCombinedIcon:Sxe,ChartNoAxesGantt:QR,ChartNoAxesGanttIcon:QR,ChartPie:JR,ChartPieIcon:JR,ChartScatter:eD,ChartScatterIcon:eD,ChartSpline:Cxe,ChartSplineIcon:Cxe,Check:ma,CheckCheck:Iz,CheckCheckIcon:Iz,CheckCircle:Wl,CheckCircle2:Vr,CheckCircle2Icon:Vr,CheckCircleIcon:Wl,CheckIcon:ma,CheckSquare:qj,CheckSquare2:IF,CheckSquare2Icon:IF,CheckSquareIcon:qj,ChefHat:Axe,ChefHatIcon:Axe,Cherry:Exe,CherryIcon:Exe,ChevronDown:wl,ChevronDownCircle:cD,ChevronDownCircleIcon:cD,ChevronDownIcon:wl,ChevronDownSquare:LF,ChevronDownSquareIcon:LF,ChevronFirst:Txe,ChevronFirstIcon:Txe,ChevronLast:Mxe,ChevronLastIcon:Mxe,ChevronLeft:kd,ChevronLeftCircle:dD,ChevronLeftCircleIcon:dD,ChevronLeftIcon:kd,ChevronLeftSquare:RF,ChevronLeftSquareIcon:RF,ChevronRight:Di,ChevronRightCircle:uD,ChevronRightCircleIcon:uD,ChevronRightIcon:Di,ChevronRightSquare:DF,ChevronRightSquareIcon:DF,ChevronUp:xb,ChevronUpCircle:hD,ChevronUpCircleIcon:hD,ChevronUpIcon:xb,ChevronUpSquare:FF,ChevronUpSquareIcon:FF,ChevronsDown:Ixe,ChevronsDownIcon:Ixe,ChevronsDownUp:Pxe,ChevronsDownUpIcon:Pxe,ChevronsLeft:Dxe,ChevronsLeftIcon:Dxe,ChevronsLeftRight:Rxe,ChevronsLeftRightEllipsis:Lxe,ChevronsLeftRightEllipsisIcon:Lxe,ChevronsLeftRightIcon:Rxe,ChevronsRight:Oxe,ChevronsRightIcon:Oxe,ChevronsRightLeft:Fxe,ChevronsRightLeftIcon:Fxe,ChevronsUp:zxe,ChevronsUpDown:kw,ChevronsUpDownIcon:kw,ChevronsUpIcon:zxe,Chrome:Lz,ChromeIcon:Lz,Church:Bxe,ChurchIcon:Bxe,Cigarette:Uxe,CigaretteIcon:Uxe,CigaretteOff:$xe,CigaretteOffIcon:$xe,Circle:Dg,CircleAlert:vl,CircleAlertIcon:vl,CircleArrowDown:tD,CircleArrowDownIcon:tD,CircleArrowLeft:sD,CircleArrowLeftIcon:sD,CircleArrowOutDownLeft:nD,CircleArrowOutDownLeftIcon:nD,CircleArrowOutDownRight:rD,CircleArrowOutDownRightIcon:rD,CircleArrowOutUpLeft:aD,CircleArrowOutUpLeftIcon:aD,CircleArrowOutUpRight:iD,CircleArrowOutUpRightIcon:iD,CircleArrowRight:oD,CircleArrowRightIcon:oD,CircleArrowUp:lD,CircleArrowUpIcon:lD,CircleCheck:Vr,CircleCheckBig:Wl,CircleCheckBigIcon:Wl,CircleCheckIcon:Vr,CircleChevronDown:cD,CircleChevronDownIcon:cD,CircleChevronLeft:dD,CircleChevronLeftIcon:dD,CircleChevronRight:uD,CircleChevronRightIcon:uD,CircleChevronUp:hD,CircleChevronUpIcon:hD,CircleDashed:qxe,CircleDashedIcon:qxe,CircleDivide:mD,CircleDivideIcon:mD,CircleDollarSign:Vxe,CircleDollarSignIcon:Vxe,CircleDot:Gxe,CircleDotDashed:Hxe,CircleDotDashedIcon:Hxe,CircleDotIcon:Gxe,CircleEllipsis:Wxe,CircleEllipsisIcon:Wxe,CircleEqual:Kxe,CircleEqualIcon:Kxe,CircleFadingArrowUp:Yxe,CircleFadingArrowUpIcon:Yxe,CircleFadingPlus:Zxe,CircleFadingPlusIcon:Zxe,CircleGauge:fD,CircleGaugeIcon:fD,CircleHelp:J5,CircleHelpIcon:J5,CircleIcon:Dg,CircleMinus:pD,CircleMinusIcon:pD,CircleOff:Xxe,CircleOffIcon:Xxe,CircleParking:xD,CircleParkingIcon:xD,CircleParkingOff:gD,CircleParkingOffIcon:gD,CirclePause:yD,CirclePauseIcon:yD,CirclePercent:vD,CirclePercentIcon:vD,CirclePlay:ef,CirclePlayIcon:ef,CirclePlus:bD,CirclePlusIcon:bD,CirclePower:_D,CirclePowerIcon:_D,CircleSlash:Qxe,CircleSlash2:wD,CircleSlash2Icon:wD,CircleSlashIcon:Qxe,CircleSlashed:wD,CircleSlashedIcon:wD,CircleStop:jD,CircleStopIcon:jD,CircleUser:kD,CircleUserIcon:kD,CircleUserRound:ND,CircleUserRoundIcon:ND,CircleX:ju,CircleXIcon:ju,CircuitBoard:Jxe,CircuitBoardIcon:Jxe,Citrus:eye,CitrusIcon:eye,Clapperboard:Nq,ClapperboardIcon:Nq,Clipboard:oye,ClipboardCheck:GN,ClipboardCheckIcon:GN,ClipboardCopy:tye,ClipboardCopyIcon:tye,ClipboardEdit:CD,ClipboardEditIcon:CD,ClipboardIcon:oye,ClipboardList:Fg,ClipboardListIcon:Fg,ClipboardMinus:sye,ClipboardMinusIcon:sye,ClipboardPaste:nye,ClipboardPasteIcon:nye,ClipboardPen:CD,ClipboardPenIcon:CD,ClipboardPenLine:SD,ClipboardPenLineIcon:SD,ClipboardPlus:rye,ClipboardPlusIcon:rye,ClipboardSignature:SD,ClipboardSignatureIcon:SD,ClipboardType:aye,ClipboardTypeIcon:aye,ClipboardX:iye,ClipboardXIcon:iye,Clock:ca,Clock1:lye,Clock10:cye,Clock10Icon:cye,Clock11:dye,Clock11Icon:dye,Clock12:uye,Clock12Icon:uye,Clock1Icon:lye,Clock2:hye,Clock2Icon:hye,Clock3:kq,Clock3Icon:kq,Clock4:mye,Clock4Icon:mye,Clock5:fye,Clock5Icon:fye,Clock6:pye,Clock6Icon:pye,Clock7:gye,Clock7Icon:gye,Clock8:xye,Clock8Icon:xye,Clock9:yye,Clock9Icon:yye,ClockAlert:vye,ClockAlertIcon:vye,ClockArrowDown:bye,ClockArrowDownIcon:bye,ClockArrowUp:_ye,ClockArrowUpIcon:_ye,ClockIcon:ca,Cloud:Dye,CloudAlert:wye,CloudAlertIcon:wye,CloudCog:jye,CloudCogIcon:jye,CloudDownload:AD,CloudDownloadIcon:AD,CloudDrizzle:Nye,CloudDrizzleIcon:Nye,CloudFog:kye,CloudFogIcon:kye,CloudHail:Sye,CloudHailIcon:Sye,CloudIcon:Dye,CloudLightning:Cye,CloudLightningIcon:Cye,CloudMoon:Eye,CloudMoonIcon:Eye,CloudMoonRain:Aye,CloudMoonRainIcon:Aye,CloudOff:Tye,CloudOffIcon:Tye,CloudRain:Pye,CloudRainIcon:Pye,CloudRainWind:Mye,CloudRainWindIcon:Mye,CloudSnow:Iye,CloudSnowIcon:Iye,CloudSun:Rye,CloudSunIcon:Rye,CloudSunRain:Lye,CloudSunRainIcon:Lye,CloudUpload:tP,CloudUploadIcon:tP,Cloudy:Fye,CloudyIcon:Fye,Clover:pE,CloverIcon:pE,Club:Oye,ClubIcon:Oye,Code:SE,Code2:e4,Code2Icon:e4,CodeIcon:SE,CodeSquare:OF,CodeSquareIcon:OF,CodeXml:e4,CodeXmlIcon:e4,Codepen:zye,CodepenIcon:zye,Codesandbox:Bye,CodesandboxIcon:Bye,Coffee:E4,CoffeeIcon:E4,Cog:$ye,CogIcon:$ye,Coins:fJ,CoinsIcon:fJ,Columns:ED,Columns2:ED,Columns2Icon:ED,Columns3:sP,Columns3Icon:sP,Columns4:Uye,Columns4Icon:Uye,ColumnsIcon:ED,Combine:qye,CombineIcon:qye,Command:Vye,CommandIcon:Vye,Compass:Rz,CompassIcon:Rz,Component:Hye,ComponentIcon:Hye,Computer:Gye,ComputerIcon:Gye,ConciergeBell:Wye,ConciergeBellIcon:Wye,Cone:Kye,ConeIcon:Kye,Construction:Yye,ConstructionIcon:Yye,Contact:BI,Contact2:TD,Contact2Icon:TD,ContactIcon:BI,ContactRound:TD,ContactRoundIcon:TD,Container:Zye,ContainerIcon:Zye,Contrast:Xye,ContrastIcon:Xye,Cookie:Qye,CookieIcon:Qye,CookingPot:Jye,CookingPotIcon:Jye,Copy:Za,CopyCheck:e0e,CopyCheckIcon:e0e,CopyIcon:Za,CopyMinus:t0e,CopyMinusIcon:t0e,CopyPlus:s0e,CopyPlusIcon:s0e,CopySlash:n0e,CopySlashIcon:n0e,CopyX:r0e,CopyXIcon:r0e,Copyleft:a0e,CopyleftIcon:a0e,Copyright:i0e,CopyrightIcon:i0e,CornerDownLeft:o0e,CornerDownLeftIcon:o0e,CornerDownRight:pJ,CornerDownRightIcon:pJ,CornerLeftDown:l0e,CornerLeftDownIcon:l0e,CornerLeftUp:c0e,CornerLeftUpIcon:c0e,CornerRightDown:d0e,CornerRightDownIcon:d0e,CornerRightUp:u0e,CornerRightUpIcon:u0e,CornerUpLeft:h0e,CornerUpLeftIcon:h0e,CornerUpRight:m0e,CornerUpRightIcon:m0e,Cpu:f0e,CpuIcon:f0e,CreativeCommons:p0e,CreativeCommonsIcon:p0e,CreditCard:jv,CreditCardIcon:jv,Croissant:g0e,CroissantIcon:g0e,Crop:x0e,CropIcon:x0e,Cross:y0e,CrossIcon:y0e,Crosshair:v0e,CrosshairIcon:v0e,Crown:Og,CrownIcon:Og,Cuboid:b0e,CuboidIcon:b0e,CupSoda:_0e,CupSodaIcon:_0e,CurlyBraces:eP,CurlyBracesIcon:eP,Currency:w0e,CurrencyIcon:w0e,Cylinder:j0e,CylinderIcon:j0e,Dam:N0e,DamIcon:N0e,Database:Sq,DatabaseBackup:k0e,DatabaseBackupIcon:k0e,DatabaseIcon:Sq,DatabaseZap:S0e,DatabaseZapIcon:S0e,Delete:C0e,DeleteIcon:C0e,Dessert:A0e,DessertIcon:A0e,Diameter:E0e,DiameterIcon:E0e,Diamond:P0e,DiamondIcon:P0e,DiamondMinus:T0e,DiamondMinusIcon:T0e,DiamondPercent:MD,DiamondPercentIcon:MD,DiamondPlus:M0e,DiamondPlusIcon:M0e,Dice1:I0e,Dice1Icon:I0e,Dice2:L0e,Dice2Icon:L0e,Dice3:R0e,Dice3Icon:R0e,Dice4:D0e,Dice4Icon:D0e,Dice5:F0e,Dice5Icon:F0e,Dice6:O0e,Dice6Icon:O0e,Dices:z0e,DicesIcon:z0e,Diff:B0e,DiffIcon:B0e,Disc:V0e,Disc2:$0e,Disc2Icon:$0e,Disc3:U0e,Disc3Icon:U0e,DiscAlbum:q0e,DiscAlbumIcon:q0e,DiscIcon:V0e,Divide:H0e,DivideCircle:mD,DivideCircleIcon:mD,DivideIcon:H0e,DivideSquare:UF,DivideSquareIcon:UF,Dna:W0e,DnaIcon:W0e,DnaOff:G0e,DnaOffIcon:G0e,Dock:K0e,DockIcon:K0e,Dog:Y0e,DogIcon:Y0e,DollarSign:su,DollarSignIcon:su,Donut:Z0e,DonutIcon:Z0e,DoorClosed:X0e,DoorClosedIcon:X0e,DoorOpen:WN,DoorOpenIcon:WN,Dot:Q0e,DotIcon:Q0e,DotSquare:qF,DotSquareIcon:qF,Download:ji,DownloadCloud:AD,DownloadCloudIcon:AD,DownloadIcon:ji,DraftingCompass:J0e,DraftingCompassIcon:J0e,Drama:eve,DramaIcon:eve,Dribbble:tve,DribbbleIcon:tve,Drill:sve,DrillIcon:sve,Droplet:nve,DropletIcon:nve,Droplets:p1,DropletsIcon:p1,Drum:rve,DrumIcon:rve,Drumstick:ave,DrumstickIcon:ave,Dumbbell:ive,DumbbellIcon:ive,Ear:lve,EarIcon:lve,EarOff:ove,EarOffIcon:ove,Earth:kN,EarthIcon:kN,EarthLock:cve,EarthLockIcon:cve,Eclipse:dve,EclipseIcon:dve,Edit:bp,Edit2:SN,Edit2Icon:SN,Edit3:_f,Edit3Icon:_f,EditIcon:bp,Egg:Cq,EggFried:uve,EggFriedIcon:uve,EggIcon:Cq,EggOff:hve,EggOffIcon:hve,Ellipsis:o_,EllipsisIcon:o_,EllipsisVertical:Xx,EllipsisVerticalIcon:Xx,Equal:pve,EqualApproximately:mve,EqualApproximatelyIcon:mve,EqualIcon:pve,EqualNot:fve,EqualNotIcon:fve,EqualSquare:VF,EqualSquareIcon:VF,Eraser:Aq,EraserIcon:Aq,EthernetPort:gve,EthernetPortIcon:gve,Euro:xve,EuroIcon:xve,Expand:yve,ExpandIcon:yve,ExternalLink:Ir,ExternalLinkIcon:Ir,Eye:Ta,EyeClosed:vve,EyeClosedIcon:vve,EyeIcon:Ta,EyeOff:Nx,EyeOffIcon:Nx,Facebook:Zp,FacebookIcon:Zp,Factory:bve,FactoryIcon:bve,Fan:_ve,FanIcon:_ve,FastForward:wve,FastForwardIcon:wve,Feather:jve,FeatherIcon:jve,Fence:Nve,FenceIcon:Nve,FerrisWheel:kve,FerrisWheelIcon:kve,Figma:Sve,FigmaIcon:Sve,File:Tq,FileArchive:Cve,FileArchiveIcon:Cve,FileAudio:Eve,FileAudio2:Ave,FileAudio2Icon:Ave,FileAudioIcon:Eve,FileAxis3D:PD,FileAxis3DIcon:PD,FileAxis3d:PD,FileAxis3dIcon:PD,FileBadge:Mve,FileBadge2:Tve,FileBadge2Icon:Tve,FileBadgeIcon:Mve,FileBarChart:ID,FileBarChart2:LD,FileBarChart2Icon:LD,FileBarChartIcon:ID,FileBox:Pve,FileBoxIcon:Pve,FileChartColumn:LD,FileChartColumnIcon:LD,FileChartColumnIncreasing:ID,FileChartColumnIncreasingIcon:ID,FileChartLine:RD,FileChartLineIcon:RD,FileChartPie:DD,FileChartPieIcon:DD,FileCheck:gJ,FileCheck2:Dz,FileCheck2Icon:Dz,FileCheckIcon:gJ,FileClock:Ive,FileClockIcon:Ive,FileCode:Rve,FileCode2:Lve,FileCode2Icon:Lve,FileCodeIcon:Rve,FileCog:FD,FileCog2:FD,FileCog2Icon:FD,FileCogIcon:FD,FileDiff:Dve,FileDiffIcon:Dve,FileDigit:Fve,FileDigitIcon:Fve,FileDown:a2,FileDownIcon:a2,FileEdit:OD,FileEditIcon:OD,FileHeart:Ove,FileHeartIcon:Ove,FileIcon:Tq,FileImage:$I,FileImageIcon:$I,FileInput:zve,FileInputIcon:zve,FileJson:$ve,FileJson2:Bve,FileJson2Icon:Bve,FileJsonIcon:$ve,FileKey:qve,FileKey2:Uve,FileKey2Icon:Uve,FileKeyIcon:qve,FileLineChart:RD,FileLineChartIcon:RD,FileLock:Hve,FileLock2:Vve,FileLock2Icon:Vve,FileLockIcon:Hve,FileMinus:Wve,FileMinus2:Gve,FileMinus2Icon:Gve,FileMinusIcon:Wve,FileMusic:Kve,FileMusicIcon:Kve,FileOutput:Yve,FileOutputIcon:Yve,FilePen:OD,FilePenIcon:OD,FilePenLine:l_,FilePenLineIcon:l_,FilePieChart:DD,FilePieChartIcon:DD,FilePlus:Zve,FilePlus2:Eq,FilePlus2Icon:Eq,FilePlusIcon:Zve,FileQuestion:Xve,FileQuestionIcon:Xve,FileScan:Qve,FileScanIcon:Qve,FileSearch:xJ,FileSearch2:Jve,FileSearch2Icon:Jve,FileSearchIcon:xJ,FileSignature:l_,FileSignatureIcon:l_,FileSliders:ebe,FileSlidersIcon:ebe,FileSpreadsheet:KN,FileSpreadsheetIcon:KN,FileStack:yJ,FileStackIcon:yJ,FileSymlink:tbe,FileSymlinkIcon:tbe,FileTerminal:sbe,FileTerminalIcon:sbe,FileText:Qr,FileTextIcon:Qr,FileType:rbe,FileType2:nbe,FileType2Icon:nbe,FileTypeIcon:rbe,FileUp:vJ,FileUpIcon:vJ,FileUser:abe,FileUserIcon:abe,FileVideo:bJ,FileVideo2:ibe,FileVideo2Icon:ibe,FileVideoIcon:bJ,FileVolume:lbe,FileVolume2:obe,FileVolume2Icon:obe,FileVolumeIcon:lbe,FileWarning:cbe,FileWarningIcon:cbe,FileX:ube,FileX2:dbe,FileX2Icon:dbe,FileXIcon:ube,Files:hbe,FilesIcon:hbe,Film:nf,FilmIcon:nf,Filter:Sw,FilterIcon:Sw,FilterX:mbe,FilterXIcon:mbe,Fingerprint:fbe,FingerprintIcon:fbe,FireExtinguisher:pbe,FireExtinguisherIcon:pbe,Fish:ybe,FishIcon:ybe,FishOff:gbe,FishOffIcon:gbe,FishSymbol:xbe,FishSymbolIcon:xbe,Flag:CE,FlagIcon:CE,FlagOff:vbe,FlagOffIcon:vbe,FlagTriangleLeft:bbe,FlagTriangleLeftIcon:bbe,FlagTriangleRight:_be,FlagTriangleRightIcon:_be,Flame:sh,FlameIcon:sh,FlameKindling:wbe,FlameKindlingIcon:wbe,Flashlight:Nbe,FlashlightIcon:Nbe,FlashlightOff:jbe,FlashlightOffIcon:jbe,FlaskConical:UI,FlaskConicalIcon:UI,FlaskConicalOff:kbe,FlaskConicalOffIcon:kbe,FlaskRound:Sbe,FlaskRoundIcon:Sbe,FlipHorizontal:_J,FlipHorizontal2:Cbe,FlipHorizontal2Icon:Cbe,FlipHorizontalIcon:_J,FlipVertical:Ebe,FlipVertical2:Abe,FlipVertical2Icon:Abe,FlipVerticalIcon:Ebe,Flower:Tbe,Flower2:US,Flower2Icon:US,FlowerIcon:Tbe,Focus:Mbe,FocusIcon:Mbe,FoldHorizontal:Pbe,FoldHorizontalIcon:Pbe,FoldVertical:Ibe,FoldVerticalIcon:Ibe,Folder:Mq,FolderArchive:Lbe,FolderArchiveIcon:Lbe,FolderCheck:Rbe,FolderCheckIcon:Rbe,FolderClock:Dbe,FolderClockIcon:Dbe,FolderClosed:Fbe,FolderClosedIcon:Fbe,FolderCode:Obe,FolderCodeIcon:Obe,FolderCog:zD,FolderCog2:zD,FolderCog2Icon:zD,FolderCogIcon:zD,FolderDot:zbe,FolderDotIcon:zbe,FolderDown:Bbe,FolderDownIcon:Bbe,FolderEdit:BD,FolderEditIcon:BD,FolderGit:Ube,FolderGit2:$be,FolderGit2Icon:$be,FolderGitIcon:Ube,FolderHeart:qbe,FolderHeartIcon:qbe,FolderIcon:Mq,FolderInput:Vbe,FolderInputIcon:Vbe,FolderKanban:Hbe,FolderKanbanIcon:Hbe,FolderKey:Gbe,FolderKeyIcon:Gbe,FolderLock:Wbe,FolderLockIcon:Wbe,FolderMinus:Kbe,FolderMinusIcon:Kbe,FolderOpen:Nv,FolderOpenDot:Ybe,FolderOpenDotIcon:Ybe,FolderOpenIcon:Nv,FolderOutput:Zbe,FolderOutputIcon:Zbe,FolderPen:BD,FolderPenIcon:BD,FolderPlus:wJ,FolderPlusIcon:wJ,FolderRoot:Xbe,FolderRootIcon:Xbe,FolderSearch:Jbe,FolderSearch2:Qbe,FolderSearch2Icon:Qbe,FolderSearchIcon:Jbe,FolderSymlink:e1e,FolderSymlinkIcon:e1e,FolderSync:t1e,FolderSyncIcon:t1e,FolderTree:s1e,FolderTreeIcon:s1e,FolderUp:n1e,FolderUpIcon:n1e,FolderX:r1e,FolderXIcon:r1e,Folders:a1e,FoldersIcon:a1e,Footprints:i1e,FootprintsIcon:i1e,ForkKnife:SO,ForkKnifeCrossed:kO,ForkKnifeCrossedIcon:kO,ForkKnifeIcon:SO,Forklift:o1e,ForkliftIcon:o1e,FormInput:dF,FormInputIcon:dF,Forward:l1e,ForwardIcon:l1e,Frame:c1e,FrameIcon:c1e,Framer:d1e,FramerIcon:d1e,Frown:u1e,FrownIcon:u1e,Fuel:h1e,FuelIcon:h1e,Fullscreen:m1e,FullscreenIcon:m1e,FunctionSquare:HF,FunctionSquareIcon:HF,GalleryHorizontal:p1e,GalleryHorizontalEnd:f1e,GalleryHorizontalEndIcon:f1e,GalleryHorizontalIcon:p1e,GalleryThumbnails:g1e,GalleryThumbnailsIcon:g1e,GalleryVertical:y1e,GalleryVerticalEnd:x1e,GalleryVerticalEndIcon:x1e,GalleryVerticalIcon:y1e,Gamepad:b1e,Gamepad2:v1e,Gamepad2Icon:v1e,GamepadIcon:b1e,GanttChart:QR,GanttChartIcon:QR,GanttChartSquare:f5,GanttChartSquareIcon:f5,Gauge:_1e,GaugeCircle:fD,GaugeCircleIcon:fD,GaugeIcon:_1e,Gavel:w1e,GavelIcon:w1e,Gem:j1e,GemIcon:j1e,Ghost:Fz,GhostIcon:Fz,Gift:dl,GiftIcon:dl,GitBranch:k1e,GitBranchIcon:k1e,GitBranchPlus:N1e,GitBranchPlusIcon:N1e,GitCommit:$D,GitCommitHorizontal:$D,GitCommitHorizontalIcon:$D,GitCommitIcon:$D,GitCommitVertical:S1e,GitCommitVerticalIcon:S1e,GitCompare:A1e,GitCompareArrows:C1e,GitCompareArrowsIcon:C1e,GitCompareIcon:A1e,GitFork:E1e,GitForkIcon:E1e,GitGraph:T1e,GitGraphIcon:T1e,GitMerge:M1e,GitMergeIcon:M1e,GitPullRequest:F1e,GitPullRequestArrow:P1e,GitPullRequestArrowIcon:P1e,GitPullRequestClosed:I1e,GitPullRequestClosedIcon:I1e,GitPullRequestCreate:R1e,GitPullRequestCreateArrow:L1e,GitPullRequestCreateArrowIcon:L1e,GitPullRequestCreateIcon:R1e,GitPullRequestDraft:D1e,GitPullRequestDraftIcon:D1e,GitPullRequestIcon:F1e,Github:O1e,GithubIcon:O1e,Gitlab:z1e,GitlabIcon:z1e,GlassWater:B1e,GlassWaterIcon:B1e,Glasses:$1e,GlassesIcon:$1e,Globe:cl,Globe2:kN,Globe2Icon:kN,GlobeIcon:cl,GlobeLock:U1e,GlobeLockIcon:U1e,Goal:q1e,GoalIcon:q1e,Grab:V1e,GrabIcon:V1e,GraduationCap:af,GraduationCapIcon:af,Grape:H1e,GrapeIcon:H1e,Grid:Dj,Grid2X2:qD,Grid2X2Icon:qD,Grid2X2Plus:UD,Grid2X2PlusIcon:UD,Grid2x2:qD,Grid2x2Check:G1e,Grid2x2CheckIcon:G1e,Grid2x2Icon:qD,Grid2x2Plus:UD,Grid2x2PlusIcon:UD,Grid2x2X:W1e,Grid2x2XIcon:W1e,Grid3X3:Dj,Grid3X3Icon:Dj,Grid3x3:Dj,Grid3x3Icon:Dj,GridIcon:Dj,Grip:Y1e,GripHorizontal:K1e,GripHorizontalIcon:K1e,GripIcon:Y1e,GripVertical:zg,GripVerticalIcon:zg,Group:Z1e,GroupIcon:Z1e,Guitar:X1e,GuitarIcon:X1e,Ham:Q1e,HamIcon:Q1e,Hammer:jJ,HammerIcon:jJ,Hand:Pq,HandCoins:J1e,HandCoinsIcon:J1e,HandHeart:NJ,HandHeartIcon:NJ,HandHelping:t4,HandHelpingIcon:t4,HandIcon:Pq,HandMetal:e_e,HandMetalIcon:e_e,HandPlatter:t_e,HandPlatterIcon:t_e,Handshake:yb,HandshakeIcon:yb,HardDrive:kJ,HardDriveDownload:s_e,HardDriveDownloadIcon:s_e,HardDriveIcon:kJ,HardDriveUpload:n_e,HardDriveUploadIcon:n_e,HardHat:r_e,HardHatIcon:r_e,Hash:qI,HashIcon:qI,Haze:a_e,HazeIcon:a_e,HdmiPort:i_e,HdmiPortIcon:i_e,Heading:d_e,Heading1:Iq,Heading1Icon:Iq,Heading2:Oz,Heading2Icon:Oz,Heading3:Lq,Heading3Icon:Lq,Heading4:o_e,Heading4Icon:o_e,Heading5:l_e,Heading5Icon:l_e,Heading6:c_e,Heading6Icon:c_e,HeadingIcon:d_e,HeadphoneOff:u_e,HeadphoneOffIcon:u_e,Headphones:h_e,HeadphonesIcon:h_e,Headset:m_e,HeadsetIcon:m_e,Heart:Jo,HeartCrack:f_e,HeartCrackIcon:f_e,HeartHandshake:SJ,HeartHandshakeIcon:SJ,HeartIcon:Jo,HeartOff:p_e,HeartOffIcon:p_e,HeartPulse:g_e,HeartPulseIcon:g_e,Heater:x_e,HeaterIcon:x_e,HelpCircle:J5,HelpCircleIcon:J5,HelpingHand:t4,HelpingHandIcon:t4,Hexagon:y_e,HexagonIcon:y_e,Highlighter:v_e,HighlighterIcon:v_e,History:Cw,HistoryIcon:Cw,Home:va,HomeIcon:va,Hop:__e,HopIcon:__e,HopOff:b_e,HopOffIcon:b_e,Hospital:w_e,HospitalIcon:w_e,Hotel:j_e,HotelIcon:j_e,Hourglass:CJ,HourglassIcon:CJ,House:va,HouseIcon:va,HousePlug:N_e,HousePlugIcon:N_e,HousePlus:k_e,HousePlusIcon:k_e,IceCream:HD,IceCream2:VD,IceCream2Icon:VD,IceCreamBowl:VD,IceCreamBowlIcon:VD,IceCreamCone:HD,IceCreamConeIcon:HD,IceCreamIcon:HD,Icon:NRt,IdCard:AJ,IdCardIcon:AJ,Image:Hc,ImageDown:S_e,ImageDownIcon:S_e,ImageIcon:Hc,ImageMinus:C_e,ImageMinusIcon:C_e,ImageOff:A_e,ImageOffIcon:A_e,ImagePlay:E_e,ImagePlayIcon:E_e,ImagePlus:kv,ImagePlusIcon:kv,ImageUp:T_e,ImageUpIcon:T_e,ImageUpscale:M_e,ImageUpscaleIcon:M_e,Images:P_e,ImagesIcon:P_e,Import:I_e,ImportIcon:I_e,Inbox:zz,InboxIcon:zz,Indent:WD,IndentDecrease:GD,IndentDecreaseIcon:GD,IndentIcon:WD,IndentIncrease:WD,IndentIncreaseIcon:WD,IndianRupee:L_e,IndianRupeeIcon:L_e,Infinity:Rq,InfinityIcon:Rq,Info:XS,InfoIcon:XS,Inspect:XF,InspectIcon:XF,InspectionPanel:R_e,InspectionPanelIcon:R_e,Instagram:Ef,InstagramIcon:Ef,Italic:AE,ItalicIcon:AE,IterationCcw:D_e,IterationCcwIcon:D_e,IterationCw:F_e,IterationCwIcon:F_e,JapaneseYen:O_e,JapaneseYenIcon:O_e,Joystick:z_e,JoystickIcon:z_e,Kanban:i2,KanbanIcon:i2,KanbanSquare:GF,KanbanSquareDashed:zF,KanbanSquareDashedIcon:zF,KanbanSquareIcon:GF,Key:__,KeyIcon:__,KeyRound:VI,KeyRoundIcon:VI,KeySquare:B_e,KeySquareIcon:B_e,Keyboard:q_e,KeyboardIcon:q_e,KeyboardMusic:$_e,KeyboardMusicIcon:$_e,KeyboardOff:U_e,KeyboardOffIcon:U_e,Lamp:Y_e,LampCeiling:V_e,LampCeilingIcon:V_e,LampDesk:H_e,LampDeskIcon:H_e,LampFloor:G_e,LampFloorIcon:G_e,LampIcon:Y_e,LampWallDown:W_e,LampWallDownIcon:W_e,LampWallUp:K_e,LampWallUpIcon:K_e,LandPlot:Z_e,LandPlotIcon:Z_e,Landmark:Dq,LandmarkIcon:Dq,Languages:X_e,LanguagesIcon:X_e,Laptop:J_e,Laptop2:KD,Laptop2Icon:KD,LaptopIcon:J_e,LaptopMinimal:KD,LaptopMinimalCheck:Q_e,LaptopMinimalCheckIcon:Q_e,LaptopMinimalIcon:KD,Lasso:twe,LassoIcon:twe,LassoSelect:ewe,LassoSelectIcon:ewe,Laugh:swe,LaughIcon:swe,Layers:T4,Layers2:nwe,Layers2Icon:nwe,Layers3:rwe,Layers3Icon:rwe,LayersIcon:T4,Layout:IA,LayoutDashboard:HI,LayoutDashboardIcon:HI,LayoutGrid:Xf,LayoutGridIcon:Xf,LayoutIcon:IA,LayoutList:awe,LayoutListIcon:awe,LayoutPanelLeft:iwe,LayoutPanelLeftIcon:iwe,LayoutPanelTop:owe,LayoutPanelTopIcon:owe,LayoutTemplate:o2,LayoutTemplateIcon:o2,Leaf:lwe,LeafIcon:lwe,LeafyGreen:cwe,LeafyGreenIcon:cwe,Lectern:dwe,LecternIcon:dwe,LetterText:uwe,LetterTextIcon:uwe,Library:l2,LibraryBig:hwe,LibraryBigIcon:hwe,LibraryIcon:l2,LibrarySquare:WF,LibrarySquareIcon:WF,LifeBuoy:Fq,LifeBuoyIcon:Fq,Ligature:mwe,LigatureIcon:mwe,Lightbulb:QS,LightbulbIcon:QS,LightbulbOff:fwe,LightbulbOffIcon:fwe,LineChart:YR,LineChartIcon:YR,Link:Sd,Link2:nu,Link2Icon:nu,Link2Off:pwe,Link2OffIcon:pwe,LinkIcon:Sd,Linkedin:ly,LinkedinIcon:ly,List:E0,ListCheck:gwe,ListCheckIcon:gwe,ListChecks:Sv,ListChecksIcon:Sv,ListCollapse:xwe,ListCollapseIcon:xwe,ListEnd:ywe,ListEndIcon:ywe,ListFilter:EJ,ListFilterIcon:EJ,ListIcon:E0,ListMinus:vwe,ListMinusIcon:vwe,ListMusic:bwe,ListMusicIcon:bwe,ListOrdered:c2,ListOrderedIcon:c2,ListPlus:TJ,ListPlusIcon:TJ,ListRestart:_we,ListRestartIcon:_we,ListStart:wwe,ListStartIcon:wwe,ListTodo:jwe,ListTodoIcon:jwe,ListTree:Nwe,ListTreeIcon:Nwe,ListVideo:kwe,ListVideoIcon:kwe,ListX:Swe,ListXIcon:Swe,Loader:Awe,Loader2:Ct,Loader2Icon:Ct,LoaderCircle:Ct,LoaderCircleIcon:Ct,LoaderIcon:Awe,LoaderPinwheel:Cwe,LoaderPinwheelIcon:Cwe,Locate:Oq,LocateFixed:Ewe,LocateFixedIcon:Ewe,LocateIcon:Oq,LocateOff:Twe,LocateOffIcon:Twe,Lock:jc,LockIcon:jc,LockKeyhole:MJ,LockKeyholeIcon:MJ,LockKeyholeOpen:YD,LockKeyholeOpenIcon:YD,LockOpen:ZD,LockOpenIcon:ZD,LogIn:GI,LogInIcon:GI,LogOut:Bz,LogOutIcon:Bz,Logs:Mwe,LogsIcon:Mwe,Lollipop:Pwe,LollipopIcon:Pwe,LucideAArrowDown:pme,LucideAArrowUp:gme,LucideALargeSmall:xme,LucideAccessibility:yme,LucideActivity:rf,LucideActivitySquare:yF,LucideAirVent:vme,LucideAirplay:bme,LucideAlarmCheck:ER,LucideAlarmClock:wme,LucideAlarmClockCheck:ER,LucideAlarmClockMinus:TR,LucideAlarmClockOff:_me,LucideAlarmClockPlus:MR,LucideAlarmMinus:TR,LucideAlarmPlus:MR,LucideAlarmSmoke:jme,LucideAlbum:Nme,LucideAlertCircle:vl,LucideAlertOctagon:FS,LucideAlertTriangle:Al,LucideAlignCenter:LI,LucideAlignCenterHorizontal:kme,LucideAlignCenterVertical:Sme,LucideAlignEndHorizontal:Cme,LucideAlignEndVertical:Ame,LucideAlignHorizontalDistributeCenter:Eme,LucideAlignHorizontalDistributeEnd:Tme,LucideAlignHorizontalDistributeStart:Mme,LucideAlignHorizontalJustifyCenter:Pme,LucideAlignHorizontalJustifyEnd:Ime,LucideAlignHorizontalJustifyStart:Lme,LucideAlignHorizontalSpaceAround:Rme,LucideAlignHorizontalSpaceBetween:Dme,LucideAlignJustify:Fme,LucideAlignLeft:RI,LucideAlignRight:DI,LucideAlignStartHorizontal:Ome,LucideAlignStartVertical:zme,LucideAlignVerticalDistributeCenter:Bme,LucideAlignVerticalDistributeEnd:$me,LucideAlignVerticalDistributeStart:Ume,LucideAlignVerticalJustifyCenter:qme,LucideAlignVerticalJustifyEnd:Vme,LucideAlignVerticalJustifyStart:Hme,LucideAlignVerticalSpaceAround:Gme,LucideAlignVerticalSpaceBetween:Wme,LucideAmbulance:Kme,LucideAmpersand:Yme,LucideAmpersands:Zme,LucideAmphora:Xme,LucideAnchor:Qme,LucideAngry:Jme,LucideAnnoyed:efe,LucideAntenna:tfe,LucideAnvil:sfe,LucideAperture:nfe,LucideAppWindow:afe,LucideAppWindowMac:rfe,LucideApple:ife,LucideArchive:wv,LucideArchiveRestore:FI,LucideArchiveX:ofe,LucideAreaChart:qR,LucideArmchair:lfe,LucideArrowBigDown:dfe,LucideArrowBigDownDash:cfe,LucideArrowBigLeft:hfe,LucideArrowBigLeftDash:ufe,LucideArrowBigRight:ffe,LucideArrowBigRightDash:mfe,LucideArrowBigUp:gfe,LucideArrowBigUpDash:pfe,LucideArrowDown:Lg,LucideArrowDown01:xfe,LucideArrowDown10:yfe,LucideArrowDownAZ:PR,LucideArrowDownAz:PR,LucideArrowDownCircle:tD,LucideArrowDownFromLine:vfe,LucideArrowDownLeft:bfe,LucideArrowDownLeftFromCircle:nD,LucideArrowDownLeftFromSquare:jF,LucideArrowDownLeftSquare:vF,LucideArrowDownNarrowWide:_fe,LucideArrowDownRight:lJ,LucideArrowDownRightFromCircle:rD,LucideArrowDownRightFromSquare:NF,LucideArrowDownRightSquare:bF,LucideArrowDownSquare:_F,LucideArrowDownToDot:wfe,LucideArrowDownToLine:jfe,LucideArrowDownUp:Nfe,LucideArrowDownWideNarrow:IR,LucideArrowDownZA:LR,LucideArrowDownZa:LR,LucideArrowLeft:Va,LucideArrowLeftCircle:sD,LucideArrowLeftFromLine:kfe,LucideArrowLeftRight:cJ,LucideArrowLeftSquare:wF,LucideArrowLeftToLine:Sfe,LucideArrowRight:Qa,LucideArrowRightCircle:oD,LucideArrowRightFromLine:Cfe,LucideArrowRightLeft:S4,LucideArrowRightSquare:CF,LucideArrowRightToLine:Afe,LucideArrowUp:Zf,LucideArrowUp01:Efe,LucideArrowUp10:Tfe,LucideArrowUpAZ:RR,LucideArrowUpAz:RR,LucideArrowUpCircle:lD,LucideArrowUpDown:Dy,LucideArrowUpFromDot:Mfe,LucideArrowUpFromLine:Pfe,LucideArrowUpLeft:Ife,LucideArrowUpLeftFromCircle:aD,LucideArrowUpLeftFromSquare:kF,LucideArrowUpLeftSquare:AF,LucideArrowUpNarrowWide:DR,LucideArrowUpRight:Mz,LucideArrowUpRightFromCircle:iD,LucideArrowUpRightFromSquare:SF,LucideArrowUpRightSquare:EF,LucideArrowUpSquare:TF,LucideArrowUpToLine:Lfe,LucideArrowUpWideNarrow:Rfe,LucideArrowUpZA:FR,LucideArrowUpZa:FR,LucideArrowsUpFromLine:Dfe,LucideAsterisk:Ffe,LucideAsteriskSquare:MF,LucideAtSign:Ofe,LucideAtom:zfe,LucideAudioLines:Bfe,LucideAudioWaveform:$fe,LucideAward:Im,LucideAxe:Ufe,LucideAxis3D:OR,LucideAxis3d:OR,LucideBaby:qfe,LucideBackpack:Vfe,LucideBadge:ipe,LucideBadgeAlert:Hfe,LucideBadgeCent:Gfe,LucideBadgeCheck:PA,LucideBadgeDollarSign:Wfe,LucideBadgeEuro:Kfe,LucideBadgeHelp:Yfe,LucideBadgeIndianRupee:Zfe,LucideBadgeInfo:Xfe,LucideBadgeJapaneseYen:Qfe,LucideBadgeMinus:Jfe,LucideBadgePercent:epe,LucideBadgePlus:tpe,LucideBadgePoundSterling:spe,LucideBadgeRussianRuble:npe,LucideBadgeSwissFranc:rpe,LucideBadgeX:ape,LucideBaggageClaim:ope,LucideBan:Pz,LucideBanana:lpe,LucideBandage:cpe,LucideBanknote:dpe,LucideBarChart:ZR,LucideBarChart2:XR,LucideBarChart3:Gl,LucideBarChart4:KR,LucideBarChartBig:WR,LucideBarChartHorizontal:HR,LucideBarChartHorizontalBig:VR,LucideBarcode:upe,LucideBaseline:hpe,LucideBath:C0,LucideBattery:ype,LucideBatteryCharging:mpe,LucideBatteryFull:fpe,LucideBatteryLow:ppe,LucideBatteryMedium:gpe,LucideBatteryWarning:xpe,LucideBeaker:dJ,LucideBean:bpe,LucideBeanOff:vpe,LucideBed:n2,LucideBedDouble:C4,LucideBedSingle:_pe,LucideBeef:wpe,LucideBeer:Npe,LucideBeerOff:jpe,LucideBell:zy,LucideBellDot:kpe,LucideBellElectric:Spe,LucideBellMinus:Cpe,LucideBellOff:KS,LucideBellPlus:Ape,LucideBellRing:YS,LucideBetweenHorizonalEnd:zR,LucideBetweenHorizonalStart:BR,LucideBetweenHorizontalEnd:zR,LucideBetweenHorizontalStart:BR,LucideBetweenVerticalEnd:Epe,LucideBetweenVerticalStart:Tpe,LucideBicepsFlexed:Mpe,LucideBike:Ppe,LucideBinary:Ipe,LucideBinoculars:Lpe,LucideBiohazard:Rpe,LucideBird:Dpe,LucideBitcoin:Fpe,LucideBlend:Ope,LucideBlinds:zpe,LucideBlocks:Bpe,LucideBluetooth:Vpe,LucideBluetoothConnected:$pe,LucideBluetoothOff:Upe,LucideBluetoothSearching:qpe,LucideBold:kE,LucideBolt:Hpe,LucideBomb:Gpe,LucideBone:Wpe,LucideBook:pge,LucideBookA:Kpe,LucideBookAudio:Ype,LucideBookCheck:Zpe,LucideBookCopy:Xpe,LucideBookDashed:$R,LucideBookDown:Qpe,LucideBookHeadphones:Jpe,LucideBookHeart:ege,LucideBookImage:tge,LucideBookKey:sge,LucideBookLock:nge,LucideBookMarked:rge,LucideBookMinus:age,LucideBookOpen:_x,LucideBookOpenCheck:ige,LucideBookOpenText:oge,LucideBookPlus:lge,LucideBookTemplate:$R,LucideBookText:cge,LucideBookType:dge,LucideBookUp:hge,LucideBookUp2:uge,LucideBookUser:mge,LucideBookX:fge,LucideBookmark:A0,LucideBookmarkCheck:gge,LucideBookmarkMinus:xge,LucideBookmarkPlus:OI,LucideBookmarkX:yge,LucideBoomBox:vge,LucideBot:A4,LucideBotMessageSquare:bge,LucideBotOff:_ge,LucideBox:uJ,LucideBoxSelect:$F,LucideBoxes:wge,LucideBraces:eP,LucideBrackets:jge,LucideBrain:hJ,LucideBrainCircuit:Nge,LucideBrainCog:kge,LucideBrickWall:Sge,LucideBriefcase:wx,LucideBriefcaseBusiness:Cge,LucideBriefcaseConveyorBelt:Age,LucideBriefcaseMedical:Ege,LucideBringToFront:Tge,LucideBrush:Mge,LucideBug:Lge,LucideBugOff:Pge,LucideBugPlay:Ige,LucideBuilding:zI,LucideBuilding2:wi,LucideBus:Dge,LucideBusFront:Rge,LucideCable:Oge,LucideCableCar:Fge,LucideCake:Rg,LucideCakeSlice:zge,LucideCalculator:r2,LucideCalendar:Ea,LucideCalendar1:Bge,LucideCalendarArrowDown:$ge,LucideCalendarArrowUp:Uge,LucideCalendarCheck:gb,LucideCalendarCheck2:qge,LucideCalendarClock:Su,LucideCalendarCog:Vge,LucideCalendarDays:Wc,LucideCalendarFold:Hge,LucideCalendarHeart:ZS,LucideCalendarMinus:Wge,LucideCalendarMinus2:Gge,LucideCalendarOff:jq,LucideCalendarPlus:vv,LucideCalendarPlus2:Kge,LucideCalendarRange:Yge,LucideCalendarSearch:Zge,LucideCalendarSync:Xge,LucideCalendarX:mJ,LucideCalendarX2:Qge,LucideCamera:jx,LucideCameraOff:Jge,LucideCandlestickChart:GR,LucideCandy:sxe,LucideCandyCane:exe,LucideCandyOff:txe,LucideCannabis:nxe,LucideCaptions:UR,LucideCaptionsOff:rxe,LucideCar:oxe,LucideCarFront:axe,LucideCarTaxiFront:ixe,LucideCaravan:lxe,LucideCarrot:cxe,LucideCaseLower:dxe,LucideCaseSensitive:uxe,LucideCaseUpper:hxe,LucideCassetteTape:mxe,LucideCast:fxe,LucideCastle:pxe,LucideCat:gxe,LucideCctv:xxe,LucideChartArea:qR,LucideChartBar:HR,LucideChartBarBig:VR,LucideChartBarDecreasing:yxe,LucideChartBarIncreasing:vxe,LucideChartBarStacked:bxe,LucideChartCandlestick:GR,LucideChartColumn:Gl,LucideChartColumnBig:WR,LucideChartColumnDecreasing:_xe,LucideChartColumnIncreasing:KR,LucideChartColumnStacked:wxe,LucideChartGantt:jxe,LucideChartLine:YR,LucideChartNetwork:Nxe,LucideChartNoAxesColumn:XR,LucideChartNoAxesColumnDecreasing:kxe,LucideChartNoAxesColumnIncreasing:ZR,LucideChartNoAxesCombined:Sxe,LucideChartNoAxesGantt:QR,LucideChartPie:JR,LucideChartScatter:eD,LucideChartSpline:Cxe,LucideCheck:ma,LucideCheckCheck:Iz,LucideCheckCircle:Wl,LucideCheckCircle2:Vr,LucideCheckSquare:qj,LucideCheckSquare2:IF,LucideChefHat:Axe,LucideCherry:Exe,LucideChevronDown:wl,LucideChevronDownCircle:cD,LucideChevronDownSquare:LF,LucideChevronFirst:Txe,LucideChevronLast:Mxe,LucideChevronLeft:kd,LucideChevronLeftCircle:dD,LucideChevronLeftSquare:RF,LucideChevronRight:Di,LucideChevronRightCircle:uD,LucideChevronRightSquare:DF,LucideChevronUp:xb,LucideChevronUpCircle:hD,LucideChevronUpSquare:FF,LucideChevronsDown:Ixe,LucideChevronsDownUp:Pxe,LucideChevronsLeft:Dxe,LucideChevronsLeftRight:Rxe,LucideChevronsLeftRightEllipsis:Lxe,LucideChevronsRight:Oxe,LucideChevronsRightLeft:Fxe,LucideChevronsUp:zxe,LucideChevronsUpDown:kw,LucideChrome:Lz,LucideChurch:Bxe,LucideCigarette:Uxe,LucideCigaretteOff:$xe,LucideCircle:Dg,LucideCircleAlert:vl,LucideCircleArrowDown:tD,LucideCircleArrowLeft:sD,LucideCircleArrowOutDownLeft:nD,LucideCircleArrowOutDownRight:rD,LucideCircleArrowOutUpLeft:aD,LucideCircleArrowOutUpRight:iD,LucideCircleArrowRight:oD,LucideCircleArrowUp:lD,LucideCircleCheck:Vr,LucideCircleCheckBig:Wl,LucideCircleChevronDown:cD,LucideCircleChevronLeft:dD,LucideCircleChevronRight:uD,LucideCircleChevronUp:hD,LucideCircleDashed:qxe,LucideCircleDivide:mD,LucideCircleDollarSign:Vxe,LucideCircleDot:Gxe,LucideCircleDotDashed:Hxe,LucideCircleEllipsis:Wxe,LucideCircleEqual:Kxe,LucideCircleFadingArrowUp:Yxe,LucideCircleFadingPlus:Zxe,LucideCircleGauge:fD,LucideCircleHelp:J5,LucideCircleMinus:pD,LucideCircleOff:Xxe,LucideCircleParking:xD,LucideCircleParkingOff:gD,LucideCirclePause:yD,LucideCirclePercent:vD,LucideCirclePlay:ef,LucideCirclePlus:bD,LucideCirclePower:_D,LucideCircleSlash:Qxe,LucideCircleSlash2:wD,LucideCircleSlashed:wD,LucideCircleStop:jD,LucideCircleUser:kD,LucideCircleUserRound:ND,LucideCircleX:ju,LucideCircuitBoard:Jxe,LucideCitrus:eye,LucideClapperboard:Nq,LucideClipboard:oye,LucideClipboardCheck:GN,LucideClipboardCopy:tye,LucideClipboardEdit:CD,LucideClipboardList:Fg,LucideClipboardMinus:sye,LucideClipboardPaste:nye,LucideClipboardPen:CD,LucideClipboardPenLine:SD,LucideClipboardPlus:rye,LucideClipboardSignature:SD,LucideClipboardType:aye,LucideClipboardX:iye,LucideClock:ca,LucideClock1:lye,LucideClock10:cye,LucideClock11:dye,LucideClock12:uye,LucideClock2:hye,LucideClock3:kq,LucideClock4:mye,LucideClock5:fye,LucideClock6:pye,LucideClock7:gye,LucideClock8:xye,LucideClock9:yye,LucideClockAlert:vye,LucideClockArrowDown:bye,LucideClockArrowUp:_ye,LucideCloud:Dye,LucideCloudAlert:wye,LucideCloudCog:jye,LucideCloudDownload:AD,LucideCloudDrizzle:Nye,LucideCloudFog:kye,LucideCloudHail:Sye,LucideCloudLightning:Cye,LucideCloudMoon:Eye,LucideCloudMoonRain:Aye,LucideCloudOff:Tye,LucideCloudRain:Pye,LucideCloudRainWind:Mye,LucideCloudSnow:Iye,LucideCloudSun:Rye,LucideCloudSunRain:Lye,LucideCloudUpload:tP,LucideCloudy:Fye,LucideClover:pE,LucideClub:Oye,LucideCode:SE,LucideCode2:e4,LucideCodeSquare:OF,LucideCodeXml:e4,LucideCodepen:zye,LucideCodesandbox:Bye,LucideCoffee:E4,LucideCog:$ye,LucideCoins:fJ,LucideColumns:ED,LucideColumns2:ED,LucideColumns3:sP,LucideColumns4:Uye,LucideCombine:qye,LucideCommand:Vye,LucideCompass:Rz,LucideComponent:Hye,LucideComputer:Gye,LucideConciergeBell:Wye,LucideCone:Kye,LucideConstruction:Yye,LucideContact:BI,LucideContact2:TD,LucideContactRound:TD,LucideContainer:Zye,LucideContrast:Xye,LucideCookie:Qye,LucideCookingPot:Jye,LucideCopy:Za,LucideCopyCheck:e0e,LucideCopyMinus:t0e,LucideCopyPlus:s0e,LucideCopySlash:n0e,LucideCopyX:r0e,LucideCopyleft:a0e,LucideCopyright:i0e,LucideCornerDownLeft:o0e,LucideCornerDownRight:pJ,LucideCornerLeftDown:l0e,LucideCornerLeftUp:c0e,LucideCornerRightDown:d0e,LucideCornerRightUp:u0e,LucideCornerUpLeft:h0e,LucideCornerUpRight:m0e,LucideCpu:f0e,LucideCreativeCommons:p0e,LucideCreditCard:jv,LucideCroissant:g0e,LucideCrop:x0e,LucideCross:y0e,LucideCrosshair:v0e,LucideCrown:Og,LucideCuboid:b0e,LucideCupSoda:_0e,LucideCurlyBraces:eP,LucideCurrency:w0e,LucideCylinder:j0e,LucideDam:N0e,LucideDatabase:Sq,LucideDatabaseBackup:k0e,LucideDatabaseZap:S0e,LucideDelete:C0e,LucideDessert:A0e,LucideDiameter:E0e,LucideDiamond:P0e,LucideDiamondMinus:T0e,LucideDiamondPercent:MD,LucideDiamondPlus:M0e,LucideDice1:I0e,LucideDice2:L0e,LucideDice3:R0e,LucideDice4:D0e,LucideDice5:F0e,LucideDice6:O0e,LucideDices:z0e,LucideDiff:B0e,LucideDisc:V0e,LucideDisc2:$0e,LucideDisc3:U0e,LucideDiscAlbum:q0e,LucideDivide:H0e,LucideDivideCircle:mD,LucideDivideSquare:UF,LucideDna:W0e,LucideDnaOff:G0e,LucideDock:K0e,LucideDog:Y0e,LucideDollarSign:su,LucideDonut:Z0e,LucideDoorClosed:X0e,LucideDoorOpen:WN,LucideDot:Q0e,LucideDotSquare:qF,LucideDownload:ji,LucideDownloadCloud:AD,LucideDraftingCompass:J0e,LucideDrama:eve,LucideDribbble:tve,LucideDrill:sve,LucideDroplet:nve,LucideDroplets:p1,LucideDrum:rve,LucideDrumstick:ave,LucideDumbbell:ive,LucideEar:lve,LucideEarOff:ove,LucideEarth:kN,LucideEarthLock:cve,LucideEclipse:dve,LucideEdit:bp,LucideEdit2:SN,LucideEdit3:_f,LucideEgg:Cq,LucideEggFried:uve,LucideEggOff:hve,LucideEllipsis:o_,LucideEllipsisVertical:Xx,LucideEqual:pve,LucideEqualApproximately:mve,LucideEqualNot:fve,LucideEqualSquare:VF,LucideEraser:Aq,LucideEthernetPort:gve,LucideEuro:xve,LucideExpand:yve,LucideExternalLink:Ir,LucideEye:Ta,LucideEyeClosed:vve,LucideEyeOff:Nx,LucideFacebook:Zp,LucideFactory:bve,LucideFan:_ve,LucideFastForward:wve,LucideFeather:jve,LucideFence:Nve,LucideFerrisWheel:kve,LucideFigma:Sve,LucideFile:Tq,LucideFileArchive:Cve,LucideFileAudio:Eve,LucideFileAudio2:Ave,LucideFileAxis3D:PD,LucideFileAxis3d:PD,LucideFileBadge:Mve,LucideFileBadge2:Tve,LucideFileBarChart:ID,LucideFileBarChart2:LD,LucideFileBox:Pve,LucideFileChartColumn:LD,LucideFileChartColumnIncreasing:ID,LucideFileChartLine:RD,LucideFileChartPie:DD,LucideFileCheck:gJ,LucideFileCheck2:Dz,LucideFileClock:Ive,LucideFileCode:Rve,LucideFileCode2:Lve,LucideFileCog:FD,LucideFileCog2:FD,LucideFileDiff:Dve,LucideFileDigit:Fve,LucideFileDown:a2,LucideFileEdit:OD,LucideFileHeart:Ove,LucideFileImage:$I,LucideFileInput:zve,LucideFileJson:$ve,LucideFileJson2:Bve,LucideFileKey:qve,LucideFileKey2:Uve,LucideFileLineChart:RD,LucideFileLock:Hve,LucideFileLock2:Vve,LucideFileMinus:Wve,LucideFileMinus2:Gve,LucideFileMusic:Kve,LucideFileOutput:Yve,LucideFilePen:OD,LucideFilePenLine:l_,LucideFilePieChart:DD,LucideFilePlus:Zve,LucideFilePlus2:Eq,LucideFileQuestion:Xve,LucideFileScan:Qve,LucideFileSearch:xJ,LucideFileSearch2:Jve,LucideFileSignature:l_,LucideFileSliders:ebe,LucideFileSpreadsheet:KN,LucideFileStack:yJ,LucideFileSymlink:tbe,LucideFileTerminal:sbe,LucideFileText:Qr,LucideFileType:rbe,LucideFileType2:nbe,LucideFileUp:vJ,LucideFileUser:abe,LucideFileVideo:bJ,LucideFileVideo2:ibe,LucideFileVolume:lbe,LucideFileVolume2:obe,LucideFileWarning:cbe,LucideFileX:ube,LucideFileX2:dbe,LucideFiles:hbe,LucideFilm:nf,LucideFilter:Sw,LucideFilterX:mbe,LucideFingerprint:fbe,LucideFireExtinguisher:pbe,LucideFish:ybe,LucideFishOff:gbe,LucideFishSymbol:xbe,LucideFlag:CE,LucideFlagOff:vbe,LucideFlagTriangleLeft:bbe,LucideFlagTriangleRight:_be,LucideFlame:sh,LucideFlameKindling:wbe,LucideFlashlight:Nbe,LucideFlashlightOff:jbe,LucideFlaskConical:UI,LucideFlaskConicalOff:kbe,LucideFlaskRound:Sbe,LucideFlipHorizontal:_J,LucideFlipHorizontal2:Cbe,LucideFlipVertical:Ebe,LucideFlipVertical2:Abe,LucideFlower:Tbe,LucideFlower2:US,LucideFocus:Mbe,LucideFoldHorizontal:Pbe,LucideFoldVertical:Ibe,LucideFolder:Mq,LucideFolderArchive:Lbe,LucideFolderCheck:Rbe,LucideFolderClock:Dbe,LucideFolderClosed:Fbe,LucideFolderCode:Obe,LucideFolderCog:zD,LucideFolderCog2:zD,LucideFolderDot:zbe,LucideFolderDown:Bbe,LucideFolderEdit:BD,LucideFolderGit:Ube,LucideFolderGit2:$be,LucideFolderHeart:qbe,LucideFolderInput:Vbe,LucideFolderKanban:Hbe,LucideFolderKey:Gbe,LucideFolderLock:Wbe,LucideFolderMinus:Kbe,LucideFolderOpen:Nv,LucideFolderOpenDot:Ybe,LucideFolderOutput:Zbe,LucideFolderPen:BD,LucideFolderPlus:wJ,LucideFolderRoot:Xbe,LucideFolderSearch:Jbe,LucideFolderSearch2:Qbe,LucideFolderSymlink:e1e,LucideFolderSync:t1e,LucideFolderTree:s1e,LucideFolderUp:n1e,LucideFolderX:r1e,LucideFolders:a1e,LucideFootprints:i1e,LucideForkKnife:SO,LucideForkKnifeCrossed:kO,LucideForklift:o1e,LucideFormInput:dF,LucideForward:l1e,LucideFrame:c1e,LucideFramer:d1e,LucideFrown:u1e,LucideFuel:h1e,LucideFullscreen:m1e,LucideFunctionSquare:HF,LucideGalleryHorizontal:p1e,LucideGalleryHorizontalEnd:f1e,LucideGalleryThumbnails:g1e,LucideGalleryVertical:y1e,LucideGalleryVerticalEnd:x1e,LucideGamepad:b1e,LucideGamepad2:v1e,LucideGanttChart:QR,LucideGanttChartSquare:f5,LucideGauge:_1e,LucideGaugeCircle:fD,LucideGavel:w1e,LucideGem:j1e,LucideGhost:Fz,LucideGift:dl,LucideGitBranch:k1e,LucideGitBranchPlus:N1e,LucideGitCommit:$D,LucideGitCommitHorizontal:$D,LucideGitCommitVertical:S1e,LucideGitCompare:A1e,LucideGitCompareArrows:C1e,LucideGitFork:E1e,LucideGitGraph:T1e,LucideGitMerge:M1e,LucideGitPullRequest:F1e,LucideGitPullRequestArrow:P1e,LucideGitPullRequestClosed:I1e,LucideGitPullRequestCreate:R1e,LucideGitPullRequestCreateArrow:L1e,LucideGitPullRequestDraft:D1e,LucideGithub:O1e,LucideGitlab:z1e,LucideGlassWater:B1e,LucideGlasses:$1e,LucideGlobe:cl,LucideGlobe2:kN,LucideGlobeLock:U1e,LucideGoal:q1e,LucideGrab:V1e,LucideGraduationCap:af,LucideGrape:H1e,LucideGrid:Dj,LucideGrid2X2:qD,LucideGrid2X2Plus:UD,LucideGrid2x2:qD,LucideGrid2x2Check:G1e,LucideGrid2x2Plus:UD,LucideGrid2x2X:W1e,LucideGrid3X3:Dj,LucideGrid3x3:Dj,LucideGrip:Y1e,LucideGripHorizontal:K1e,LucideGripVertical:zg,LucideGroup:Z1e,LucideGuitar:X1e,LucideHam:Q1e,LucideHammer:jJ,LucideHand:Pq,LucideHandCoins:J1e,LucideHandHeart:NJ,LucideHandHelping:t4,LucideHandMetal:e_e,LucideHandPlatter:t_e,LucideHandshake:yb,LucideHardDrive:kJ,LucideHardDriveDownload:s_e,LucideHardDriveUpload:n_e,LucideHardHat:r_e,LucideHash:qI,LucideHaze:a_e,LucideHdmiPort:i_e,LucideHeading:d_e,LucideHeading1:Iq,LucideHeading2:Oz,LucideHeading3:Lq,LucideHeading4:o_e,LucideHeading5:l_e,LucideHeading6:c_e,LucideHeadphoneOff:u_e,LucideHeadphones:h_e,LucideHeadset:m_e,LucideHeart:Jo,LucideHeartCrack:f_e,LucideHeartHandshake:SJ,LucideHeartOff:p_e,LucideHeartPulse:g_e,LucideHeater:x_e,LucideHelpCircle:J5,LucideHelpingHand:t4,LucideHexagon:y_e,LucideHighlighter:v_e,LucideHistory:Cw,LucideHome:va,LucideHop:__e,LucideHopOff:b_e,LucideHospital:w_e,LucideHotel:j_e,LucideHourglass:CJ,LucideHouse:va,LucideHousePlug:N_e,LucideHousePlus:k_e,LucideIceCream:HD,LucideIceCream2:VD,LucideIceCreamBowl:VD,LucideIceCreamCone:HD,LucideIdCard:AJ,LucideImage:Hc,LucideImageDown:S_e,LucideImageMinus:C_e,LucideImageOff:A_e,LucideImagePlay:E_e,LucideImagePlus:kv,LucideImageUp:T_e,LucideImageUpscale:M_e,LucideImages:P_e,LucideImport:I_e,LucideInbox:zz,LucideIndent:WD,LucideIndentDecrease:GD,LucideIndentIncrease:WD,LucideIndianRupee:L_e,LucideInfinity:Rq,LucideInfo:XS,LucideInspect:XF,LucideInspectionPanel:R_e,LucideInstagram:Ef,LucideItalic:AE,LucideIterationCcw:D_e,LucideIterationCw:F_e,LucideJapaneseYen:O_e,LucideJoystick:z_e,LucideKanban:i2,LucideKanbanSquare:GF,LucideKanbanSquareDashed:zF,LucideKey:__,LucideKeyRound:VI,LucideKeySquare:B_e,LucideKeyboard:q_e,LucideKeyboardMusic:$_e,LucideKeyboardOff:U_e,LucideLamp:Y_e,LucideLampCeiling:V_e,LucideLampDesk:H_e,LucideLampFloor:G_e,LucideLampWallDown:W_e,LucideLampWallUp:K_e,LucideLandPlot:Z_e,LucideLandmark:Dq,LucideLanguages:X_e,LucideLaptop:J_e,LucideLaptop2:KD,LucideLaptopMinimal:KD,LucideLaptopMinimalCheck:Q_e,LucideLasso:twe,LucideLassoSelect:ewe,LucideLaugh:swe,LucideLayers:T4,LucideLayers2:nwe,LucideLayers3:rwe,LucideLayout:IA,LucideLayoutDashboard:HI,LucideLayoutGrid:Xf,LucideLayoutList:awe,LucideLayoutPanelLeft:iwe,LucideLayoutPanelTop:owe,LucideLayoutTemplate:o2,LucideLeaf:lwe,LucideLeafyGreen:cwe,LucideLectern:dwe,LucideLetterText:uwe,LucideLibrary:l2,LucideLibraryBig:hwe,LucideLibrarySquare:WF,LucideLifeBuoy:Fq,LucideLigature:mwe,LucideLightbulb:QS,LucideLightbulbOff:fwe,LucideLineChart:YR,LucideLink:Sd,LucideLink2:nu,LucideLink2Off:pwe,LucideLinkedin:ly,LucideList:E0,LucideListCheck:gwe,LucideListChecks:Sv,LucideListCollapse:xwe,LucideListEnd:ywe,LucideListFilter:EJ,LucideListMinus:vwe,LucideListMusic:bwe,LucideListOrdered:c2,LucideListPlus:TJ,LucideListRestart:_we,LucideListStart:wwe,LucideListTodo:jwe,LucideListTree:Nwe,LucideListVideo:kwe,LucideListX:Swe,LucideLoader:Awe,LucideLoader2:Ct,LucideLoaderCircle:Ct,LucideLoaderPinwheel:Cwe,LucideLocate:Oq,LucideLocateFixed:Ewe,LucideLocateOff:Twe,LucideLock:jc,LucideLockKeyhole:MJ,LucideLockKeyholeOpen:YD,LucideLockOpen:ZD,LucideLogIn:GI,LucideLogOut:Bz,LucideLogs:Mwe,LucideLollipop:Pwe,LucideLuggage:Iwe,LucideMSquare:KF,LucideMagnet:Lwe,LucideMail:pn,LucideMailCheck:$z,LucideMailMinus:Rwe,LucideMailOpen:zq,LucideMailPlus:Bq,LucideMailQuestion:Dwe,LucideMailSearch:Fwe,LucideMailWarning:Owe,LucideMailX:WI,LucideMailbox:zwe,LucideMails:Bwe,LucideMap:Uz,LucideMapPin:ui,LucideMapPinCheck:Uwe,LucideMapPinCheckInside:$we,LucideMapPinHouse:qwe,LucideMapPinMinus:Hwe,LucideMapPinMinusInside:Vwe,LucideMapPinOff:Gwe,LucideMapPinPlus:Kwe,LucideMapPinPlusInside:Wwe,LucideMapPinX:Zwe,LucideMapPinXInside:Ywe,LucideMapPinned:PJ,LucideMartini:Xwe,LucideMaximize:qz,LucideMaximize2:IJ,LucideMedal:EE,LucideMegaphone:gm,LucideMegaphoneOff:Qwe,LucideMeh:Jwe,LucideMemoryStick:eje,LucideMenu:TE,LucideMenuSquare:YF,LucideMerge:Vz,LucideMessageCircle:Ah,LucideMessageCircleCode:tje,LucideMessageCircleDashed:sje,LucideMessageCircleHeart:$q,LucideMessageCircleMore:nje,LucideMessageCircleOff:rje,LucideMessageCirclePlus:aje,LucideMessageCircleQuestion:LJ,LucideMessageCircleReply:ije,LucideMessageCircleWarning:oje,LucideMessageCircleX:lje,LucideMessageSquare:no,LucideMessageSquareCode:cje,LucideMessageSquareDashed:dje,LucideMessageSquareDiff:uje,LucideMessageSquareDot:hje,LucideMessageSquareHeart:mje,LucideMessageSquareLock:fje,LucideMessageSquareMore:RJ,LucideMessageSquareOff:pje,LucideMessageSquarePlus:h4,LucideMessageSquareQuote:ME,LucideMessageSquareReply:DJ,LucideMessageSquareShare:gje,LucideMessageSquareText:xje,LucideMessageSquareWarning:FJ,LucideMessageSquareX:yje,LucideMessagesSquare:OJ,LucideMic:Hz,LucideMic2:XD,LucideMicOff:vje,LucideMicVocal:XD,LucideMicrochip:bje,LucideMicroscope:_je,LucideMicrowave:wje,LucideMilestone:jje,LucideMilk:kje,LucideMilkOff:Nje,LucideMinimize:Cje,LucideMinimize2:Sje,LucideMinus:YN,LucideMinusCircle:pD,LucideMinusSquare:ZF,LucideMonitor:ZN,LucideMonitorCheck:Aje,LucideMonitorCog:Eje,LucideMonitorDot:Tje,LucideMonitorDown:Mje,LucideMonitorOff:Pje,LucideMonitorPause:Ije,LucideMonitorPlay:Uq,LucideMonitorSmartphone:Lje,LucideMonitorSpeaker:Rje,LucideMonitorStop:Dje,LucideMonitorUp:Gz,LucideMonitorX:Fje,LucideMoon:zje,LucideMoonStar:Oje,LucideMoreHorizontal:o_,LucideMoreVertical:Xx,LucideMountain:$je,LucideMountainSnow:Bje,LucideMouse:Vje,LucideMouseOff:Uje,LucideMousePointer:lb,LucideMousePointer2:zJ,LucideMousePointerBan:qje,LucideMousePointerClick:Pm,LucideMousePointerSquareDashed:BF,LucideMove:BJ,LucideMove3D:QD,LucideMove3d:QD,LucideMoveDiagonal:Gje,LucideMoveDiagonal2:Hje,LucideMoveDown:Yje,LucideMoveDownLeft:Wje,LucideMoveDownRight:Kje,LucideMoveHorizontal:Zje,LucideMoveLeft:Xje,LucideMoveRight:Qje,LucideMoveUp:t2e,LucideMoveUpLeft:Jje,LucideMoveUpRight:e2e,LucideMoveVertical:s2e,LucideMusic:qq,LucideMusic2:n2e,LucideMusic3:r2e,LucideMusic4:a2e,LucideNavigation:$J,LucideNavigation2:o2e,LucideNavigation2Off:i2e,LucideNavigationOff:l2e,LucideNetwork:c2e,LucideNewspaper:XN,LucideNfc:d2e,LucideNotebook:f2e,LucideNotebookPen:u2e,LucideNotebookTabs:h2e,LucideNotebookText:m2e,LucideNotepadText:g2e,LucideNotepadTextDashed:p2e,LucideNut:y2e,LucideNutOff:x2e,LucideOctagon:b2e,LucideOctagonAlert:FS,LucideOctagonMinus:v2e,LucideOctagonPause:JD,LucideOctagonX:eF,LucideOmega:_2e,LucideOption:w2e,LucideOrbit:j2e,LucideOrigami:N2e,LucideOutdent:GD,LucidePackage:ym,LucidePackage2:k2e,LucidePackageCheck:S2e,LucidePackageMinus:C2e,LucidePackageOpen:A2e,LucidePackagePlus:E2e,LucidePackageSearch:T2e,LucidePackageX:M2e,LucidePaintBucket:P2e,LucidePaintRoller:I2e,LucidePaintbrush:L2e,LucidePaintbrush2:tF,LucidePaintbrushVertical:tF,LucidePalette:yd,LucidePalmtree:yO,LucidePanelBottom:F2e,LucidePanelBottomClose:R2e,LucidePanelBottomDashed:sF,LucidePanelBottomInactive:sF,LucidePanelBottomOpen:D2e,LucidePanelLeft:iF,LucidePanelLeftClose:nF,LucidePanelLeftDashed:rF,LucidePanelLeftInactive:rF,LucidePanelLeftOpen:aF,LucidePanelRight:B2e,LucidePanelRightClose:O2e,LucidePanelRightDashed:oF,LucidePanelRightInactive:oF,LucidePanelRightOpen:z2e,LucidePanelTop:q2e,LucidePanelTopClose:$2e,LucidePanelTopDashed:lF,LucidePanelTopInactive:lF,LucidePanelTopOpen:U2e,LucidePanelsLeftBottom:V2e,LucidePanelsLeftRight:sP,LucidePanelsRightBottom:H2e,LucidePanelsTopBottom:mF,LucidePanelsTopLeft:IA,LucidePaperclip:KI,LucideParentheses:G2e,LucideParkingCircle:xD,LucideParkingCircleOff:gD,LucideParkingMeter:W2e,LucideParkingSquare:JF,LucideParkingSquareOff:QF,LucidePartyPopper:kx,LucidePause:Cv,LucidePauseCircle:yD,LucidePauseOctagon:JD,LucidePawPrint:K2e,LucidePcCase:Y2e,LucidePen:SN,LucidePenBox:bp,LucidePenLine:_f,LucidePenOff:Z2e,LucidePenSquare:bp,LucidePenTool:PE,LucidePencil:pi,LucidePencilLine:Vq,LucidePencilOff:X2e,LucidePencilRuler:Q2e,LucidePentagon:J2e,LucidePercent:Aw,LucidePercentCircle:vD,LucidePercentDiamond:MD,LucidePercentSquare:eO,LucidePersonStanding:eNe,LucidePhilippinePeso:tNe,LucidePhone:Da,LucidePhoneCall:UJ,LucidePhoneForwarded:sNe,LucidePhoneIncoming:nNe,LucidePhoneMissed:rNe,LucidePhoneOff:aNe,LucidePhoneOutgoing:iNe,LucidePi:oNe,LucidePiSquare:tO,LucidePiano:lNe,LucidePickaxe:cNe,LucidePictureInPicture:uNe,LucidePictureInPicture2:dNe,LucidePieChart:JR,LucidePiggyBank:qJ,LucidePilcrow:fNe,LucidePilcrowLeft:hNe,LucidePilcrowRight:mNe,LucidePilcrowSquare:sO,LucidePill:gNe,LucidePillBottle:pNe,LucidePin:IE,LucidePinOff:VJ,LucidePipette:xNe,LucidePizza:yNe,LucidePlane:HJ,LucidePlaneLanding:vNe,LucidePlaneTakeoff:bNe,LucidePlay:Ou,LucidePlayCircle:ef,LucidePlaySquare:nO,LucidePlug:QN,LucidePlug2:_Ne,LucidePlugZap:cF,LucidePlugZap2:cF,LucidePlus:cn,LucidePlusCircle:bD,LucidePlusSquare:rO,LucidePocket:jNe,LucidePocketKnife:wNe,LucidePodcast:NNe,LucidePointer:SNe,LucidePointerOff:kNe,LucidePopcorn:CNe,LucidePopsicle:ANe,LucidePoundSterling:ENe,LucidePower:GJ,LucidePowerCircle:_D,LucidePowerOff:TNe,LucidePowerSquare:aO,LucidePresentation:vb,LucidePrinter:LE,LucidePrinterCheck:MNe,LucideProjector:PNe,LucideProportions:INe,LucidePuzzle:LNe,LucidePyramid:RNe,LucideQrCode:Xp,LucideQuote:d2,LucideRabbit:DNe,LucideRadar:Hq,LucideRadiation:FNe,LucideRadical:ONe,LucideRadio:bb,LucideRadioReceiver:zNe,LucideRadioTower:BNe,LucideRadius:$Ne,LucideRailSymbol:UNe,LucideRainbow:qNe,LucideRat:VNe,LucideRatio:HNe,LucideReceipt:Gq,LucideReceiptCent:GNe,LucideReceiptEuro:WNe,LucideReceiptIndianRupee:KNe,LucideReceiptJapaneseYen:YNe,LucideReceiptPoundSterling:ZNe,LucideReceiptRussianRuble:XNe,LucideReceiptSwissFranc:QNe,LucideReceiptText:JNe,LucideRectangleEllipsis:dF,LucideRectangleHorizontal:eke,LucideRectangleVertical:tke,LucideRecycle:ske,LucideRedo:RE,LucideRedo2:nke,LucideRedoDot:rke,LucideRefreshCcw:Wq,LucideRefreshCcwDot:ake,LucideRefreshCw:co,LucideRefreshCwOff:ike,LucideRefrigerator:oke,LucideRegex:lke,LucideRemoveFormatting:cke,LucideRepeat:DE,LucideRepeat1:dke,LucideRepeat2:WJ,LucideReplace:hke,LucideReplaceAll:uke,LucideReply:Kq,LucideReplyAll:mke,LucideRewind:fke,LucideRibbon:pke,LucideRocket:By,LucideRockingChair:gke,LucideRollerCoaster:xke,LucideRotate3D:uF,LucideRotate3d:uF,LucideRotateCcw:Sx,LucideRotateCcwSquare:yke,LucideRotateCw:Wz,LucideRotateCwSquare:vke,LucideRoute:Yq,LucideRouteOff:bke,LucideRouter:_ke,LucideRows:hF,LucideRows2:hF,LucideRows3:mF,LucideRows4:wke,LucideRss:jke,LucideRuler:M4,LucideRussianRuble:Nke,LucideSailboat:kke,LucideSalad:Ske,LucideSandwich:Cke,LucideSatellite:Eke,LucideSatelliteDish:Ake,LucideSave:tl,LucideSaveAll:Tke,LucideSaveOff:Mke,LucideScale:Pke,LucideScale3D:fF,LucideScale3d:fF,LucideScaling:Ike,LucideScan:$ke,LucideScanBarcode:Lke,LucideScanEye:Rke,LucideScanFace:Dke,LucideScanLine:Fke,LucideScanQrCode:Oke,LucideScanSearch:zke,LucideScanText:Bke,LucideScatterChart:eD,LucideSchool:Uke,LucideSchool2:bO,LucideScissors:Vke,LucideScissorsLineDashed:qke,LucideScissorsSquare:iO,LucideScissorsSquareDashedBottom:PF,LucideScreenShare:Gke,LucideScreenShareOff:Hke,LucideScroll:Wke,LucideScrollText:Zq,LucideSearch:Kr,LucideSearchCheck:Kke,LucideSearchCode:Yke,LucideSearchSlash:Zke,LucideSearchX:Xq,LucideSection:Xke,LucideSend:Zr,LucideSendHorizonal:pF,LucideSendHorizontal:pF,LucideSendToBack:Qke,LucideSeparatorHorizontal:Jke,LucideSeparatorVertical:eSe,LucideServer:rSe,LucideServerCog:tSe,LucideServerCrash:sSe,LucideServerOff:nSe,LucideSettings:Nd,LucideSettings2:JS,LucideShapes:aSe,LucideShare:KJ,LucideShare2:Hd,LucideSheet:iSe,LucideShell:oSe,LucideShield:Tf,LucideShieldAlert:Qq,LucideShieldBan:lSe,LucideShieldCheck:Rm,LucideShieldClose:gF,LucideShieldEllipsis:cSe,LucideShieldHalf:dSe,LucideShieldMinus:uSe,LucideShieldOff:Kz,LucideShieldPlus:hSe,LucideShieldQuestion:Yz,LucideShieldX:gF,LucideShip:fSe,LucideShipWheel:mSe,LucideShirt:pSe,LucideShoppingBag:P4,LucideShoppingBasket:gSe,LucideShoppingCart:eC,LucideShovel:xSe,LucideShowerHead:ySe,LucideShrink:vSe,LucideShrub:bSe,LucideShuffle:Zz,LucideSidebar:iF,LucideSidebarClose:nF,LucideSidebarOpen:aF,LucideSigma:_Se,LucideSigmaSquare:oO,LucideSignal:SSe,LucideSignalHigh:wSe,LucideSignalLow:jSe,LucideSignalMedium:NSe,LucideSignalZero:kSe,LucideSignature:CSe,LucideSignpost:YJ,LucideSignpostBig:ASe,LucideSiren:ESe,LucideSkipBack:TSe,LucideSkipForward:ZJ,LucideSkull:MSe,LucideSlack:PSe,LucideSlash:ISe,LucideSlashSquare:lO,LucideSlice:LSe,LucideSliders:xF,LucideSlidersHorizontal:YI,LucideSlidersVertical:xF,LucideSmartphone:g1,LucideSmartphoneCharging:RSe,LucideSmartphoneNfc:DSe,LucideSmile:OSe,LucideSmilePlus:FSe,LucideSnail:zSe,LucideSnowflake:Zj,LucideSofa:Jq,LucideSortAsc:DR,LucideSortDesc:IR,LucideSoup:BSe,LucideSpace:$Se,LucideSpade:USe,LucideSparkle:ZI,LucideSparkles:wn,LucideSpeaker:qSe,LucideSpeech:VSe,LucideSpellCheck:GSe,LucideSpellCheck2:HSe,LucideSpline:WSe,LucideSplit:KSe,LucideSplitSquareHorizontal:cO,LucideSplitSquareVertical:dO,LucideSprayCan:YSe,LucideSprout:XI,LucideSquare:w_,LucideSquareActivity:yF,LucideSquareArrowDown:_F,LucideSquareArrowDownLeft:vF,LucideSquareArrowDownRight:bF,LucideSquareArrowLeft:wF,LucideSquareArrowOutDownLeft:jF,LucideSquareArrowOutDownRight:NF,LucideSquareArrowOutUpLeft:kF,LucideSquareArrowOutUpRight:SF,LucideSquareArrowRight:CF,LucideSquareArrowUp:TF,LucideSquareArrowUpLeft:AF,LucideSquareArrowUpRight:EF,LucideSquareAsterisk:MF,LucideSquareBottomDashedScissors:PF,LucideSquareChartGantt:f5,LucideSquareCheck:IF,LucideSquareCheckBig:qj,LucideSquareChevronDown:LF,LucideSquareChevronLeft:RF,LucideSquareChevronRight:DF,LucideSquareChevronUp:FF,LucideSquareCode:OF,LucideSquareDashed:$F,LucideSquareDashedBottom:XSe,LucideSquareDashedBottomCode:ZSe,LucideSquareDashedKanban:zF,LucideSquareDashedMousePointer:BF,LucideSquareDivide:UF,LucideSquareDot:qF,LucideSquareEqual:VF,LucideSquareFunction:HF,LucideSquareGanttChart:f5,LucideSquareKanban:GF,LucideSquareLibrary:WF,LucideSquareM:KF,LucideSquareMenu:YF,LucideSquareMinus:ZF,LucideSquareMousePointer:XF,LucideSquareParking:JF,LucideSquareParkingOff:QF,LucideSquarePen:bp,LucideSquarePercent:eO,LucideSquarePi:tO,LucideSquarePilcrow:sO,LucideSquarePlay:nO,LucideSquarePlus:rO,LucideSquarePower:aO,LucideSquareRadical:QSe,LucideSquareScissors:iO,LucideSquareSigma:oO,LucideSquareSlash:lO,LucideSquareSplitHorizontal:cO,LucideSquareSplitVertical:dO,LucideSquareSquare:JSe,LucideSquareStack:eCe,LucideSquareTerminal:uO,LucideSquareUser:mO,LucideSquareUserRound:hO,LucideSquareX:fO,LucideSquircle:tCe,LucideSquirrel:sCe,LucideStamp:nCe,LucideStar:ei,LucideStarHalf:rCe,LucideStarOff:aCe,LucideStars:wn,LucideStepBack:iCe,LucideStepForward:oCe,LucideStethoscope:lCe,LucideSticker:cCe,LucideStickyNote:Xz,LucideStopCircle:jD,LucideStore:eV,LucideStretchHorizontal:dCe,LucideStretchVertical:uCe,LucideStrikethrough:XJ,LucideSubscript:hCe,LucideSubtitles:UR,LucideSun:JN,LucideSunDim:mCe,LucideSunMedium:fCe,LucideSunMoon:pCe,LucideSunSnow:gCe,LucideSunrise:xCe,LucideSunset:yCe,LucideSuperscript:vCe,LucideSwatchBook:bCe,LucideSwissFranc:_Ce,LucideSwitchCamera:wCe,LucideSword:jCe,LucideSwords:NCe,LucideSyringe:kCe,LucideTable:sV,LucideTable2:tV,LucideTableCellsMerge:SCe,LucideTableCellsSplit:CCe,LucideTableColumnsSplit:ACe,LucideTableOfContents:ECe,LucideTableProperties:TCe,LucideTableRowsSplit:MCe,LucideTablet:nV,LucideTabletSmartphone:PCe,LucideTablets:ICe,LucideTag:Cp,LucideTags:QJ,LucideTally1:LCe,LucideTally2:RCe,LucideTally3:DCe,LucideTally4:FCe,LucideTally5:OCe,LucideTangent:zCe,LucideTarget:ph,LucideTelescope:BCe,LucideTent:UCe,LucideTentTree:$Ce,LucideTerminal:qCe,LucideTerminalSquare:uO,LucideTestTube:VCe,LucideTestTube2:pO,LucideTestTubeDiagonal:pO,LucideTestTubes:HCe,LucideText:YCe,LucideTextCursor:GCe,LucideTextCursorInput:rV,LucideTextQuote:WCe,LucideTextSearch:KCe,LucideTextSelect:gO,LucideTextSelection:gO,LucideTheater:ZCe,LucideThermometer:JCe,LucideThermometerSnowflake:XCe,LucideThermometerSun:QCe,LucideThumbsDown:JJ,LucideThumbsUp:$y,LucideTicket:Qz,LucideTicketCheck:e5e,LucideTicketMinus:t5e,LucideTicketPercent:s5e,LucideTicketPlus:n5e,LucideTicketSlash:r5e,LucideTicketX:a5e,LucideTickets:o5e,LucideTicketsPlane:i5e,LucideTimer:d5e,LucideTimerOff:l5e,LucideTimerReset:c5e,LucideToggleLeft:u5e,LucideToggleRight:h5e,LucideToilet:m5e,LucideTornado:f5e,LucideTorus:p5e,LucideTouchpad:x5e,LucideTouchpadOff:g5e,LucideTowerControl:y5e,LucideToyBrick:v5e,LucideTractor:b5e,LucideTrafficCone:_5e,LucideTrain:xO,LucideTrainFront:j5e,LucideTrainFrontTunnel:w5e,LucideTrainTrack:N5e,LucideTramFront:xO,LucideTrash:k5e,LucideTrash2:qn,LucideTreeDeciduous:S5e,LucideTreePalm:yO,LucideTreePine:QI,LucideTrees:C5e,LucideTrello:A5e,LucideTrendingDown:tC,LucideTrendingUp:Zl,LucideTrendingUpDown:E5e,LucideTriangle:M5e,LucideTriangleAlert:Al,LucideTriangleRight:T5e,LucideTrophy:Kl,LucideTruck:eee,LucideTurtle:P5e,LucideTv:L5e,LucideTv2:vO,LucideTvMinimal:vO,LucideTvMinimalPlay:I5e,LucideTwitch:R5e,LucideTwitter:tee,LucideType:aV,LucideTypeOutline:D5e,LucideUmbrella:O5e,LucideUmbrellaOff:F5e,LucideUnderline:Jz,LucideUndo:FE,LucideUndo2:see,LucideUndoDot:z5e,LucideUnfoldHorizontal:B5e,LucideUnfoldVertical:$5e,LucideUngroup:U5e,LucideUniversity:bO,LucideUnlink:e7,LucideUnlink2:q5e,LucideUnlock:ZD,LucideUnlockKeyhole:YD,LucideUnplug:iV,LucideUpload:ni,LucideUploadCloud:tP,LucideUsb:V5e,LucideUser:sl,LucideUser2:rP,LucideUserCheck:u2,LucideUserCheck2:nP,LucideUserCircle:kD,LucideUserCircle2:ND,LucideUserCog:nee,LucideUserCog2:_O,LucideUserMinus:oV,LucideUserMinus2:wO,LucideUserPen:H5e,LucideUserPlus:lc,LucideUserPlus2:jO,LucideUserRound:rP,LucideUserRoundCheck:nP,LucideUserRoundCog:_O,LucideUserRoundMinus:wO,LucideUserRoundPen:G5e,LucideUserRoundPlus:jO,LucideUserRoundSearch:lV,LucideUserRoundX:NO,LucideUserSearch:W5e,LucideUserSquare:mO,LucideUserSquare2:hO,LucideUserX:cV,LucideUserX2:NO,LucideUsers:Yn,LucideUsers2:x0,LucideUsersRound:x0,LucideUtensils:SO,LucideUtensilsCrossed:kO,LucideUtilityPole:K5e,LucideVariable:dV,LucideVault:Y5e,LucideVegan:Z5e,LucideVenetianMask:X5e,LucideVerified:PA,LucideVibrate:J5e,LucideVibrateOff:Q5e,LucideVideo:fa,LucideVideoOff:e4e,LucideVideotape:t4e,LucideView:s4e,LucideVoicemail:n4e,LucideVolleyball:r4e,LucideVolume:o4e,LucideVolume1:a4e,LucideVolume2:ree,LucideVolumeOff:i4e,LucideVolumeX:aee,LucideVote:l4e,LucideWallet:t7,LucideWallet2:CO,LucideWalletCards:c4e,LucideWalletMinimal:CO,LucideWallpaper:d4e,LucideWand:u4e,LucideWand2:Qx,LucideWandSparkles:Qx,LucideWarehouse:h4e,LucideWashingMachine:m4e,LucideWatch:f4e,LucideWaves:p4e,LucideWaypoints:g4e,LucideWebcam:x4e,LucideWebhook:v4e,LucideWebhookOff:y4e,LucideWeight:b4e,LucideWheat:w4e,LucideWheatOff:_4e,LucideWholeWord:j4e,LucideWifi:A4e,LucideWifiHigh:N4e,LucideWifiLow:k4e,LucideWifiOff:S4e,LucideWifiZero:C4e,LucideWind:T4e,LucideWindArrowDown:E4e,LucideWine:P4e,LucideWineOff:M4e,LucideWorkflow:s7,LucideWorm:I4e,LucideWrapText:L4e,LucideWrench:I4,LucideX:mr,LucideXCircle:ju,LucideXOctagon:eF,LucideXSquare:fO,LucideYoutube:uV,LucideZap:Qp,LucideZapOff:R4e,LucideZoomIn:JI,LucideZoomOut:hV,Luggage:Iwe,LuggageIcon:Iwe,MSquare:KF,MSquareIcon:KF,Magnet:Lwe,MagnetIcon:Lwe,Mail:pn,MailCheck:$z,MailCheckIcon:$z,MailIcon:pn,MailMinus:Rwe,MailMinusIcon:Rwe,MailOpen:zq,MailOpenIcon:zq,MailPlus:Bq,MailPlusIcon:Bq,MailQuestion:Dwe,MailQuestionIcon:Dwe,MailSearch:Fwe,MailSearchIcon:Fwe,MailWarning:Owe,MailWarningIcon:Owe,MailX:WI,MailXIcon:WI,Mailbox:zwe,MailboxIcon:zwe,Mails:Bwe,MailsIcon:Bwe,Map:Uz,MapIcon:Uz,MapPin:ui,MapPinCheck:Uwe,MapPinCheckIcon:Uwe,MapPinCheckInside:$we,MapPinCheckInsideIcon:$we,MapPinHouse:qwe,MapPinHouseIcon:qwe,MapPinIcon:ui,MapPinMinus:Hwe,MapPinMinusIcon:Hwe,MapPinMinusInside:Vwe,MapPinMinusInsideIcon:Vwe,MapPinOff:Gwe,MapPinOffIcon:Gwe,MapPinPlus:Kwe,MapPinPlusIcon:Kwe,MapPinPlusInside:Wwe,MapPinPlusInsideIcon:Wwe,MapPinX:Zwe,MapPinXIcon:Zwe,MapPinXInside:Ywe,MapPinXInsideIcon:Ywe,MapPinned:PJ,MapPinnedIcon:PJ,Martini:Xwe,MartiniIcon:Xwe,Maximize:qz,Maximize2:IJ,Maximize2Icon:IJ,MaximizeIcon:qz,Medal:EE,MedalIcon:EE,Megaphone:gm,MegaphoneIcon:gm,MegaphoneOff:Qwe,MegaphoneOffIcon:Qwe,Meh:Jwe,MehIcon:Jwe,MemoryStick:eje,MemoryStickIcon:eje,Menu:TE,MenuIcon:TE,MenuSquare:YF,MenuSquareIcon:YF,Merge:Vz,MergeIcon:Vz,MessageCircle:Ah,MessageCircleCode:tje,MessageCircleCodeIcon:tje,MessageCircleDashed:sje,MessageCircleDashedIcon:sje,MessageCircleHeart:$q,MessageCircleHeartIcon:$q,MessageCircleIcon:Ah,MessageCircleMore:nje,MessageCircleMoreIcon:nje,MessageCircleOff:rje,MessageCircleOffIcon:rje,MessageCirclePlus:aje,MessageCirclePlusIcon:aje,MessageCircleQuestion:LJ,MessageCircleQuestionIcon:LJ,MessageCircleReply:ije,MessageCircleReplyIcon:ije,MessageCircleWarning:oje,MessageCircleWarningIcon:oje,MessageCircleX:lje,MessageCircleXIcon:lje,MessageSquare:no,MessageSquareCode:cje,MessageSquareCodeIcon:cje,MessageSquareDashed:dje,MessageSquareDashedIcon:dje,MessageSquareDiff:uje,MessageSquareDiffIcon:uje,MessageSquareDot:hje,MessageSquareDotIcon:hje,MessageSquareHeart:mje,MessageSquareHeartIcon:mje,MessageSquareIcon:no,MessageSquareLock:fje,MessageSquareLockIcon:fje,MessageSquareMore:RJ,MessageSquareMoreIcon:RJ,MessageSquareOff:pje,MessageSquareOffIcon:pje,MessageSquarePlus:h4,MessageSquarePlusIcon:h4,MessageSquareQuote:ME,MessageSquareQuoteIcon:ME,MessageSquareReply:DJ,MessageSquareReplyIcon:DJ,MessageSquareShare:gje,MessageSquareShareIcon:gje,MessageSquareText:xje,MessageSquareTextIcon:xje,MessageSquareWarning:FJ,MessageSquareWarningIcon:FJ,MessageSquareX:yje,MessageSquareXIcon:yje,MessagesSquare:OJ,MessagesSquareIcon:OJ,Mic:Hz,Mic2:XD,Mic2Icon:XD,MicIcon:Hz,MicOff:vje,MicOffIcon:vje,MicVocal:XD,MicVocalIcon:XD,Microchip:bje,MicrochipIcon:bje,Microscope:_je,MicroscopeIcon:_je,Microwave:wje,MicrowaveIcon:wje,Milestone:jje,MilestoneIcon:jje,Milk:kje,MilkIcon:kje,MilkOff:Nje,MilkOffIcon:Nje,Minimize:Cje,Minimize2:Sje,Minimize2Icon:Sje,MinimizeIcon:Cje,Minus:YN,MinusCircle:pD,MinusCircleIcon:pD,MinusIcon:YN,MinusSquare:ZF,MinusSquareIcon:ZF,Monitor:ZN,MonitorCheck:Aje,MonitorCheckIcon:Aje,MonitorCog:Eje,MonitorCogIcon:Eje,MonitorDot:Tje,MonitorDotIcon:Tje,MonitorDown:Mje,MonitorDownIcon:Mje,MonitorIcon:ZN,MonitorOff:Pje,MonitorOffIcon:Pje,MonitorPause:Ije,MonitorPauseIcon:Ije,MonitorPlay:Uq,MonitorPlayIcon:Uq,MonitorSmartphone:Lje,MonitorSmartphoneIcon:Lje,MonitorSpeaker:Rje,MonitorSpeakerIcon:Rje,MonitorStop:Dje,MonitorStopIcon:Dje,MonitorUp:Gz,MonitorUpIcon:Gz,MonitorX:Fje,MonitorXIcon:Fje,Moon:zje,MoonIcon:zje,MoonStar:Oje,MoonStarIcon:Oje,MoreHorizontal:o_,MoreHorizontalIcon:o_,MoreVertical:Xx,MoreVerticalIcon:Xx,Mountain:$je,MountainIcon:$je,MountainSnow:Bje,MountainSnowIcon:Bje,Mouse:Vje,MouseIcon:Vje,MouseOff:Uje,MouseOffIcon:Uje,MousePointer:lb,MousePointer2:zJ,MousePointer2Icon:zJ,MousePointerBan:qje,MousePointerBanIcon:qje,MousePointerClick:Pm,MousePointerClickIcon:Pm,MousePointerIcon:lb,MousePointerSquareDashed:BF,MousePointerSquareDashedIcon:BF,Move:BJ,Move3D:QD,Move3DIcon:QD,Move3d:QD,Move3dIcon:QD,MoveDiagonal:Gje,MoveDiagonal2:Hje,MoveDiagonal2Icon:Hje,MoveDiagonalIcon:Gje,MoveDown:Yje,MoveDownIcon:Yje,MoveDownLeft:Wje,MoveDownLeftIcon:Wje,MoveDownRight:Kje,MoveDownRightIcon:Kje,MoveHorizontal:Zje,MoveHorizontalIcon:Zje,MoveIcon:BJ,MoveLeft:Xje,MoveLeftIcon:Xje,MoveRight:Qje,MoveRightIcon:Qje,MoveUp:t2e,MoveUpIcon:t2e,MoveUpLeft:Jje,MoveUpLeftIcon:Jje,MoveUpRight:e2e,MoveUpRightIcon:e2e,MoveVertical:s2e,MoveVerticalIcon:s2e,Music:qq,Music2:n2e,Music2Icon:n2e,Music3:r2e,Music3Icon:r2e,Music4:a2e,Music4Icon:a2e,MusicIcon:qq,Navigation:$J,Navigation2:o2e,Navigation2Icon:o2e,Navigation2Off:i2e,Navigation2OffIcon:i2e,NavigationIcon:$J,NavigationOff:l2e,NavigationOffIcon:l2e,Network:c2e,NetworkIcon:c2e,Newspaper:XN,NewspaperIcon:XN,Nfc:d2e,NfcIcon:d2e,Notebook:f2e,NotebookIcon:f2e,NotebookPen:u2e,NotebookPenIcon:u2e,NotebookTabs:h2e,NotebookTabsIcon:h2e,NotebookText:m2e,NotebookTextIcon:m2e,NotepadText:g2e,NotepadTextDashed:p2e,NotepadTextDashedIcon:p2e,NotepadTextIcon:g2e,Nut:y2e,NutIcon:y2e,NutOff:x2e,NutOffIcon:x2e,Octagon:b2e,OctagonAlert:FS,OctagonAlertIcon:FS,OctagonIcon:b2e,OctagonMinus:v2e,OctagonMinusIcon:v2e,OctagonPause:JD,OctagonPauseIcon:JD,OctagonX:eF,OctagonXIcon:eF,Omega:_2e,OmegaIcon:_2e,Option:w2e,OptionIcon:w2e,Orbit:j2e,OrbitIcon:j2e,Origami:N2e,OrigamiIcon:N2e,Outdent:GD,OutdentIcon:GD,Package:ym,Package2:k2e,Package2Icon:k2e,PackageCheck:S2e,PackageCheckIcon:S2e,PackageIcon:ym,PackageMinus:C2e,PackageMinusIcon:C2e,PackageOpen:A2e,PackageOpenIcon:A2e,PackagePlus:E2e,PackagePlusIcon:E2e,PackageSearch:T2e,PackageSearchIcon:T2e,PackageX:M2e,PackageXIcon:M2e,PaintBucket:P2e,PaintBucketIcon:P2e,PaintRoller:I2e,PaintRollerIcon:I2e,Paintbrush:L2e,Paintbrush2:tF,Paintbrush2Icon:tF,PaintbrushIcon:L2e,PaintbrushVertical:tF,PaintbrushVerticalIcon:tF,Palette:yd,PaletteIcon:yd,Palmtree:yO,PalmtreeIcon:yO,PanelBottom:F2e,PanelBottomClose:R2e,PanelBottomCloseIcon:R2e,PanelBottomDashed:sF,PanelBottomDashedIcon:sF,PanelBottomIcon:F2e,PanelBottomInactive:sF,PanelBottomInactiveIcon:sF,PanelBottomOpen:D2e,PanelBottomOpenIcon:D2e,PanelLeft:iF,PanelLeftClose:nF,PanelLeftCloseIcon:nF,PanelLeftDashed:rF,PanelLeftDashedIcon:rF,PanelLeftIcon:iF,PanelLeftInactive:rF,PanelLeftInactiveIcon:rF,PanelLeftOpen:aF,PanelLeftOpenIcon:aF,PanelRight:B2e,PanelRightClose:O2e,PanelRightCloseIcon:O2e,PanelRightDashed:oF,PanelRightDashedIcon:oF,PanelRightIcon:B2e,PanelRightInactive:oF,PanelRightInactiveIcon:oF,PanelRightOpen:z2e,PanelRightOpenIcon:z2e,PanelTop:q2e,PanelTopClose:$2e,PanelTopCloseIcon:$2e,PanelTopDashed:lF,PanelTopDashedIcon:lF,PanelTopIcon:q2e,PanelTopInactive:lF,PanelTopInactiveIcon:lF,PanelTopOpen:U2e,PanelTopOpenIcon:U2e,PanelsLeftBottom:V2e,PanelsLeftBottomIcon:V2e,PanelsLeftRight:sP,PanelsLeftRightIcon:sP,PanelsRightBottom:H2e,PanelsRightBottomIcon:H2e,PanelsTopBottom:mF,PanelsTopBottomIcon:mF,PanelsTopLeft:IA,PanelsTopLeftIcon:IA,Paperclip:KI,PaperclipIcon:KI,Parentheses:G2e,ParenthesesIcon:G2e,ParkingCircle:xD,ParkingCircleIcon:xD,ParkingCircleOff:gD,ParkingCircleOffIcon:gD,ParkingMeter:W2e,ParkingMeterIcon:W2e,ParkingSquare:JF,ParkingSquareIcon:JF,ParkingSquareOff:QF,ParkingSquareOffIcon:QF,PartyPopper:kx,PartyPopperIcon:kx,Pause:Cv,PauseCircle:yD,PauseCircleIcon:yD,PauseIcon:Cv,PauseOctagon:JD,PauseOctagonIcon:JD,PawPrint:K2e,PawPrintIcon:K2e,PcCase:Y2e,PcCaseIcon:Y2e,Pen:SN,PenBox:bp,PenBoxIcon:bp,PenIcon:SN,PenLine:_f,PenLineIcon:_f,PenOff:Z2e,PenOffIcon:Z2e,PenSquare:bp,PenSquareIcon:bp,PenTool:PE,PenToolIcon:PE,Pencil:pi,PencilIcon:pi,PencilLine:Vq,PencilLineIcon:Vq,PencilOff:X2e,PencilOffIcon:X2e,PencilRuler:Q2e,PencilRulerIcon:Q2e,Pentagon:J2e,PentagonIcon:J2e,Percent:Aw,PercentCircle:vD,PercentCircleIcon:vD,PercentDiamond:MD,PercentDiamondIcon:MD,PercentIcon:Aw,PercentSquare:eO,PercentSquareIcon:eO,PersonStanding:eNe,PersonStandingIcon:eNe,PhilippinePeso:tNe,PhilippinePesoIcon:tNe,Phone:Da,PhoneCall:UJ,PhoneCallIcon:UJ,PhoneForwarded:sNe,PhoneForwardedIcon:sNe,PhoneIcon:Da,PhoneIncoming:nNe,PhoneIncomingIcon:nNe,PhoneMissed:rNe,PhoneMissedIcon:rNe,PhoneOff:aNe,PhoneOffIcon:aNe,PhoneOutgoing:iNe,PhoneOutgoingIcon:iNe,Pi:oNe,PiIcon:oNe,PiSquare:tO,PiSquareIcon:tO,Piano:lNe,PianoIcon:lNe,Pickaxe:cNe,PickaxeIcon:cNe,PictureInPicture:uNe,PictureInPicture2:dNe,PictureInPicture2Icon:dNe,PictureInPictureIcon:uNe,PieChart:JR,PieChartIcon:JR,PiggyBank:qJ,PiggyBankIcon:qJ,Pilcrow:fNe,PilcrowIcon:fNe,PilcrowLeft:hNe,PilcrowLeftIcon:hNe,PilcrowRight:mNe,PilcrowRightIcon:mNe,PilcrowSquare:sO,PilcrowSquareIcon:sO,Pill:gNe,PillBottle:pNe,PillBottleIcon:pNe,PillIcon:gNe,Pin:IE,PinIcon:IE,PinOff:VJ,PinOffIcon:VJ,Pipette:xNe,PipetteIcon:xNe,Pizza:yNe,PizzaIcon:yNe,Plane:HJ,PlaneIcon:HJ,PlaneLanding:vNe,PlaneLandingIcon:vNe,PlaneTakeoff:bNe,PlaneTakeoffIcon:bNe,Play:Ou,PlayCircle:ef,PlayCircleIcon:ef,PlayIcon:Ou,PlaySquare:nO,PlaySquareIcon:nO,Plug:QN,Plug2:_Ne,Plug2Icon:_Ne,PlugIcon:QN,PlugZap:cF,PlugZap2:cF,PlugZap2Icon:cF,PlugZapIcon:cF,Plus:cn,PlusCircle:bD,PlusCircleIcon:bD,PlusIcon:cn,PlusSquare:rO,PlusSquareIcon:rO,Pocket:jNe,PocketIcon:jNe,PocketKnife:wNe,PocketKnifeIcon:wNe,Podcast:NNe,PodcastIcon:NNe,Pointer:SNe,PointerIcon:SNe,PointerOff:kNe,PointerOffIcon:kNe,Popcorn:CNe,PopcornIcon:CNe,Popsicle:ANe,PopsicleIcon:ANe,PoundSterling:ENe,PoundSterlingIcon:ENe,Power:GJ,PowerCircle:_D,PowerCircleIcon:_D,PowerIcon:GJ,PowerOff:TNe,PowerOffIcon:TNe,PowerSquare:aO,PowerSquareIcon:aO,Presentation:vb,PresentationIcon:vb,Printer:LE,PrinterCheck:MNe,PrinterCheckIcon:MNe,PrinterIcon:LE,Projector:PNe,ProjectorIcon:PNe,Proportions:INe,ProportionsIcon:INe,Puzzle:LNe,PuzzleIcon:LNe,Pyramid:RNe,PyramidIcon:RNe,QrCode:Xp,QrCodeIcon:Xp,Quote:d2,QuoteIcon:d2,Rabbit:DNe,RabbitIcon:DNe,Radar:Hq,RadarIcon:Hq,Radiation:FNe,RadiationIcon:FNe,Radical:ONe,RadicalIcon:ONe,Radio:bb,RadioIcon:bb,RadioReceiver:zNe,RadioReceiverIcon:zNe,RadioTower:BNe,RadioTowerIcon:BNe,Radius:$Ne,RadiusIcon:$Ne,RailSymbol:UNe,RailSymbolIcon:UNe,Rainbow:qNe,RainbowIcon:qNe,Rat:VNe,RatIcon:VNe,Ratio:HNe,RatioIcon:HNe,Receipt:Gq,ReceiptCent:GNe,ReceiptCentIcon:GNe,ReceiptEuro:WNe,ReceiptEuroIcon:WNe,ReceiptIcon:Gq,ReceiptIndianRupee:KNe,ReceiptIndianRupeeIcon:KNe,ReceiptJapaneseYen:YNe,ReceiptJapaneseYenIcon:YNe,ReceiptPoundSterling:ZNe,ReceiptPoundSterlingIcon:ZNe,ReceiptRussianRuble:XNe,ReceiptRussianRubleIcon:XNe,ReceiptSwissFranc:QNe,ReceiptSwissFrancIcon:QNe,ReceiptText:JNe,ReceiptTextIcon:JNe,RectangleEllipsis:dF,RectangleEllipsisIcon:dF,RectangleHorizontal:eke,RectangleHorizontalIcon:eke,RectangleVertical:tke,RectangleVerticalIcon:tke,Recycle:ske,RecycleIcon:ske,Redo:RE,Redo2:nke,Redo2Icon:nke,RedoDot:rke,RedoDotIcon:rke,RedoIcon:RE,RefreshCcw:Wq,RefreshCcwDot:ake,RefreshCcwDotIcon:ake,RefreshCcwIcon:Wq,RefreshCw:co,RefreshCwIcon:co,RefreshCwOff:ike,RefreshCwOffIcon:ike,Refrigerator:oke,RefrigeratorIcon:oke,Regex:lke,RegexIcon:lke,RemoveFormatting:cke,RemoveFormattingIcon:cke,Repeat:DE,Repeat1:dke,Repeat1Icon:dke,Repeat2:WJ,Repeat2Icon:WJ,RepeatIcon:DE,Replace:hke,ReplaceAll:uke,ReplaceAllIcon:uke,ReplaceIcon:hke,Reply:Kq,ReplyAll:mke,ReplyAllIcon:mke,ReplyIcon:Kq,Rewind:fke,RewindIcon:fke,Ribbon:pke,RibbonIcon:pke,Rocket:By,RocketIcon:By,RockingChair:gke,RockingChairIcon:gke,RollerCoaster:xke,RollerCoasterIcon:xke,Rotate3D:uF,Rotate3DIcon:uF,Rotate3d:uF,Rotate3dIcon:uF,RotateCcw:Sx,RotateCcwIcon:Sx,RotateCcwSquare:yke,RotateCcwSquareIcon:yke,RotateCw:Wz,RotateCwIcon:Wz,RotateCwSquare:vke,RotateCwSquareIcon:vke,Route:Yq,RouteIcon:Yq,RouteOff:bke,RouteOffIcon:bke,Router:_ke,RouterIcon:_ke,Rows:hF,Rows2:hF,Rows2Icon:hF,Rows3:mF,Rows3Icon:mF,Rows4:wke,Rows4Icon:wke,RowsIcon:hF,Rss:jke,RssIcon:jke,Ruler:M4,RulerIcon:M4,RussianRuble:Nke,RussianRubleIcon:Nke,Sailboat:kke,SailboatIcon:kke,Salad:Ske,SaladIcon:Ske,Sandwich:Cke,SandwichIcon:Cke,Satellite:Eke,SatelliteDish:Ake,SatelliteDishIcon:Ake,SatelliteIcon:Eke,Save:tl,SaveAll:Tke,SaveAllIcon:Tke,SaveIcon:tl,SaveOff:Mke,SaveOffIcon:Mke,Scale:Pke,Scale3D:fF,Scale3DIcon:fF,Scale3d:fF,Scale3dIcon:fF,ScaleIcon:Pke,Scaling:Ike,ScalingIcon:Ike,Scan:$ke,ScanBarcode:Lke,ScanBarcodeIcon:Lke,ScanEye:Rke,ScanEyeIcon:Rke,ScanFace:Dke,ScanFaceIcon:Dke,ScanIcon:$ke,ScanLine:Fke,ScanLineIcon:Fke,ScanQrCode:Oke,ScanQrCodeIcon:Oke,ScanSearch:zke,ScanSearchIcon:zke,ScanText:Bke,ScanTextIcon:Bke,ScatterChart:eD,ScatterChartIcon:eD,School:Uke,School2:bO,School2Icon:bO,SchoolIcon:Uke,Scissors:Vke,ScissorsIcon:Vke,ScissorsLineDashed:qke,ScissorsLineDashedIcon:qke,ScissorsSquare:iO,ScissorsSquareDashedBottom:PF,ScissorsSquareDashedBottomIcon:PF,ScissorsSquareIcon:iO,ScreenShare:Gke,ScreenShareIcon:Gke,ScreenShareOff:Hke,ScreenShareOffIcon:Hke,Scroll:Wke,ScrollIcon:Wke,ScrollText:Zq,ScrollTextIcon:Zq,Search:Kr,SearchCheck:Kke,SearchCheckIcon:Kke,SearchCode:Yke,SearchCodeIcon:Yke,SearchIcon:Kr,SearchSlash:Zke,SearchSlashIcon:Zke,SearchX:Xq,SearchXIcon:Xq,Section:Xke,SectionIcon:Xke,Send:Zr,SendHorizonal:pF,SendHorizonalIcon:pF,SendHorizontal:pF,SendHorizontalIcon:pF,SendIcon:Zr,SendToBack:Qke,SendToBackIcon:Qke,SeparatorHorizontal:Jke,SeparatorHorizontalIcon:Jke,SeparatorVertical:eSe,SeparatorVerticalIcon:eSe,Server:rSe,ServerCog:tSe,ServerCogIcon:tSe,ServerCrash:sSe,ServerCrashIcon:sSe,ServerIcon:rSe,ServerOff:nSe,ServerOffIcon:nSe,Settings:Nd,Settings2:JS,Settings2Icon:JS,SettingsIcon:Nd,Shapes:aSe,ShapesIcon:aSe,Share:KJ,Share2:Hd,Share2Icon:Hd,ShareIcon:KJ,Sheet:iSe,SheetIcon:iSe,Shell:oSe,ShellIcon:oSe,Shield:Tf,ShieldAlert:Qq,ShieldAlertIcon:Qq,ShieldBan:lSe,ShieldBanIcon:lSe,ShieldCheck:Rm,ShieldCheckIcon:Rm,ShieldClose:gF,ShieldCloseIcon:gF,ShieldEllipsis:cSe,ShieldEllipsisIcon:cSe,ShieldHalf:dSe,ShieldHalfIcon:dSe,ShieldIcon:Tf,ShieldMinus:uSe,ShieldMinusIcon:uSe,ShieldOff:Kz,ShieldOffIcon:Kz,ShieldPlus:hSe,ShieldPlusIcon:hSe,ShieldQuestion:Yz,ShieldQuestionIcon:Yz,ShieldX:gF,ShieldXIcon:gF,Ship:fSe,ShipIcon:fSe,ShipWheel:mSe,ShipWheelIcon:mSe,Shirt:pSe,ShirtIcon:pSe,ShoppingBag:P4,ShoppingBagIcon:P4,ShoppingBasket:gSe,ShoppingBasketIcon:gSe,ShoppingCart:eC,ShoppingCartIcon:eC,Shovel:xSe,ShovelIcon:xSe,ShowerHead:ySe,ShowerHeadIcon:ySe,Shrink:vSe,ShrinkIcon:vSe,Shrub:bSe,ShrubIcon:bSe,Shuffle:Zz,ShuffleIcon:Zz,Sidebar:iF,SidebarClose:nF,SidebarCloseIcon:nF,SidebarIcon:iF,SidebarOpen:aF,SidebarOpenIcon:aF,Sigma:_Se,SigmaIcon:_Se,SigmaSquare:oO,SigmaSquareIcon:oO,Signal:SSe,SignalHigh:wSe,SignalHighIcon:wSe,SignalIcon:SSe,SignalLow:jSe,SignalLowIcon:jSe,SignalMedium:NSe,SignalMediumIcon:NSe,SignalZero:kSe,SignalZeroIcon:kSe,Signature:CSe,SignatureIcon:CSe,Signpost:YJ,SignpostBig:ASe,SignpostBigIcon:ASe,SignpostIcon:YJ,Siren:ESe,SirenIcon:ESe,SkipBack:TSe,SkipBackIcon:TSe,SkipForward:ZJ,SkipForwardIcon:ZJ,Skull:MSe,SkullIcon:MSe,Slack:PSe,SlackIcon:PSe,Slash:ISe,SlashIcon:ISe,SlashSquare:lO,SlashSquareIcon:lO,Slice:LSe,SliceIcon:LSe,Sliders:xF,SlidersHorizontal:YI,SlidersHorizontalIcon:YI,SlidersIcon:xF,SlidersVertical:xF,SlidersVerticalIcon:xF,Smartphone:g1,SmartphoneCharging:RSe,SmartphoneChargingIcon:RSe,SmartphoneIcon:g1,SmartphoneNfc:DSe,SmartphoneNfcIcon:DSe,Smile:OSe,SmileIcon:OSe,SmilePlus:FSe,SmilePlusIcon:FSe,Snail:zSe,SnailIcon:zSe,Snowflake:Zj,SnowflakeIcon:Zj,Sofa:Jq,SofaIcon:Jq,SortAsc:DR,SortAscIcon:DR,SortDesc:IR,SortDescIcon:IR,Soup:BSe,SoupIcon:BSe,Space:$Se,SpaceIcon:$Se,Spade:USe,SpadeIcon:USe,Sparkle:ZI,SparkleIcon:ZI,Sparkles:wn,SparklesIcon:wn,Speaker:qSe,SpeakerIcon:qSe,Speech:VSe,SpeechIcon:VSe,SpellCheck:GSe,SpellCheck2:HSe,SpellCheck2Icon:HSe,SpellCheckIcon:GSe,Spline:WSe,SplineIcon:WSe,Split:KSe,SplitIcon:KSe,SplitSquareHorizontal:cO,SplitSquareHorizontalIcon:cO,SplitSquareVertical:dO,SplitSquareVerticalIcon:dO,SprayCan:YSe,SprayCanIcon:YSe,Sprout:XI,SproutIcon:XI,Square:w_,SquareActivity:yF,SquareActivityIcon:yF,SquareArrowDown:_F,SquareArrowDownIcon:_F,SquareArrowDownLeft:vF,SquareArrowDownLeftIcon:vF,SquareArrowDownRight:bF,SquareArrowDownRightIcon:bF,SquareArrowLeft:wF,SquareArrowLeftIcon:wF,SquareArrowOutDownLeft:jF,SquareArrowOutDownLeftIcon:jF,SquareArrowOutDownRight:NF,SquareArrowOutDownRightIcon:NF,SquareArrowOutUpLeft:kF,SquareArrowOutUpLeftIcon:kF,SquareArrowOutUpRight:SF,SquareArrowOutUpRightIcon:SF,SquareArrowRight:CF,SquareArrowRightIcon:CF,SquareArrowUp:TF,SquareArrowUpIcon:TF,SquareArrowUpLeft:AF,SquareArrowUpLeftIcon:AF,SquareArrowUpRight:EF,SquareArrowUpRightIcon:EF,SquareAsterisk:MF,SquareAsteriskIcon:MF,SquareBottomDashedScissors:PF,SquareBottomDashedScissorsIcon:PF,SquareChartGantt:f5,SquareChartGanttIcon:f5,SquareCheck:IF,SquareCheckBig:qj,SquareCheckBigIcon:qj,SquareCheckIcon:IF,SquareChevronDown:LF,SquareChevronDownIcon:LF,SquareChevronLeft:RF,SquareChevronLeftIcon:RF,SquareChevronRight:DF,SquareChevronRightIcon:DF,SquareChevronUp:FF,SquareChevronUpIcon:FF,SquareCode:OF,SquareCodeIcon:OF,SquareDashed:$F,SquareDashedBottom:XSe,SquareDashedBottomCode:ZSe,SquareDashedBottomCodeIcon:ZSe,SquareDashedBottomIcon:XSe,SquareDashedIcon:$F,SquareDashedKanban:zF,SquareDashedKanbanIcon:zF,SquareDashedMousePointer:BF,SquareDashedMousePointerIcon:BF,SquareDivide:UF,SquareDivideIcon:UF,SquareDot:qF,SquareDotIcon:qF,SquareEqual:VF,SquareEqualIcon:VF,SquareFunction:HF,SquareFunctionIcon:HF,SquareGanttChart:f5,SquareGanttChartIcon:f5,SquareIcon:w_,SquareKanban:GF,SquareKanbanIcon:GF,SquareLibrary:WF,SquareLibraryIcon:WF,SquareM:KF,SquareMIcon:KF,SquareMenu:YF,SquareMenuIcon:YF,SquareMinus:ZF,SquareMinusIcon:ZF,SquareMousePointer:XF,SquareMousePointerIcon:XF,SquareParking:JF,SquareParkingIcon:JF,SquareParkingOff:QF,SquareParkingOffIcon:QF,SquarePen:bp,SquarePenIcon:bp,SquarePercent:eO,SquarePercentIcon:eO,SquarePi:tO,SquarePiIcon:tO,SquarePilcrow:sO,SquarePilcrowIcon:sO,SquarePlay:nO,SquarePlayIcon:nO,SquarePlus:rO,SquarePlusIcon:rO,SquarePower:aO,SquarePowerIcon:aO,SquareRadical:QSe,SquareRadicalIcon:QSe,SquareScissors:iO,SquareScissorsIcon:iO,SquareSigma:oO,SquareSigmaIcon:oO,SquareSlash:lO,SquareSlashIcon:lO,SquareSplitHorizontal:cO,SquareSplitHorizontalIcon:cO,SquareSplitVertical:dO,SquareSplitVerticalIcon:dO,SquareSquare:JSe,SquareSquareIcon:JSe,SquareStack:eCe,SquareStackIcon:eCe,SquareTerminal:uO,SquareTerminalIcon:uO,SquareUser:mO,SquareUserIcon:mO,SquareUserRound:hO,SquareUserRoundIcon:hO,SquareX:fO,SquareXIcon:fO,Squircle:tCe,SquircleIcon:tCe,Squirrel:sCe,SquirrelIcon:sCe,Stamp:nCe,StampIcon:nCe,Star:ei,StarHalf:rCe,StarHalfIcon:rCe,StarIcon:ei,StarOff:aCe,StarOffIcon:aCe,Stars:wn,StarsIcon:wn,StepBack:iCe,StepBackIcon:iCe,StepForward:oCe,StepForwardIcon:oCe,Stethoscope:lCe,StethoscopeIcon:lCe,Sticker:cCe,StickerIcon:cCe,StickyNote:Xz,StickyNoteIcon:Xz,StopCircle:jD,StopCircleIcon:jD,Store:eV,StoreIcon:eV,StretchHorizontal:dCe,StretchHorizontalIcon:dCe,StretchVertical:uCe,StretchVerticalIcon:uCe,Strikethrough:XJ,StrikethroughIcon:XJ,Subscript:hCe,SubscriptIcon:hCe,Subtitles:UR,SubtitlesIcon:UR,Sun:JN,SunDim:mCe,SunDimIcon:mCe,SunIcon:JN,SunMedium:fCe,SunMediumIcon:fCe,SunMoon:pCe,SunMoonIcon:pCe,SunSnow:gCe,SunSnowIcon:gCe,Sunrise:xCe,SunriseIcon:xCe,Sunset:yCe,SunsetIcon:yCe,Superscript:vCe,SuperscriptIcon:vCe,SwatchBook:bCe,SwatchBookIcon:bCe,SwissFranc:_Ce,SwissFrancIcon:_Ce,SwitchCamera:wCe,SwitchCameraIcon:wCe,Sword:jCe,SwordIcon:jCe,Swords:NCe,SwordsIcon:NCe,Syringe:kCe,SyringeIcon:kCe,Table:sV,Table2:tV,Table2Icon:tV,TableCellsMerge:SCe,TableCellsMergeIcon:SCe,TableCellsSplit:CCe,TableCellsSplitIcon:CCe,TableColumnsSplit:ACe,TableColumnsSplitIcon:ACe,TableIcon:sV,TableOfContents:ECe,TableOfContentsIcon:ECe,TableProperties:TCe,TablePropertiesIcon:TCe,TableRowsSplit:MCe,TableRowsSplitIcon:MCe,Tablet:nV,TabletIcon:nV,TabletSmartphone:PCe,TabletSmartphoneIcon:PCe,Tablets:ICe,TabletsIcon:ICe,Tag:Cp,TagIcon:Cp,Tags:QJ,TagsIcon:QJ,Tally1:LCe,Tally1Icon:LCe,Tally2:RCe,Tally2Icon:RCe,Tally3:DCe,Tally3Icon:DCe,Tally4:FCe,Tally4Icon:FCe,Tally5:OCe,Tally5Icon:OCe,Tangent:zCe,TangentIcon:zCe,Target:ph,TargetIcon:ph,Telescope:BCe,TelescopeIcon:BCe,Tent:UCe,TentIcon:UCe,TentTree:$Ce,TentTreeIcon:$Ce,Terminal:qCe,TerminalIcon:qCe,TerminalSquare:uO,TerminalSquareIcon:uO,TestTube:VCe,TestTube2:pO,TestTube2Icon:pO,TestTubeDiagonal:pO,TestTubeDiagonalIcon:pO,TestTubeIcon:VCe,TestTubes:HCe,TestTubesIcon:HCe,Text:YCe,TextCursor:GCe,TextCursorIcon:GCe,TextCursorInput:rV,TextCursorInputIcon:rV,TextIcon:YCe,TextQuote:WCe,TextQuoteIcon:WCe,TextSearch:KCe,TextSearchIcon:KCe,TextSelect:gO,TextSelectIcon:gO,TextSelection:gO,TextSelectionIcon:gO,Theater:ZCe,TheaterIcon:ZCe,Thermometer:JCe,ThermometerIcon:JCe,ThermometerSnowflake:XCe,ThermometerSnowflakeIcon:XCe,ThermometerSun:QCe,ThermometerSunIcon:QCe,ThumbsDown:JJ,ThumbsDownIcon:JJ,ThumbsUp:$y,ThumbsUpIcon:$y,Ticket:Qz,TicketCheck:e5e,TicketCheckIcon:e5e,TicketIcon:Qz,TicketMinus:t5e,TicketMinusIcon:t5e,TicketPercent:s5e,TicketPercentIcon:s5e,TicketPlus:n5e,TicketPlusIcon:n5e,TicketSlash:r5e,TicketSlashIcon:r5e,TicketX:a5e,TicketXIcon:a5e,Tickets:o5e,TicketsIcon:o5e,TicketsPlane:i5e,TicketsPlaneIcon:i5e,Timer:d5e,TimerIcon:d5e,TimerOff:l5e,TimerOffIcon:l5e,TimerReset:c5e,TimerResetIcon:c5e,ToggleLeft:u5e,ToggleLeftIcon:u5e,ToggleRight:h5e,ToggleRightIcon:h5e,Toilet:m5e,ToiletIcon:m5e,Tornado:f5e,TornadoIcon:f5e,Torus:p5e,TorusIcon:p5e,Touchpad:x5e,TouchpadIcon:x5e,TouchpadOff:g5e,TouchpadOffIcon:g5e,TowerControl:y5e,TowerControlIcon:y5e,ToyBrick:v5e,ToyBrickIcon:v5e,Tractor:b5e,TractorIcon:b5e,TrafficCone:_5e,TrafficConeIcon:_5e,Train:xO,TrainFront:j5e,TrainFrontIcon:j5e,TrainFrontTunnel:w5e,TrainFrontTunnelIcon:w5e,TrainIcon:xO,TrainTrack:N5e,TrainTrackIcon:N5e,TramFront:xO,TramFrontIcon:xO,Trash:k5e,Trash2:qn,Trash2Icon:qn,TrashIcon:k5e,TreeDeciduous:S5e,TreeDeciduousIcon:S5e,TreePalm:yO,TreePalmIcon:yO,TreePine:QI,TreePineIcon:QI,Trees:C5e,TreesIcon:C5e,Trello:A5e,TrelloIcon:A5e,TrendingDown:tC,TrendingDownIcon:tC,TrendingUp:Zl,TrendingUpDown:E5e,TrendingUpDownIcon:E5e,TrendingUpIcon:Zl,Triangle:M5e,TriangleAlert:Al,TriangleAlertIcon:Al,TriangleIcon:M5e,TriangleRight:T5e,TriangleRightIcon:T5e,Trophy:Kl,TrophyIcon:Kl,Truck:eee,TruckIcon:eee,Turtle:P5e,TurtleIcon:P5e,Tv:L5e,Tv2:vO,Tv2Icon:vO,TvIcon:L5e,TvMinimal:vO,TvMinimalIcon:vO,TvMinimalPlay:I5e,TvMinimalPlayIcon:I5e,Twitch:R5e,TwitchIcon:R5e,Twitter:tee,TwitterIcon:tee,Type:aV,TypeIcon:aV,TypeOutline:D5e,TypeOutlineIcon:D5e,Umbrella:O5e,UmbrellaIcon:O5e,UmbrellaOff:F5e,UmbrellaOffIcon:F5e,Underline:Jz,UnderlineIcon:Jz,Undo:FE,Undo2:see,Undo2Icon:see,UndoDot:z5e,UndoDotIcon:z5e,UndoIcon:FE,UnfoldHorizontal:B5e,UnfoldHorizontalIcon:B5e,UnfoldVertical:$5e,UnfoldVerticalIcon:$5e,Ungroup:U5e,UngroupIcon:U5e,University:bO,UniversityIcon:bO,Unlink:e7,Unlink2:q5e,Unlink2Icon:q5e,UnlinkIcon:e7,Unlock:ZD,UnlockIcon:ZD,UnlockKeyhole:YD,UnlockKeyholeIcon:YD,Unplug:iV,UnplugIcon:iV,Upload:ni,UploadCloud:tP,UploadCloudIcon:tP,UploadIcon:ni,Usb:V5e,UsbIcon:V5e,User:sl,User2:rP,User2Icon:rP,UserCheck:u2,UserCheck2:nP,UserCheck2Icon:nP,UserCheckIcon:u2,UserCircle:kD,UserCircle2:ND,UserCircle2Icon:ND,UserCircleIcon:kD,UserCog:nee,UserCog2:_O,UserCog2Icon:_O,UserCogIcon:nee,UserIcon:sl,UserMinus:oV,UserMinus2:wO,UserMinus2Icon:wO,UserMinusIcon:oV,UserPen:H5e,UserPenIcon:H5e,UserPlus:lc,UserPlus2:jO,UserPlus2Icon:jO,UserPlusIcon:lc,UserRound:rP,UserRoundCheck:nP,UserRoundCheckIcon:nP,UserRoundCog:_O,UserRoundCogIcon:_O,UserRoundIcon:rP,UserRoundMinus:wO,UserRoundMinusIcon:wO,UserRoundPen:G5e,UserRoundPenIcon:G5e,UserRoundPlus:jO,UserRoundPlusIcon:jO,UserRoundSearch:lV,UserRoundSearchIcon:lV,UserRoundX:NO,UserRoundXIcon:NO,UserSearch:W5e,UserSearchIcon:W5e,UserSquare:mO,UserSquare2:hO,UserSquare2Icon:hO,UserSquareIcon:mO,UserX:cV,UserX2:NO,UserX2Icon:NO,UserXIcon:cV,Users:Yn,Users2:x0,Users2Icon:x0,UsersIcon:Yn,UsersRound:x0,UsersRoundIcon:x0,Utensils:SO,UtensilsCrossed:kO,UtensilsCrossedIcon:kO,UtensilsIcon:SO,UtilityPole:K5e,UtilityPoleIcon:K5e,Variable:dV,VariableIcon:dV,Vault:Y5e,VaultIcon:Y5e,Vegan:Z5e,VeganIcon:Z5e,VenetianMask:X5e,VenetianMaskIcon:X5e,Verified:PA,VerifiedIcon:PA,Vibrate:J5e,VibrateIcon:J5e,VibrateOff:Q5e,VibrateOffIcon:Q5e,Video:fa,VideoIcon:fa,VideoOff:e4e,VideoOffIcon:e4e,Videotape:t4e,VideotapeIcon:t4e,View:s4e,ViewIcon:s4e,Voicemail:n4e,VoicemailIcon:n4e,Volleyball:r4e,VolleyballIcon:r4e,Volume:o4e,Volume1:a4e,Volume1Icon:a4e,Volume2:ree,Volume2Icon:ree,VolumeIcon:o4e,VolumeOff:i4e,VolumeOffIcon:i4e,VolumeX:aee,VolumeXIcon:aee,Vote:l4e,VoteIcon:l4e,Wallet:t7,Wallet2:CO,Wallet2Icon:CO,WalletCards:c4e,WalletCardsIcon:c4e,WalletIcon:t7,WalletMinimal:CO,WalletMinimalIcon:CO,Wallpaper:d4e,WallpaperIcon:d4e,Wand:u4e,Wand2:Qx,Wand2Icon:Qx,WandIcon:u4e,WandSparkles:Qx,WandSparklesIcon:Qx,Warehouse:h4e,WarehouseIcon:h4e,WashingMachine:m4e,WashingMachineIcon:m4e,Watch:f4e,WatchIcon:f4e,Waves:p4e,WavesIcon:p4e,Waypoints:g4e,WaypointsIcon:g4e,Webcam:x4e,WebcamIcon:x4e,Webhook:v4e,WebhookIcon:v4e,WebhookOff:y4e,WebhookOffIcon:y4e,Weight:b4e,WeightIcon:b4e,Wheat:w4e,WheatIcon:w4e,WheatOff:_4e,WheatOffIcon:_4e,WholeWord:j4e,WholeWordIcon:j4e,Wifi:A4e,WifiHigh:N4e,WifiHighIcon:N4e,WifiIcon:A4e,WifiLow:k4e,WifiLowIcon:k4e,WifiOff:S4e,WifiOffIcon:S4e,WifiZero:C4e,WifiZeroIcon:C4e,Wind:T4e,WindArrowDown:E4e,WindArrowDownIcon:E4e,WindIcon:T4e,Wine:P4e,WineIcon:P4e,WineOff:M4e,WineOffIcon:M4e,Workflow:s7,WorkflowIcon:s7,Worm:I4e,WormIcon:I4e,WrapText:L4e,WrapTextIcon:L4e,Wrench:I4,WrenchIcon:I4,X:mr,XCircle:ju,XCircleIcon:ju,XIcon:mr,XOctagon:eF,XOctagonIcon:eF,XSquare:fO,XSquareIcon:fO,Youtube:uV,YoutubeIcon:uV,Zap:Qp,ZapIcon:Qp,ZapOff:R4e,ZapOffIcon:R4e,ZoomIn:JI,ZoomInIcon:JI,ZoomOut:hV,ZoomOutIcon:hV,createLucideIcon:ge,icons:E0s},Symbol.toStringTag,{value:"Module"})),XJe="-",T0s=s=>{const t=P0s(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(XJe);return o[0]===""&&o.length!==1&&o.shift(),kRt(o,t)||M0s(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},kRt=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?kRt(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(XJe);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},lgt=/^\[(.+)\]$/,M0s=s=>{if(lgt.test(s)){const t=lgt.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},P0s=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return L0s(Object.entries(s.classGroups),n).forEach(([i,l])=>{TVe(l,r,i,t)}),r},TVe=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:cgt(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(I0s(a)){TVe(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{TVe(l,cgt(t,i),n,r)})})},cgt=(s,t)=>{let n=s;return t.split(XJe).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},I0s=s=>s.isThemeGetter,L0s=(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,R0s=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)}}},SRt="!",D0s=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 v=0;vu?h-u:void 0;return{modifiers:c,hasImportantModifier:f,baseClassName:g,maybePostfixModifierPosition:x}};return n?o=>n({className:o,parseClassName:l}):l},F0s=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},O0s=s=>({cache:R0s(s.cacheSize),parseClassName:D0s(s),...T0s(s)}),z0s=/\s+/,B0s=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(z0s);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 v=F0s(u).join(":"),y=h?v+SRt:v,b=y+x;if(i.includes(b))continue;i.push(b);const w=a(x,g);for(let S=0;S0?" "+o:o)}return o};function $0s(){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=O0s(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=B0s(c,n);return a(c,u),u}return function(){return i($0s.apply(null,arguments))}}const fp=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},ARt=/^\[(?:([a-z-]+):)?(.+)\]$/i,q0s=/^\d+\/\d+$/,V0s=new Set(["px","full","screen"]),H0s=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,G0s=/\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$/,W0s=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,K0s=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Y0s=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Y3=s=>mV(s)||V0s.has(s)||q0s.test(s),fM=s=>zW(s,"length",nvs),mV=s=>!!s&&!Number.isNaN(Number(s)),xze=s=>zW(s,"number",mV),mZ=s=>!!s&&Number.isInteger(Number(s)),Z0s=s=>s.endsWith("%")&&mV(s.slice(0,-1)),Id=s=>ARt.test(s),pM=s=>H0s.test(s),X0s=new Set(["length","size","percentage"]),Q0s=s=>zW(s,X0s,ERt),J0s=s=>zW(s,"position",ERt),evs=new Set(["image","url"]),tvs=s=>zW(s,evs,avs),svs=s=>zW(s,"",rvs),fZ=()=>!0,zW=(s,t,n)=>{const r=ARt.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},nvs=s=>G0s.test(s)&&!W0s.test(s),ERt=()=>!1,rvs=s=>K0s.test(s),avs=s=>Y0s.test(s),ivs=()=>{const s=fp("colors"),t=fp("spacing"),n=fp("blur"),r=fp("brightness"),a=fp("borderColor"),i=fp("borderRadius"),l=fp("borderSpacing"),o=fp("borderWidth"),c=fp("contrast"),d=fp("grayscale"),u=fp("hueRotate"),h=fp("invert"),m=fp("gap"),f=fp("gradientColorStops"),g=fp("gradientColorStopPositions"),x=fp("inset"),v=fp("margin"),y=fp("opacity"),b=fp("padding"),w=fp("saturate"),S=fp("scale"),A=fp("sepia"),E=fp("skew"),I=fp("space"),P=fp("translate"),R=()=>["auto","contain","none"],D=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto",Id,t],U=()=>[Id,t],W=()=>["",Y3,fM],V=()=>["auto",mV,Id],G=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Z=()=>["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"],le=()=>["","0",Id],re=()=>["auto","avoid","all","avoid-page","page","left","right","column"],te=()=>[mV,Id];return{cacheSize:500,separator:":",theme:{colors:[fZ],spacing:[Y3,fM],blur:["none","",pM,Id],brightness:te(),borderColor:[s],borderRadius:["none","","full",pM,Id],borderSpacing:U(),borderWidth:W(),contrast:te(),grayscale:le(),hueRotate:te(),invert:le(),gap:U(),gradientColorStops:[s],gradientColorStopPositions:[Z0s,fM],inset:O(),margin:O(),opacity:te(),padding:U(),saturate:te(),scale:te(),sepia:le(),skew:te(),space:U(),translate:U()},classGroups:{aspect:[{aspect:["auto","square","video",Id]}],container:["container"],columns:[{columns:[pM]}],"break-after":[{"break-after":re()}],"break-before":[{"break-before":re()}],"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(),Id]}],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",mZ,Id]}],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",Id]}],grow:[{grow:le()}],shrink:[{shrink:le()}],order:[{order:["first","last","none",mZ,Id]}],"grid-cols":[{"grid-cols":[fZ]}],"col-start-end":[{col:["auto",{span:["full",mZ,Id]},Id]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[fZ]}],"row-start-end":[{row:["auto",{span:[mZ,Id]},Id]}],"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",Id]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Id]}],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:[v]}],mx:[{mx:[v]}],my:[{my:[v]}],ms:[{ms:[v]}],me:[{me:[v]}],mt:[{mt:[v]}],mr:[{mr:[v]}],mb:[{mb:[v]}],ml:[{ml:[v]}],"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",Id,t]}],"min-w":[{"min-w":[Id,t,"min","max","fit"]}],"max-w":[{"max-w":[Id,t,"none","full","min","max","fit","prose",{screen:[pM]},pM]}],h:[{h:[Id,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Id,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Id,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Id,t,"auto","min","max","fit"]}],"font-size":[{text:["base",pM,fM]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",xze]}],"font-family":[{font:[fZ]}],"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",Id]}],"line-clamp":[{"line-clamp":["none",mV,xze]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Y3,Id]}],"list-image":[{"list-image":["none",Id]}],"list-style-type":[{list:["none","disc","decimal",Id]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Z(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Y3,fM]}],"underline-offset":[{"underline-offset":["auto",Y3,Id]}],"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",Id]}],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",Id]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...G(),J0s]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Q0s]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},tvs]}],"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":[y]}],"border-style":[{border:[...Z(),"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":[y]}],"divide-style":[{divide:Z()}],"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:["",...Z()]}],"outline-offset":[{"outline-offset":[Y3,Id]}],"outline-w":[{outline:[Y3,fM]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[Y3,fM]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",pM,svs]}],"shadow-color":[{shadow:[fZ]}],opacity:[{opacity:[y]}],"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",pM,Id]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[h]}],saturate:[{saturate:[w]}],sepia:[{sepia:[A]}],"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":[y]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[A]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[l]}],"border-spacing-x":[{"border-spacing-x":[l]}],"border-spacing-y":[{"border-spacing-y":[l]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Id]}],duration:[{duration:te()}],ease:[{ease:["linear","in","out","in-out",Id]}],delay:[{delay:te()}],animate:[{animate:["none","spin","ping","pulse","bounce",Id]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[mZ,Id]}],"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",Id]}],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",Id]}],"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",Id]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[Y3,fM,xze]}],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"]}}},ovs=U0s(ivs);function Pt(...s){return ovs(sd(s))}function Xm(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 dgt(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function Fte(s){return s?s.replace(/<[^>]*>/g,""):""}const lvs=S0s,TRt=j.forwardRef(({className:s,...t},n)=>e.jsx(gRt,{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}));TRt.displayName=gRt.displayName;const cvs=AB("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"}}),MRt=j.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(xRt,{ref:r,className:Pt(cvs({variant:t}),s),...n}));MRt.displayName=xRt.displayName;const dvs=j.forwardRef(({className:s,...t},n)=>e.jsx(bRt,{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}));dvs.displayName=bRt.displayName;const PRt=j.forwardRef(({className:s,...t},n)=>e.jsx(_Rt,{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(mr,{className:"h-4 w-4"})}));PRt.displayName=_Rt.displayName;const IRt=j.forwardRef(({className:s,...t},n)=>e.jsx(yRt,{ref:n,className:Pt("text-sm font-semibold",s),...t}));IRt.displayName=yRt.displayName;const LRt=j.forwardRef(({className:s,...t},n)=>e.jsx(vRt,{ref:n,className:Pt("text-sm opacity-90",s),...t}));LRt.displayName=vRt.displayName;function uvs(){const{toasts:s}=Bi();return e.jsxs(lvs,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(MRt,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx(IRt,{children:n}),r&&e.jsx(LRt,{children:r})]}),a,e.jsx(PRt,{})]},t)}),e.jsx(TRt,{})]})}var ugt=["light","dark"],hvs="(prefers-color-scheme: dark)",mvs=j.createContext(void 0),fvs={setTheme:s=>{},themes:[]},pvs=()=>{var s;return(s=j.useContext(mvs))!=null?s:fvs};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?ugt.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,v=!0)=>{let y=l?l[g]:g,b=x?g+"|| ''":`'${y}'`,w="";return a&&v&&!x&&ugt.includes(g)&&(w+=`d.style.colorScheme = '${g}';`),n==="class"?x||y?w+=`c.add(${b})`:w+="null":y&&(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='${hvs}',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 gvs=s=>{switch(s){case"success":return vvs;case"info":return _vs;case"warning":return bvs;case"error":return wvs;default:return null}},xvs=Array(12).fill(0),yvs=({visible:s,className:t})=>Kt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},Kt.createElement("div",{className:"sonner-spinner"},xvs.map((n,r)=>Kt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),vvs=Kt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Kt.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"})),bvs=Kt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Kt.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"})),_vs=Kt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Kt.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"})),wvs=Kt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Kt.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"})),jvs=Kt.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"},Kt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Kt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Nvs=()=>{let[s,t]=Kt.useState(document.hidden);return Kt.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},MVe=1,kvs=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:MVe++,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],Kt.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(Cvs(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)||MVe++;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}},ow=new kvs,Svs=(s,t)=>{let n=(t==null?void 0:t.id)||MVe++;return ow.addToast({title:s,...t,id:n}),n},Cvs=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",Avs=Svs,Evs=()=>ow.toasts,Tvs=()=>ow.getActiveToasts(),ne=Object.assign(Avs,{success:ow.success,info:ow.info,warning:ow.warning,error:ow.error,custom:ow.custom,message:ow.message,promise:ow.promise,dismiss:ow.dismiss,loading:ow.loading},{getHistory:Evs,getToasts:Tvs});function Mvs(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))}Mvs(`: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 cce(s){return s.label!==void 0}var Pvs=3,Ivs="32px",Lvs="16px",hgt=4e3,Rvs=356,Dvs=14,Fvs=20,Ovs=200;function Xk(...s){return s.filter(Boolean).join(" ")}function zvs(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var Bvs=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:m,toast:f,unstyled:g,interacting:x,setHeights:v,visibleToasts:y,heights:b,index:w,toasts:S,expanded:A,removeToast:E,defaultRichColors:I,closeButton:P,style:R,cancelButtonStyle:D,actionButtonStyle:O,className:U="",descriptionClassName:W="",duration:V,position:G,gap:Z,loadingIcon:X,expandByDefault:ae,classNames:le,icons:re,closeButtonAriaLabel:te="Close toast",pauseWhenPageIsHidden:J}=s,[ce,ve]=Kt.useState(null),[fe,ue]=Kt.useState(null),[be,Ee]=Kt.useState(!1),[ke,Ie]=Kt.useState(!1),[Fe,Ne]=Kt.useState(!1),[Be,Se]=Kt.useState(!1),[Ae,Ce]=Kt.useState(!1),[qe,ze]=Kt.useState(0),[Ve,ht]=Kt.useState(0),Qe=Kt.useRef(f.duration||V||hgt),at=Kt.useRef(null),rt=Kt.useRef(null),Ke=w===0,Je=w+1<=y,ft=f.type,gt=f.dismissible!==!1,es=f.className||"",Ht=f.descriptionClassName||"",as=Kt.useMemo(()=>b.findIndex(Ks=>Ks.toastId===f.id)||0,[b,f.id]),bs=Kt.useMemo(()=>{var Ks;return(Ks=f.closeButton)!=null?Ks:P},[f.closeButton,P]),Ut=Kt.useMemo(()=>f.duration||V||hgt,[f.duration,V]),Ft=Kt.useRef(0),is=Kt.useRef(0),jt=Kt.useRef(0),zs=Kt.useRef(null),[yt,gs]=G.split("-"),Ss=Kt.useMemo(()=>b.reduce((Ks,Cn,Rr)=>Rr>=as?Ks:Ks+Cn.height,0),[b,as]),Ds=Nvs(),Bt=f.invert||m,zt=ft==="loading";is.current=Kt.useMemo(()=>as*Z+Ss,[as,Ss]),Kt.useEffect(()=>{Qe.current=Ut},[Ut]),Kt.useEffect(()=>{Ee(!0)},[]),Kt.useEffect(()=>{let Ks=rt.current;if(Ks){let Cn=Ks.getBoundingClientRect().height;return ht(Cn),v(Rr=>[{toastId:f.id,height:Cn,position:f.position},...Rr]),()=>v(Rr=>Rr.filter(ia=>ia.toastId!==f.id))}},[v,f.id]),Kt.useLayoutEffect(()=>{if(!be)return;let Ks=rt.current,Cn=Ks.style.height;Ks.style.height="auto";let Rr=Ks.getBoundingClientRect().height;Ks.style.height=Cn,ht(Rr),v(ia=>ia.find(Hs=>Hs.toastId===f.id)?ia.map(Hs=>Hs.toastId===f.id?{...Hs,height:Rr}:Hs):[{toastId:f.id,height:Rr,position:f.position},...ia])},[be,f.title,f.description,v,f.id]);let vs=Kt.useCallback(()=>{Ie(!0),ze(is.current),v(Ks=>Ks.filter(Cn=>Cn.toastId!==f.id)),setTimeout(()=>{E(f)},Ovs)},[f,E,v,is]);Kt.useEffect(()=>{if(f.promise&&ft==="loading"||f.duration===1/0||f.type==="loading")return;let Ks;return A||x||J&&Ds?(()=>{if(jt.current{var Cn;(Cn=f.onAutoClose)==null||Cn.call(f,f),vs()},Qe.current)),()=>clearTimeout(Ks)},[A,x,f,ft,J,Ds,vs]),Kt.useEffect(()=>{f.delete&&vs()},[vs,f.delete]);function dn(){var Ks,Cn,Rr;return re!=null&&re.loading?Kt.createElement("div",{className:Xk(le==null?void 0:le.loader,(Ks=f==null?void 0:f.classNames)==null?void 0:Ks.loader,"sonner-loader"),"data-visible":ft==="loading"},re.loading):X?Kt.createElement("div",{className:Xk(le==null?void 0:le.loader,(Cn=f==null?void 0:f.classNames)==null?void 0:Cn.loader,"sonner-loader"),"data-visible":ft==="loading"},X):Kt.createElement(yvs,{className:Xk(le==null?void 0:le.loader,(Rr=f==null?void 0:f.classNames)==null?void 0:Rr.loader),visible:ft==="loading"})}return Kt.createElement("li",{tabIndex:0,ref:rt,className:Xk(U,es,le==null?void 0:le.toast,(t=f==null?void 0:f.classNames)==null?void 0:t.toast,le==null?void 0:le.default,le==null?void 0:le[ft],(n=f==null?void 0:f.classNames)==null?void 0:n[ft]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:I,"data-styled":!(f.jsx||f.unstyled||g),"data-mounted":be,"data-promise":!!f.promise,"data-swiped":Ae,"data-removed":ke,"data-visible":Je,"data-y-position":yt,"data-x-position":gs,"data-index":w,"data-front":Ke,"data-swiping":Fe,"data-dismissible":gt,"data-type":ft,"data-invert":Bt,"data-swipe-out":Be,"data-swipe-direction":fe,"data-expanded":!!(A||ae&&be),style:{"--index":w,"--toasts-before":w,"--z-index":S.length-w,"--offset":`${ke?qe:is.current}px`,"--initial-height":ae?"auto":`${Ve}px`,...R,...f.style},onDragEnd:()=>{Ne(!1),ve(null),zs.current=null},onPointerDown:Ks=>{zt||!gt||(at.current=new Date,ze(is.current),Ks.target.setPointerCapture(Ks.pointerId),Ks.target.tagName!=="BUTTON"&&(Ne(!0),zs.current={x:Ks.clientX,y:Ks.clientY}))},onPointerUp:()=>{var Ks,Cn,Rr,ia;if(Be||!gt)return;zs.current=null;let Hs=Number(((Ks=rt.current)==null?void 0:Ks.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Br=Number(((Cn=rt.current)==null?void 0:Cn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Ur=new Date().getTime()-((Rr=at.current)==null?void 0:Rr.getTime()),Wn=ce==="x"?Hs:Br,Sn=Math.abs(Wn)/Ur;if(Math.abs(Wn)>=Fvs||Sn>.11){ze(is.current),(ia=f.onDismiss)==null||ia.call(f,f),ue(ce==="x"?Hs>0?"right":"left":Br>0?"down":"up"),vs(),Se(!0),Ce(!1);return}Ne(!1),ve(null)},onPointerMove:Ks=>{var Cn,Rr,ia,Hs;if(!zs.current||!gt||((Cn=window.getSelection())==null?void 0:Cn.toString().length)>0)return;let Br=Ks.clientY-zs.current.y,Ur=Ks.clientX-zs.current.x,Wn=(Rr=s.swipeDirections)!=null?Rr:zvs(G);!ce&&(Math.abs(Ur)>1||Math.abs(Br)>1)&&ve(Math.abs(Ur)>Math.abs(Br)?"x":"y");let Sn={x:0,y:0};ce==="y"?(Wn.includes("top")||Wn.includes("bottom"))&&(Wn.includes("top")&&Br<0||Wn.includes("bottom")&&Br>0)&&(Sn.y=Br):ce==="x"&&(Wn.includes("left")||Wn.includes("right"))&&(Wn.includes("left")&&Ur<0||Wn.includes("right")&&Ur>0)&&(Sn.x=Ur),(Math.abs(Sn.x)>0||Math.abs(Sn.y)>0)&&Ce(!0),(ia=rt.current)==null||ia.style.setProperty("--swipe-amount-x",`${Sn.x}px`),(Hs=rt.current)==null||Hs.style.setProperty("--swipe-amount-y",`${Sn.y}px`)}},bs&&!f.jsx?Kt.createElement("button",{"aria-label":te,"data-disabled":zt,"data-close-button":!0,onClick:zt||!gt?()=>{}:()=>{var Ks;vs(),(Ks=f.onDismiss)==null||Ks.call(f,f)},className:Xk(le==null?void 0:le.closeButton,(a=f==null?void 0:f.classNames)==null?void 0:a.closeButton)},(i=re==null?void 0:re.close)!=null?i:jvs):null,f.jsx||j.isValidElement(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:Kt.createElement(Kt.Fragment,null,ft||f.icon||f.promise?Kt.createElement("div",{"data-icon":"",className:Xk(le==null?void 0:le.icon,(l=f==null?void 0:f.classNames)==null?void 0:l.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||dn():null,f.type!=="loading"?f.icon||(re==null?void 0:re[ft])||gvs(ft):null):null,Kt.createElement("div",{"data-content":"",className:Xk(le==null?void 0:le.content,(o=f==null?void 0:f.classNames)==null?void 0:o.content)},Kt.createElement("div",{"data-title":"",className:Xk(le==null?void 0:le.title,(c=f==null?void 0:f.classNames)==null?void 0:c.title)},typeof f.title=="function"?f.title():f.title),f.description?Kt.createElement("div",{"data-description":"",className:Xk(W,Ht,le==null?void 0:le.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&&cce(f.cancel)?Kt.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||D,onClick:Ks=>{var Cn,Rr;cce(f.cancel)&>&&((Rr=(Cn=f.cancel).onClick)==null||Rr.call(Cn,Ks),vs())},className:Xk(le==null?void 0:le.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&&cce(f.action)?Kt.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||O,onClick:Ks=>{var Cn,Rr;cce(f.action)&&((Rr=(Cn=f.action).onClick)==null||Rr.call(Cn,Ks),!Ks.defaultPrevented&&vs())},className:Xk(le==null?void 0:le.actionButton,(h=f==null?void 0:f.classNames)==null?void 0:h.actionButton)},f.action.label):null))};function mgt(){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 $vs(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?Lvs:Ivs;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 Uvs=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=Pvs,toastOptions:x,dir:v=mgt(),gap:y=Dvs,loadingIcon:b,icons:w,containerAriaLabel:S="Notifications",pauseWhenPageIsHidden:A}=s,[E,I]=Kt.useState([]),P=Kt.useMemo(()=>Array.from(new Set([r].concat(E.filter(J=>J.position).map(J=>J.position)))),[E,r]),[R,D]=Kt.useState([]),[O,U]=Kt.useState(!1),[W,V]=Kt.useState(!1),[G,Z]=Kt.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),X=Kt.useRef(null),ae=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),le=Kt.useRef(null),re=Kt.useRef(!1),te=Kt.useCallback(J=>{I(ce=>{var ve;return(ve=ce.find(fe=>fe.id===J.id))!=null&&ve.delete||ow.dismiss(J.id),ce.filter(({id:fe})=>fe!==J.id)})},[]);return Kt.useEffect(()=>ow.subscribe(J=>{if(J.dismiss){I(ce=>ce.map(ve=>ve.id===J.id?{...ve,delete:!0}:ve));return}setTimeout(()=>{I6t.flushSync(()=>{I(ce=>{let ve=ce.findIndex(fe=>fe.id===J.id);return ve!==-1?[...ce.slice(0,ve),{...ce[ve],...J},...ce.slice(ve+1)]:[J,...ce]})})})}),[]),Kt.useEffect(()=>{if(u!=="system"){Z(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Z("dark"):Z("light")),typeof window>"u")return;let J=window.matchMedia("(prefers-color-scheme: dark)");try{J.addEventListener("change",({matches:ce})=>{Z(ce?"dark":"light")})}catch{J.addListener(({matches:ve})=>{try{Z(ve?"dark":"light")}catch(fe){console.error(fe)}})}},[u]),Kt.useEffect(()=>{E.length<=1&&U(!1)},[E]),Kt.useEffect(()=>{let J=ce=>{var ve,fe;a.every(ue=>ce[ue]||ce.code===ue)&&(U(!0),(ve=X.current)==null||ve.focus()),ce.code==="Escape"&&(document.activeElement===X.current||(fe=X.current)!=null&&fe.contains(document.activeElement))&&U(!1)};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)},[a]),Kt.useEffect(()=>{if(X.current)return()=>{le.current&&(le.current.focus({preventScroll:!0}),le.current=null,re.current=!1)}},[X.current]),Kt.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 ve;let[fe,ue]=J.split("-");return E.length?Kt.createElement("ol",{key:J,dir:v==="auto"?mgt():v,tabIndex:-1,ref:X,className:o,"data-sonner-toaster":!0,"data-theme":G,"data-y-position":fe,"data-lifted":O&&E.length>1&&!i,"data-x-position":ue,style:{"--front-toast-height":`${((ve=R[0])==null?void 0:ve.height)||0}px`,"--width":`${Rvs}px`,"--gap":`${y}px`,...f,...$vs(c,d)},onBlur:be=>{re.current&&!be.currentTarget.contains(be.relatedTarget)&&(re.current=!1,le.current&&(le.current.focus({preventScroll:!0}),le.current=null))},onFocus:be=>{be.target instanceof HTMLElement&&be.target.dataset.dismissible==="false"||re.current||(re.current=!0,le.current=be.relatedTarget)},onMouseEnter:()=>U(!0),onMouseMove:()=>U(!0),onMouseLeave:()=>{W||U(!1)},onDragEnd:()=>U(!1),onPointerDown:be=>{be.target instanceof HTMLElement&&be.target.dataset.dismissible==="false"||V(!0)},onPointerUp:()=>V(!1)},E.filter(be=>!be.position&&ce===0||be.position===J).map((be,Ee)=>{var ke,Ie;return Kt.createElement(Bvs,{key:be.id,icons:w,index:Ee,toast:be,defaultRichColors:h,duration:(ke=x==null?void 0:x.duration)!=null?ke:m,className:x==null?void 0:x.className,descriptionClassName:x==null?void 0:x.descriptionClassName,invert:n,visibleToasts:g,closeButton:(Ie=x==null?void 0:x.closeButton)!=null?Ie: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==be.position),heights:R.filter(Fe=>Fe.position==be.position),setHeights:D,expandByDefault:i,gap:y,loadingIcon:b,expanded:O,pauseWhenPageIsHidden:A,swipeDirections:s.swipeDirections})})):null}))});const qvs=({...s})=>{const{theme:t="system"}=pvs();return e.jsx(Uvs,{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 Vvs=Object.defineProperty,Hvs=(s,t)=>Vvs(s,"name",{value:t,configurable:!0}),Gvs=jB[" useId ".trim().toString()]||(()=>{}),Wvs=0;function cy(s){const[t,n]=j.useState(Gvs());return Af(()=>{s||n(r=>r??String(Wvs++))},[s]),s||(t?`radix-${t}`:"")}Hvs(cy,"useId");var Kvs=Object.defineProperty,h_=(s,t)=>Kvs(s,"name",{value:t,configurable:!0}),yze="focusScope.autoFocusOnMount",vze="focusScope.autoFocusOnUnmount",fgt={bubbles:!1,cancelable:!0},BIe=j.forwardRef(h_(function(t,n){const{loop:r=!1,trapped:a=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...o}=t,[c,d]=j.useState(null),u=Kp(i),h=Kp(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 v=function(S){if(g.paused||!c)return;const A=S.target;c.contains(A)?m.current=A:NA(m.current,{select:!0})},y=function(S){if(g.paused||!c)return;const A=S.relatedTarget;A!==null&&(c.contains(A)||NA(m.current,{select:!0}))},b=function(S){if(document.activeElement===document.body)for(const E of S)E.removedNodes.length>0&&NA(c)};h_(v,"handleFocusIn"),h_(y,"handleFocusOut"),h_(b,"handleMutations"),document.addEventListener("focusin",v),document.addEventListener("focusout",y);const w=new MutationObserver(b);return c&&w.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",v),document.removeEventListener("focusout",y),w.disconnect()}}},[a,c,g.paused]),j.useEffect(()=>{if(c){pgt.add(g);const v=document.activeElement;if(!c.contains(v)){const b=new CustomEvent(yze,fgt);c.addEventListener(yze,u),c.dispatchEvent(b),b.defaultPrevented||(RRt(BRt(QJe(c)),{select:!0}),document.activeElement===v&&NA(c))}return()=>{c.removeEventListener(yze,u),setTimeout(()=>{const b=new CustomEvent(vze,fgt);c.addEventListener(vze,h),c.dispatchEvent(b),b.defaultPrevented||NA(v??document.body,{select:!0}),c.removeEventListener(vze,h),pgt.remove(g)},0)}}},[c,u,h,g]);const x=j.useCallback(v=>{if(!r&&!a||g.paused)return;const y=v.key==="Tab"&&!v.altKey&&!v.ctrlKey&&!v.metaKey,b=document.activeElement;if(y&&b){const w=v.currentTarget,[S,A]=DRt(w);S&&A?!v.shiftKey&&b===A?(v.preventDefault(),r&&NA(S,{select:!0})):v.shiftKey&&b===S&&(v.preventDefault(),r&&NA(A,{select:!0})):b===w&&v.preventDefault()}},[r,a,g.paused]);return e.jsx(Ei.div,{tabIndex:-1,...o,ref:f,onKeyDown:x})},"FocusScope"));function RRt(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(NA(r,{select:t}),document.activeElement!==n)return}h_(RRt,"focusFirst");function DRt(s){const t=QJe(s),n=PVe(t,s),r=PVe(t.reverse(),s);return[n,r]}h_(DRt,"getTabbableEdges");function QJe(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:h_(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}h_(QJe,"getTabbableCandidates");function PVe(s,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of s)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):FRt(r,{upTo:t})))return r}h_(PVe,"findVisible");function FRt(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}h_(FRt,"isHidden");function ORt(s){return s instanceof HTMLInputElement&&"select"in s}h_(ORt,"isSelectableInput");function NA(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&ORt(s)&&t&&s.select()}}h_(NA,"focus");var pgt=zRt();function zRt(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=IVe(s,t),s.unshift(t)},remove(t){var n;s=IVe(s,t),(n=s[0])==null||n.resume()}}}h_(zRt,"createFocusScopesStack");function IVe(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}h_(IVe,"arrayRemove");function BRt(s){return s.filter(t=>t.tagName!=="A")}h_(BRt,"removeLinks");var Yvs=Object.defineProperty,JJe=(s,t)=>Yvs(s,"name",{value:t,configurable:!0}),dce=0,QC=null;function Zvs(s){return BW(),s.children}JJe(Zvs,"FocusGuards");function BW(){j.useEffect(()=>{QC||(QC={start:LVe(),end:LVe()});const{start:s,end:t}=QC;return document.body.firstElementChild!==s&&document.body.insertAdjacentElement("afterbegin",s),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),dce++,()=>{dce===1&&(QC==null||QC.start.remove(),QC==null||QC.end.remove(),QC=null),dce=Math.max(0,dce-1)}},[])}JJe(BW,"useFocusGuards");function LVe(){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}JJe(LVe,"createFocusGuard");var i4=function(){return i4=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return mbs;var t=fbs(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])}},gbs=VRt(),fV="data-scroll-locked",xbs=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(Qvs,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat(fV,`] { 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(D4e,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(F4e,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(D4e," .").concat(D4e,` { right: 0 `).concat(r,`; } .`).concat(F4e," .").concat(F4e,` { margin-right: 0 `).concat(r,`; } body[`).concat(fV,`] { `).concat(Jvs,": ").concat(o,`px; } `)},xgt=function(){var s=parseInt(document.body.getAttribute(fV)||"0",10);return isFinite(s)?s:0},ybs=function(){j.useEffect(function(){return document.body.setAttribute(fV,(xgt()+1).toString()),function(){var s=xgt()-1;s<=0?document.body.removeAttribute(fV):document.body.setAttribute(fV,s.toString())}},[])},vbs=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;ybs();var i=j.useMemo(function(){return pbs(a)},[a]);return j.createElement(gbs,{styles:xbs(i,!t,a,n?"":"!important")})},RVe=!1;if(typeof window<"u")try{var uce=Object.defineProperty({},"passive",{get:function(){return RVe=!0,!0}});window.addEventListener("test",uce,uce),window.removeEventListener("test",uce,uce)}catch{RVe=!1}var i$=RVe?{passive:!1}:!1,bbs=function(s){return s.tagName==="TEXTAREA"},HRt=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!bbs(s)&&n[t]==="visible")},_bs=function(s){return HRt(s,"overflowY")},wbs=function(s){return HRt(s,"overflowX")},ygt=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=GRt(s,r);if(a){var i=WRt(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},jbs=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},Nbs=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},GRt=function(s,t){return s==="v"?_bs(t):wbs(t)},WRt=function(s,t){return s==="v"?jbs(t):Nbs(t)},kbs=function(s,t){return s==="h"&&t==="rtl"?-1:1},Sbs=function(s,t,n,r,a){var i=kbs(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=WRt(s,o),g=f[0],x=f[1],v=f[2],y=x-v-i*g;(g||y)&&GRt(s,o)&&(h+=y,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},hce=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},vgt=function(s){return[s.deltaX,s.deltaY]},bgt=function(s){return s&&"current"in s?s.current:s},Cbs=function(s,t){return s[0]===t[0]&&s[1]===t[1]},Abs=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},Ebs=0,o$=[];function Tbs(s){var t=j.useRef([]),n=j.useRef([0,0]),r=j.useRef(),a=j.useState(Ebs++)[0],i=j.useState(VRt)[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=Xvs([s.lockRef.current],(s.shards||[]).map(bgt),!0).filter(Boolean);return x.forEach(function(v){return v.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),x.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=j.useCallback(function(x,v){if("touches"in x&&x.touches.length===2||x.type==="wheel"&&x.ctrlKey)return!l.current.allowPinchZoom;var y=hce(x),b=n.current,w="deltaX"in x?x.deltaX:b[0]-y[0],S="deltaY"in x?x.deltaY:b[1]-y[1],A,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=ygt(I,E);if(!O)return!0;if(O?A=I:(A=I==="v"?"h":"v",O=ygt(I,E)),!O)return!1;if(!r.current&&"changedTouches"in x&&(w||S)&&(r.current=A),!A)return!0;var U=r.current||A;return Sbs(U,v,x,U==="h"?w:S)},[]),c=j.useCallback(function(x){var v=x;if(!(!o$.length||o$[o$.length-1]!==i)){var y="deltaY"in v?vgt(v):hce(v),b=t.current.filter(function(A){return A.name===v.type&&(A.target===v.target||v.target===A.shadowParent)&&Cbs(A.delta,y)})[0];if(b&&b.should){v.cancelable&&v.preventDefault();return}if(!b){var w=(l.current.shards||[]).map(bgt).filter(Boolean).filter(function(A){return A.contains(v.target)}),S=w.length>0?o(v,w[0]):!l.current.noIsolation;S&&v.cancelable&&v.preventDefault()}}},[]),d=j.useCallback(function(x,v,y,b){var w={name:x,delta:v,target:y,should:b,shadowParent:Mbs(y)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(S){return S!==w})},1)},[]),u=j.useCallback(function(x){n.current=hce(x),r.current=void 0},[]),h=j.useCallback(function(x){d(x.type,vgt(x),x.target,o(x,s.lockRef.current))},[]),m=j.useCallback(function(x){d(x.type,hce(x),x.target,o(x,s.lockRef.current))},[]);j.useEffect(function(){return o$.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:m}),document.addEventListener("wheel",c,i$),document.addEventListener("touchmove",c,i$),document.addEventListener("touchstart",u,i$),function(){o$=o$.filter(function(x){return x!==i}),document.removeEventListener("wheel",c,i$),document.removeEventListener("touchmove",c,i$),document.removeEventListener("touchstart",u,i$)}},[]);var f=s.removeScrollBar,g=s.inert;return j.createElement(j.Fragment,null,g?j.createElement(i,{styles:Abs(a)}):null,f?j.createElement(vbs,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function Mbs(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const Pbs=ibs(qRt,Tbs);var gae=j.forwardRef(function(s,t){return j.createElement($Ie,i4({},s,{ref:t,sideCar:Pbs}))});gae.classNames=$Ie.classNames;var Ibs=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},l$=new WeakMap,mce=new WeakMap,fce={},jze=0,KRt=function(s){return s&&(s.host||KRt(s.parentNode))},Lbs=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=KRt(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})},Rbs=function(s,t,n,r){var a=Lbs(t,Array.isArray(s)?s:[s]);fce[n]||(fce[n]=new WeakMap);var i=fce[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=(l$.get(m)||0)+1,v=(i.get(m)||0)+1;l$.set(m,x),i.set(m,v),l.push(m),x===1&&g&&mce.set(m,!0),v===1&&m.setAttribute(n,"true"),g||m.setAttribute(r,"true")}catch(y){console.error("aria-hidden: cannot operate on ",m,y)}})};return u(t),o.clear(),jze++,function(){l.forEach(function(h){var m=l$.get(h)-1,f=i.get(h)-1;l$.set(h,m),i.set(h,f),m||(mce.has(h)||h.removeAttribute(r),mce.delete(h)),f||h.removeAttribute(n)}),jze--,jze||(l$=new WeakMap,l$=new WeakMap,mce=new WeakMap,fce={})}},UIe=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=Ibs(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live], script"))),Rbs(r,a,n,"aria-hidden")):function(){return null}},Dbs=Object.defineProperty,D2=(s,t)=>Dbs(s,"name",{value:t,configurable:!0}),eet="Dialog",[YRt,ZRt]=ep(eet),[Fbs,vC]=YRt(eet),qIe=D2(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]=dy({prop:r,defaultProp:a??!1,onChange:i,caller:eet}),[h,m]=j.useState(0),[f,g]=j.useState(0);return e.jsx(Fbs,{scope:t,triggerRef:o,contentRef:c,contentId:cy(),titleId:cy(),descriptionId:cy(),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"),Obs="DialogTrigger",tet=j.forwardRef(D2(function(t,n){const{__scopeDialog:r,...a}=t,i=vC(Obs,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":HIe(i.open),...a,ref:l,onClick:Ra(t.onClick,i.onOpenToggle)})},"DialogTrigger")),XRt="DialogPortal",[zbs,QRt]=YRt(XRt,{forceMount:void 0}),VIe=D2(s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=vC(XRt,t);return e.jsx(zbs,{scope:t,forceMount:n,children:j.Children.map(r,l=>e.jsx(my,{present:n||i.open,children:e.jsx(fae,{asChild:!0,container:a,children:l})}))})},"DialogPortal"),DVe="DialogOverlay",$W=j.forwardRef(D2(function(t,n){const r=QRt(DVe,t.__scopeDialog),{forceMount:a=r.forceMount,...i}=t,l=vC(DVe,t.__scopeDialog);return l.modal?e.jsx(my,{present:a||l.open,children:e.jsx($bs,{...i,ref:n})}):null},"DialogOverlay")),Bbs=hC("DialogOverlay.RemoveScroll"),$bs=j.forwardRef(D2(function(t,n){const{__scopeDialog:r,...a}=t,i=vC(DVe,r),l=X6t(),o=Vo(n,l);return e.jsx(gae,{as:Bbs,allowPinchZoom:!0,shards:[i.contentRef],children:e.jsx(Ei.div,{"data-state":HIe(i.open),...a,ref:o,style:{pointerEvents:"auto",...a.style}})})},"DialogOverlayImpl")),Ote="DialogContent",UW=j.forwardRef(D2(function(t,n){const r=QRt(Ote,t.__scopeDialog),{forceMount:a=r.forceMount,...i}=t,l=vC(Ote,t.__scopeDialog);return e.jsx(my,{present:a||l.open,children:l.modal?e.jsx(Ubs,{...i,ref:n}):e.jsx(qbs,{...i,ref:n})})},"DialogContent")),Ubs=j.forwardRef(D2(function(t,n){const r=vC(Ote,t.__scopeDialog),a=j.useRef(null),i=Vo(n,r.contentRef,a);return j.useEffect(()=>{const l=a.current;if(l)return UIe(l)},[]),e.jsx(JRt,{...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")),qbs=j.forwardRef(D2(function(t,n){const r=vC(Ote,t.__scopeDialog),a=j.useRef(!1),i=j.useRef(!1);return e.jsx(JRt,{...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")),JRt=j.forwardRef(D2(function(t,n){const{__scopeDialog:r,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,...o}=t,c=vC(Ote,r);return BW(),e.jsx(e.Fragment,{children:e.jsx(BIe,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:i,onUnmountAutoFocus:l,children:e.jsx(CB,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionPresent?c.descriptionId:void 0,"aria-labelledby":c.titlePresent?c.titleId:void 0,"data-state":HIe(c.open),...o,ref:n,deferPointerDownOutside:!0,onDismiss:()=>c.onOpenChange(!1)})})})},"DialogContentImpl")),Vbs="DialogTitle",xae=j.forwardRef(D2(function(t,n){const{__scopeDialog:r,...a}=t,i=vC(Vbs,r),{setTitleCount:l}=i;return Af(()=>(l(o=>o+1),()=>l(o=>o-1)),[l]),e.jsx(Ei.h2,{id:i.titleId,...a,ref:n})},"DialogTitle")),Hbs="DialogDescription",yae=j.forwardRef(D2(function(t,n){const{__scopeDialog:r,...a}=t,i=vC(Hbs,r),{setDescriptionCount:l}=i;return Af(()=>(l(o=>o+1),()=>l(o=>o-1)),[l]),e.jsx(Ei.p,{id:i.descriptionId,...a,ref:n})},"DialogDescription")),Gbs="DialogClose",vae=j.forwardRef(D2(function(t,n){const{__scopeDialog:r,...a}=t,i=vC(Gbs,r);return e.jsx(Ei.button,{type:"button",...a,ref:n,onClick:Ra(t.onClick,()=>i.onOpenChange(!1))})},"DialogClose"));function HIe(s){return s?"open":"closed"}D2(HIe,"getState");var Wbs=Object.defineProperty,NT=(s,t)=>Wbs(s,"name",{value:t,configurable:!0}),Kbs="AlertDialog",[Ybs,GNr]=ep(Kbs,[ZRt]),kT=ZRt(),Zbs=NT(s=>{const{__scopeAlertDialog:t,...n}=s,r=kT(t);return e.jsx(qIe,{...r,...n,modal:!0})},"AlertDialog"),Xbs=j.forwardRef(NT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=kT(r);return e.jsx(tet,{...i,...a,ref:n})},"AlertDialogTrigger")),Qbs=NT(s=>{const{__scopeAlertDialog:t,...n}=s,r=kT(t);return e.jsx(VIe,{...r,...n})},"AlertDialogPortal"),Jbs=j.forwardRef(NT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=kT(r);return e.jsx($W,{...i,...a,ref:n})},"AlertDialogOverlay")),e1s="AlertDialogContent",[t1s,s1s]=Ybs(e1s),n1s=j.forwardRef(NT(function(t,n){const{__scopeAlertDialog:r,children:a,...i}=t,l=kT(r),o=j.useRef(null),c=Vo(n,o),d=j.useRef(null);return e.jsx(t1s,{scope:r,cancelRef:d,children:e.jsx(UW,{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")),r1s=j.forwardRef(NT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=kT(r);return e.jsx(xae,{...i,...a,ref:n})},"AlertDialogTitle")),a1s=j.forwardRef(NT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=kT(r);return e.jsx(yae,{...i,...a,ref:n})},"AlertDialogDescription")),i1s=j.forwardRef(NT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=kT(r);return e.jsx(vae,{...i,...a,ref:n})},"AlertDialogAction")),o1s="AlertDialogCancel",l1s=j.forwardRef(NT(function(t,n){const{__scopeAlertDialog:r,...a}=t,{cancelRef:i}=s1s(o1s,r),l=kT(r),o=Vo(n,i);return e.jsx(vae,{...l,...a,ref:o})},"AlertDialogCancel")),c1s=Zbs,d1s=Xbs,u1s=Qbs,eDt=Jbs,tDt=n1s,sDt=i1s,nDt=l1s,rDt=r1s,aDt=a1s;const dG=AB("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?VJe:"button";return e.jsx(l,{className:Pt(dG({variant:t,size:n,className:s})),ref:i,...a})});$.displayName="Button";const fc=c1s,Ag=d1s,h1s=u1s,iDt=j.forwardRef(({className:s,...t},n)=>e.jsx(eDt,{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}));iDt.displayName=eDt.displayName;const sc=j.forwardRef(({className:s,...t},n)=>e.jsxs(h1s,{children:[e.jsx(iDt,{}),e.jsx(tDt,{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})]}));sc.displayName=tDt.displayName;const nc=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col space-y-2 text-center sm:text-left",s),...t});nc.displayName="AlertDialogHeader";const rc=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});rc.displayName="AlertDialogFooter";const ac=j.forwardRef(({className:s,...t},n)=>e.jsx(rDt,{ref:n,className:Pt("text-lg font-semibold",s),...t}));ac.displayName=rDt.displayName;const ic=j.forwardRef(({className:s,...t},n)=>e.jsx(aDt,{ref:n,className:Pt("text-sm text-muted-foreground",s),...t}));ic.displayName=aDt.displayName;const Yl=j.forwardRef(({className:s,...t},n)=>e.jsx(sDt,{ref:n,className:Pt(dG(),s),...t}));Yl.displayName=sDt.displayName;const oc=j.forwardRef(({className:s,...t},n)=>e.jsx(nDt,{ref:n,className:Pt(dG({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));oc.displayName=nDt.displayName;let oEe=null;const m1s=["delete","remove","revoke","cannot be undone","permanently"];function mo(s,t={}){const n=typeof s=="string"?{description:s,...t}:s,r=`${n.title??""} ${n.description??""}`.toLowerCase(),a=n.destructive??m1s.some(i=>r.includes(i));return new Promise(i=>{if(!oEe){i(window.confirm(n.description??n.title??"Are you sure?"));return}oEe({...n,destructive:a,resolve:i})})}function f1s(){const[s,t]=j.useState(null);j.useEffect(()=>(oEe=a=>t(a),()=>{oEe=null}),[]);const n=a=>{s==null||s.resolve(a),t(null)},r=!!(s!=null&&s.destructive);return e.jsx(fc,{open:!!s,onOpenChange:a=>!a&&n(!1),children:e.jsxs(sc,{className:"sm:max-w-md",children:[e.jsx(nc,{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(Al,{className:"h-5 w-5"})}),e.jsxs("div",{className:"space-y-1.5 text-left",children:[e.jsx(ac,{children:(s==null?void 0:s.title)??(r?"Are you sure?":"Please confirm")}),(s==null?void 0:s.description)&&e.jsx(ic,{className:"leading-relaxed",children:s.description})]})]})}),e.jsxs(rc,{className:"gap-2 sm:gap-2",children:[e.jsx(oc,{onClick:()=>n(!1),children:(s==null?void 0:s.cancelText)??"Cancel"}),e.jsx(Yl,{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 p1s=["top","right","bottom","left"],vL=Math.min,OE=Math.max,lEe=Math.round,pce=Math.floor,zE=s=>({x:s,y:s}),g1s={left:"right",right:"left",bottom:"top",top:"bottom"};function oDt(s,t,n){return OE(s,vL(t,n))}function oT(s,t){return typeof s=="function"?s(t):s}function bL(s){return s.split("-")[0]}function qW(s){return s.split("-")[1]}function set(s){return s==="x"?"y":"x"}function net(s){return s==="y"?"height":"width"}function m4(s){const t=s[0];return t==="t"||t==="b"?"y":"x"}function ret(s){return set(m4(s))}function x1s(s,t,n){n===void 0&&(n=!1);const r=qW(s),a=ret(s),i=net(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=cEe(l)),[l,cEe(l)]}function y1s(s){const t=cEe(s);return[FVe(s),t,FVe(t)]}function FVe(s){return s.includes("start")?s.replace("start","end"):s.replace("end","start")}const _gt=["left","right"],wgt=["right","left"],v1s=["top","bottom"],b1s=["bottom","top"];function _1s(s,t,n){switch(s){case"top":case"bottom":return n?t?wgt:_gt:t?_gt:wgt;case"left":case"right":return t?v1s:b1s;default:return[]}}function w1s(s,t,n,r){const a=qW(s);let i=_1s(bL(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(FVe)))),i}function cEe(s){const t=bL(s);return g1s[t]+s.slice(t.length)}function j1s(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 lDt(s){return typeof s!="number"?j1s(s):{top:s,right:s,bottom:s,left:s}}function dEe(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 jgt(s,t,n){let{reference:r,floating:a}=s;const i=m4(t),l=ret(t),o=net(l),c=bL(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=qW(t);return g&&(f[l]+=m*(g==="end"?1:-1)*(n&&d?-1:1)),f}async function N1s(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}=oT(t,s),g=lDt(f),v=o[m?h==="floating"?"reference":"floating":h],y=dEe(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(v)))==null||n?v:v.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},A=dEe(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:b,offsetParent:w,strategy:c}):b);return{top:(y.top-A.top+g.top)/S.y,bottom:(A.bottom-y.bottom+g.bottom)/S.y,left:(y.left-A.left+g.left)/S.x,right:(A.right-y.right+g.right)/S.x}}const k1s=50,S1s=async(s,t,n)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:l}=n,o=l.detectOverflow?l:{...l,detectOverflow:N1s},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}=jgt(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}=oT(s,t)||{};if(d==null)return{};const h=lDt(u),m={x:n,y:r},f=ret(a),g=net(f),x=await l.getDimensions(d),v=f==="y",y=v?"top":"left",b=v?"bottom":"right",w=v?"clientHeight":"clientWidth",S=i.reference[g]+i.reference[f]-m[f]-i.floating[g],A=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-A/2,R=I/2-x[g]/2-1,D=vL(h[y],R),O=vL(h[b],R),U=I-x[g]-O,W=I/2-x[g]/2+P,V=oDt(D,W,U),G=!c.arrow&&qW(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!==m4(G):!1)||D.every(ae=>m4(ae.placement)===b?ae.overflows[0]>0:!0)))return{data:{index:V,overflows:D},reset:{placement:G}};let Z=(U=D.filter(X=>X.overflows[0]<=0).sort((X,ae)=>X.overflows[1]-ae.overflows[1])[0])==null?void 0:U.placement;if(!Z)switch(f){case"bestFit":{var W;const X=(W=D.filter(ae=>{if(E){const le=m4(ae.placement);return le===b||le==="y"}return!0}).map(ae=>[ae.placement,ae.overflows.filter(le=>le>0).reduce((le,re)=>le+re,0)]).sort((ae,le)=>ae[1]-le[1])[0])==null?void 0:W[0];X&&(Z=X);break}case"initialPlacement":Z=o;break}if(a!==Z)return{reset:{placement:Z}}}return{}}}};function Ngt(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function kgt(s){return p1s.some(t=>s[t]>=0)}const E1s=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n,platform:r}=t,{strategy:a="referenceHidden",...i}=oT(s,t);switch(a){case"referenceHidden":{const l=await r.detectOverflow(t,{...i,elementContext:"reference"}),o=Ngt(l,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:kgt(o)}}}case"escaped":{const l=await r.detectOverflow(t,{...i,altBoundary:!0}),o=Ngt(l,n.floating);return{data:{escapedOffsets:o,escaped:kgt(o)}}}default:return{}}}}},cDt=new Set(["left","top"]);async function T1s(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=bL(n),o=qW(n),c=m4(n)==="y",d=cDt.has(l)?-1:1,u=i&&c?-1:1,h=oT(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 M1s=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 T1s(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}}}}},P1s=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}=oT(s,t),u={x:n,y:r},h=await i.detectOverflow(t,d),m=m4(a),f=set(m);let g=u[f],x=u[m];const v=(b,w)=>oDt(w+h[b==="y"?"top":"left"],w,w-h[b==="y"?"bottom":"right"]);l&&(g=v(f,g)),o&&(x=v(m,x));const y=c.fn({...t,[f]:g,[m]:x});return{...y,data:{x:y.x-n,y:y.y-r,enabled:{[f]:l,[m]:o}}}}}},I1s=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}=oT(s,t),m={x:a,y:i},f=m4(l),g=set(f);let x=m[g],v=m[f];const y=oT(d,t),b=typeof y=="number"?{mainAxis:y,crossAxis:0}:{mainAxis:(n=y.mainAxis)!=null?n:0,crossAxis:(r=y.crossAxis)!=null?r:0};if(u){const A=g==="y"?"height":"width",E=o.reference[g]-o.floating[A]+b.mainAxis,I=o.reference[g]+o.reference[A]-b.mainAxis;xI&&(x=I)}if(h){var w,S;const A=g==="y"?"width":"height",E=cDt.has(bL(l)),I=o.reference[f]-o.floating[A]+(E&&((w=c.offset)==null?void 0:w[f])||0)+(E?0:b.crossAxis),P=o.reference[f]+o.reference[A]+(E?0:((S=c.offset)==null?void 0:S[f])||0)-(E?b.crossAxis:0);vP&&(v=P)}return{[g]:x,[f]:v}}}},L1s=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}=oT(s,t),c=await a.detectOverflow(t,o),d=bL(n),u=qW(n),h=m4(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 v=f-c.top-c.bottom,y=m-c.left-c.right,b=vL(f-c[g],v),w=vL(m-c[x],y),S=t.middlewareData.shift,A=!S;let E=b,I=w;S!=null&&S.enabled.x&&(I=y),S!=null&&S.enabled.y&&(E=v),A&&!u&&(h?I=m-2*OE(c.left,c.right):E=f-2*OE(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 GIe(){return typeof window<"u"}function VW(s){return dDt(s)?(s.nodeName||"").toLowerCase():"#document"}function Ew(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function ST(s){var t;return(t=(dDt(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function dDt(s){return GIe()?s instanceof Node||s instanceof Ew(s).Node:!1}function U4(s){return GIe()?s instanceof Element||s instanceof Ew(s).Element:!1}function XL(s){return GIe()?s instanceof HTMLElement||s instanceof Ew(s).HTMLElement:!1}function Sgt(s){return!GIe()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof Ew(s).ShadowRoot}function WIe(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=q4(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&a!=="inline"&&a!=="contents"}function R1s(s){return/^(table|td|th)$/.test(VW(s))}function KIe(s){try{if(s.matches(":popover-open"))return!0}catch{}try{return s.matches(":modal")}catch{return!1}}const D1s=/transform|translate|scale|rotate|perspective|filter/,F1s=/paint|layout|strict|content/,iR=s=>!!s&&s!=="none";let Nze;function aet(s){const t=U4(s)?q4(s):s;return iR(t.transform)||iR(t.translate)||iR(t.scale)||iR(t.rotate)||iR(t.perspective)||!iet()&&(iR(t.backdropFilter)||iR(t.filter))||D1s.test(t.willChange||"")||F1s.test(t.contain||"")}function O1s(s){let t=L7(s);for(;XL(t)&&!zte(t);){if(aet(t))return t;if(KIe(t))return null;t=L7(t)}return null}function iet(){return Nze==null&&(Nze=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Nze}function zte(s){return/^(html|body|#document)$/.test(VW(s))}function q4(s){return Ew(s).getComputedStyle(s)}function YIe(s){return U4(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function L7(s){if(VW(s)==="html")return s;const t=s.assignedSlot||s.parentNode||Sgt(s)&&s.host||ST(s);return Sgt(t)?t.host:t}function uDt(s){const t=L7(s);return zte(t)?(s.ownerDocument||s).body:XL(t)&&WIe(t)?t:uDt(t)}function Bte(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=uDt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=Ew(a);if(i){const o=OVe(l);return t.concat(l,l.visualViewport||[],WIe(a)?a:[],o&&n?Bte(o):[])}else return t.concat(a,Bte(a,[],n))}function OVe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function hDt(s){const t=q4(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=XL(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=lEe(n)!==i||lEe(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function oet(s){return U4(s)?s:s.contextElement}function pV(s){const t=oet(s);if(!XL(t))return zE(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=hDt(t);let l=(i?lEe(n.width):n.width)/r,o=(i?lEe(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const z1s=zE(0);function mDt(s){const t=Ew(s);return!iet()||!t.visualViewport?z1s:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function B1s(s,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Ew(s)}function R7(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=oet(s);let l=zE(1);t&&(r?U4(r)&&(l=pV(r)):l=pV(s));const o=B1s(i,n,r)?mDt(i):zE(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=Ew(i),f=U4(r)?Ew(r):r;let g=m,x=OVe(g);for(;x&&f!==g;){const v=pV(x),y=x.getBoundingClientRect(),b=q4(x),w=y.left+(x.clientLeft+parseFloat(b.paddingLeft))*v.x,S=y.top+(x.clientTop+parseFloat(b.paddingTop))*v.y;c*=v.x,d*=v.y,u*=v.x,h*=v.y,c+=w,d+=S,g=Ew(x),x=OVe(g)}}return dEe({width:u,height:h,x:c,y:d})}function ZIe(s,t){const n=YIe(s).scrollLeft;return t?t.left+n:R7(ST(s)).left+n}function fDt(s,t){const n=s.getBoundingClientRect(),r=n.left+t.scrollLeft-ZIe(s,n),a=n.top+t.scrollTop;return{x:r,y:a}}function $1s(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=ST(r),o=t?KIe(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=zE(1);const u=zE(0),h=XL(r);if((h||!i)&&((VW(r)!=="body"||WIe(l))&&(c=YIe(r)),h)){const f=R7(r);d=pV(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const m=l&&!h&&!i?fDt(l,c):zE(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 U1s(s){return s.getClientRects?Array.from(s.getClientRects()):[]}function q1s(s){const t=YIe(s),n=s.ownerDocument.body,r=OE(s.scrollWidth,s.clientWidth,n.scrollWidth,n.clientWidth),a=OE(s.scrollHeight,s.clientHeight,n.scrollHeight,n.clientHeight);let i=-t.scrollLeft+ZIe(s);const l=-t.scrollTop;return q4(n).direction==="rtl"&&(i+=OE(s.clientWidth,n.clientWidth)-r),{width:r,height:a,x:i,y:l}}const V1s=25;function H1s(s,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",a=Ew(s),i=ST(s),l=a.visualViewport;let o=i.clientWidth,c=i.clientHeight,d=0,u=0;if(l){const m=!iet()||t==="fixed";r?m||(d=-l.offsetLeft,u=-l.offsetTop):(o=l.width,c=l.height,m&&(d=l.offsetLeft,u=l.offsetTop))}if(ZIe(i)<=0){const m=i.ownerDocument,f=m.body,g=getComputedStyle(f),x=m.compatMode==="CSS1Compat"&&parseFloat(g.marginLeft)+parseFloat(g.marginRight)||0,v=Math.abs(i.clientWidth-f.clientWidth-x),y=getComputedStyle(i).scrollbarGutter==="stable both-edges"?v/2:v;y<=V1s&&(o-=y)}return{width:o,height:c,x:d,y:u}}function G1s(s,t){const n=R7(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=pV(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 Cgt(s,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=H1s(s,n,t);else if(t==="document")r=q1s(ST(s));else if(U4(t))r=G1s(t,n);else{const a=mDt(s);r={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return dEe(r)}function W1s(s,t){const n=t.get(s);if(n)return n;let r=Bte(s,[],!1).filter(o=>U4(o)&&VW(o)!=="body"),a=null;const i=q4(s).position==="fixed";let l=i?L7(s):s;for(;U4(l)&&!zte(l);){const o=q4(l),c=aet(l),d=a?a.position:i?"fixed":"";!c&&(d==="fixed"||d==="absolute"&&o.position==="static")?r=r.filter(h=>h!==l):a=o,l=L7(l)}return t.set(s,r),r}function K1s(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?KIe(t)?[]:W1s(t,this._c):[].concat(n),r],o=Cgt(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=Ew(s),d=()=>o(n);return c.addEventListener("resize",d),o(!0),()=>{c.removeEventListener("resize",d),l()}}function t_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=oet(s),u=a||i?[...d?Bte(d):[],...t?Bte(t):[]]:[];u.forEach(y=>{a&&y.addEventListener("scroll",n),i&&y.addEventListener("resize",n)});const h=d&&o?e_s(d,n,i):null;let m=-1,f=null;l&&(f=new ResizeObserver(y=>{let[b]=y;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?R7(s):null;c&&v();function v(){const y=R7(s);x&&!gDt(x,y)&&n(),x=y,g=requestAnimationFrame(v)}return n(),()=>{var y;u.forEach(b=>{a&&b.removeEventListener("scroll",n),i&&b.removeEventListener("resize",n)}),h==null||h(),(y=f)==null||y.disconnect(),f=null,c&&cancelAnimationFrame(g)}}const s_s=M1s,n_s=P1s,r_s=A1s,a_s=L1s,i_s=E1s,Egt=C1s,o_s=I1s,l_s=(s,t,n)=>{const r=new Map,a=n??{},i={...J1s,...a.platform,_c:r};return S1s(s,t,{...a,platform:i})};var c_s=typeof document<"u",d_s=function(){},O4e=c_s?j.useLayoutEffect:d_s;function uEe(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(!uEe(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)&&!uEe(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function xDt(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function Tgt(s,t){const n=xDt(s);return Math.round(t*n)/n}function Sze(s){const t=j.useRef(s);return O4e(()=>{t.current=s}),t}function u_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);uEe(m,r)||f(r);const[g,x]=j.useState(null),[v,y]=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,y(ae))},[]),S=i||g,A=l||v,E=j.useRef(null),I=j.useRef(null),P=j.useRef(u),R=c!=null,D=Sze(c),O=Sze(a),U=Sze(d),W=j.useCallback(()=>{if(!E.current||!I.current)return;const ae={placement:t,strategy:n,middleware:m};O.current&&(ae.platform=O.current),l_s(E.current,I.current,ae).then(le=>{const re={...le,isPositioned:U.current!==!1};V.current&&!uEe(P.current,re)&&(P.current=re,yv.flushSync(()=>{h(re)}))})},[m,t,n,O,U]);O4e(()=>{d===!1&&P.current.isPositioned&&(P.current.isPositioned=!1,h(ae=>({...ae,isPositioned:!1})))},[d]);const V=j.useRef(!1);O4e(()=>(V.current=!0,()=>{V.current=!1}),[]),O4e(()=>{if(S&&(E.current=S),A&&(I.current=A),S&&A){if(D.current)return D.current(S,A,W);W()}},[S,A,W,D,R]);const G=j.useMemo(()=>({reference:E,floating:I,setReference:b,setFloating:w}),[b,w]),Z=j.useMemo(()=>({reference:S,floating:A}),[S,A]),X=j.useMemo(()=>{const ae={position:n,left:0,top:0};if(!Z.floating)return ae;const le=Tgt(Z.floating,u.x),re=Tgt(Z.floating,u.y);return o?{...ae,transform:"translate("+le+"px, "+re+"px)",...xDt(Z.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:le,top:re}},[n,o,Z.floating,u.x,u.y]);return j.useMemo(()=>({...u,update:W,refs:G,elements:Z,floatingStyles:X}),[u,W,G,Z,X])}const h_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?Egt({element:r.current,padding:a}).fn(n):{}:r?Egt({element:r,padding:a}).fn(n):{}}}},m_s=(s,t)=>{const n=s_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},f_s=(s,t)=>{const n=n_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},p_s=(s,t)=>({fn:o_s(s).fn,options:[s,t]}),g_s=(s,t)=>{const n=r_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},x_s=(s,t)=>{const n=a_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},y_s=(s,t)=>{const n=i_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},v_s=(s,t)=>{const n=h_s(s);return{name:n.name,fn:n.fn,options:[s,t]}};var b_s=Object.defineProperty,__s=(s,t)=>b_s(s,"name",{value:t,configurable:!0});function HW(s){const[t,n]=j.useState(void 0);return Af(()=>{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}__s(HW,"useSize");var w_s=Object.defineProperty,eL=(s,t)=>w_s(s,"name",{value:t,configurable:!0}),yDt="Popper",[vDt,n3]=ep(yDt),[j_s,bDt]=vDt(yDt),N_s=eL(s=>{const{__scopePopper:t,children:n}=s,[r,a]=j.useState(null),[i,l]=j.useState(void 0);return e.jsx(j_s,{scope:t,anchor:r,onAnchorChange:a,placementState:i,setPlacementState:l,children:n})},"Popper"),k_s="PopperAnchor",S_s=j.forwardRef(eL(function(t,n){const{__scopePopper:r,virtualRef:a,...i}=t,l=bDt(k_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&&XIe(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")),_Dt="PopperContent",[C_s,WNr]=vDt(_Dt),A_s=j.forwardRef(eL(function(t,n){var ke,Ie,Fe,Ne,Be,Se,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,...v}=t,y=bDt(_Dt,r),[b,w]=j.useState(null),S=Vo(n,w),[A,E]=j.useState(null),I=HW(A),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(wDt),altBoundary:W},{refs:G,floatingStyles:Z,placement:X,isPositioned:ae,middlewareData:le}=u_s({strategy:"fixed",placement:D,whileElementsMounted:eL((...Ce)=>t_s(...Ce,{animationFrame:g==="always"}),"whileElementsMounted"),elements:{reference:y.anchor},middleware:[m_s({mainAxis:i+R,alignmentAxis:o}),d&&f_s({mainAxis:!0,crossAxis:!1,limiter:m==="partial"?p_s():void 0,...V}),d&&g_s({...V}),x_s({...V,apply:eL(({elements:Ce,rects:qe,availableWidth:ze,availableHeight:Ve})=>{const{width:ht,height:Qe}=qe.reference,at=Ce.floating.style;at.setProperty("--radix-popper-available-width",`${ze}px`),at.setProperty("--radix-popper-available-height",`${Ve}px`),at.setProperty("--radix-popper-anchor-width",`${ht}px`),at.setProperty("--radix-popper-anchor-height",`${Qe}px`)},"apply")}),A&&v_s({element:A,padding:c}),E_s({arrowWidth:P,arrowHeight:R}),f&&y_s({strategy:"referenceHidden",...V,boundary:W?V.boundary:void 0})]}),re=y.setPlacementState;Af(()=>(re(X),()=>{re(void 0)}),[X,re]);const[te,J]=XIe(X),ce=Kp(x);Af(()=>{ae&&(ce==null||ce())},[ae,ce]);const ve=(ke=le.arrow)==null?void 0:ke.x,fe=(Ie=le.arrow)==null?void 0:Ie.y,ue=((Fe=le.arrow)==null?void 0:Fe.centerOffset)!==0,[be,Ee]=j.useState();return Af(()=>{b&&Ee(window.getComputedStyle(b).zIndex)},[b]),e.jsx("div",{ref:G.setFloating,"data-radix-popper-content-wrapper":"",style:{...Z,transform:ae?Z.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:be,"--radix-popper-transform-origin":[(Ne=le.transformOrigin)==null?void 0:Ne.x,(Be=le.transformOrigin)==null?void 0:Be.y].join(" "),...((Se=le.hide)==null?void 0:Se.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:e.jsx(C_s,{scope:r,placedSide:te,placedAlign:J,onArrowChange:E,arrowX:ve,arrowY:fe,shouldHideArrow:ue,children:e.jsx(Ei.div,{"data-side":te,"data-align":J,...v,ref:S,style:{...v.style,animation:ae?(Ae=v.style)==null?void 0:Ae.animation:"none"}})})})},"PopperContent"));function wDt(s){return s!==null}eL(wDt,"isNotNull");var E_s=eL(s=>({name:"transformOrigin",options:s,fn(t){var v,y,b;const{placement:n,rects:r,middlewareData:a}=t,l=((v=a.arrow)==null?void 0:v.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,u]=XIe(n),h={start:"0%",center:"50%",end:"100%"}[u],m=(((y=a.arrow)==null?void 0:y.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 XIe(s){const[t,n="center"]=s.split("-");return[t,n]}eL(XIe,"getSideAndAlignFromPlacement");var bae=N_s,_ae=S_s,wae=A_s,T_s=Object.defineProperty,cb=(s,t)=>T_s(s,"name",{value:t,configurable:!0}),[cet,KNr]=ep("Tooltip",[n3]),det=n3(),M_s="TooltipProvider",P_s=700,zVe="tooltip.open",[I_s,uet]=cet(M_s),L_s=cb(s=>{const{__scopeTooltip:t,delayDuration:n=P_s,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(I_s,{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"),BVe="Tooltip",[R_s,QIe]=cet(BVe),D_s=cb(s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=uet(BVe,s.__scopeTooltip),d=det(t),[u,h]=j.useState(null),[m,f]=j.useState(void 0),g=cy(),x=j.useRef(0),v=l??c.disableHoverableContent,y=o??c.delayDuration,b=j.useRef(!1),[w,S]=dy({prop:r,defaultProp:a??!1,onChange:cb(D=>{D?(c.onOpen(),document.dispatchEvent(new CustomEvent(zVe))):c.onClose(),i==null||i(D)},"onChange"),caller:BVe}),A=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},y)},[y,S]);j.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]);const R=m??g;return e.jsx(bae,{...d,children:e.jsx(R_s,{scope:t,contentId:R,setContentId:f,open:w,stateAttribute:A,trigger:u,onTriggerChange:h,onTriggerEnter:j.useCallback(()=>{c.isOpenDelayedRef.current?P():E()},[c.isOpenDelayedRef,P,E]),onTriggerLeave:j.useCallback(()=>{v?I():(window.clearTimeout(x.current),x.current=0)},[I,v]),onOpen:E,onClose:I,disableHoverableContent:v,children:n})})},"Tooltip"),Mgt="TooltipTrigger",F_s=j.forwardRef(cb(function(t,n){const{__scopeTooltip:r,...a}=t,i=QIe(Mgt,r),l=uet(Mgt,r),o=det(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(_ae,{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")),O_s="TooltipPortal",[YNr,z_s]=cet(O_s,{forceMount:void 0}),$te="TooltipContent",B_s=j.forwardRef(cb(function(t,n){const r=z_s($te,t.__scopeTooltip),{forceMount:a=r.forceMount,side:i="top",...l}=t,o=QIe($te,t.__scopeTooltip);return e.jsx(my,{present:a||o.open,children:o.disableHoverableContent?e.jsx(jDt,{side:i,...l,ref:n}):e.jsx($_s,{side:i,...l,ref:n})})},"TooltipContent")),$_s=j.forwardRef(cb(function(t,n){const r=QIe($te,t.__scopeTooltip),a=uet($te,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,v)=>{const y=x.currentTarget,b={x:x.clientX,y:x.clientY},w=NDt(b,y.getBoundingClientRect()),S=kDt(b,w),A=SDt(v.getBoundingClientRect()),E=ADt([...S,...A]);c(E),m(!0)},[m]);return j.useEffect(()=>()=>f(),[f]),j.useEffect(()=>{if(d&&h){const x=cb(y=>g(y,h),"handleTriggerLeave"),v=cb(y=>g(y,d),"handleContentLeave");return d.addEventListener("pointerleave",x),h.addEventListener("pointerleave",v),()=>{d.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",v)}}},[d,h,g,f]),j.useEffect(()=>{if(o){const x=cb(v=>{const y=v.target,b={x:v.clientX,y:v.clientY},w=(d==null?void 0:d.contains(y))||(h==null?void 0:h.contains(y)),S=!CDt(b,o);w?f():S&&(f(),u())},"handleTrackPointerGrace");return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[d,h,o,u,f]),e.jsx(jDt,{...t,ref:l})},"TooltipContentHoverable")),U_s=U6t("TooltipContent"),jDt=j.forwardRef(cb(function(t,n){const{__scopeTooltip:r,children:a,"aria-label":i,id:l,onEscapeKeyDown:o,onPointerDownOutside:c,...d}=t,u=QIe($te,r),h=det(r),{onClose:m}=u;j.useEffect(()=>(document.addEventListener(zVe,m),()=>document.removeEventListener(zVe,m)),[m]),j.useEffect(()=>{if(u.trigger){const g=cb(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 Af(()=>(f(l),()=>{f(void 0)}),[l,f]),e.jsx(CB,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:g=>g.preventDefault(),onDismiss:m,children:e.jsxs(wae,{"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(U_s,{children:a}),i?e.jsx(n0s,{id:u.contentId,role:"tooltip",children:i}):null]})})},"TooltipContentImpl"));function NDt(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")}}cb(NDt,"getExitSideFromRect");function kDt(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}cb(kDt,"getPaddedExitPoints");function SDt(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}]}cb(SDt,"getPointsFromRect");function CDt(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}cb(CDt,"isPointInPolygon");function ADt(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),EDt(t)}cb(ADt,"getHull");function EDt(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)}cb(EDt,"getHullPresorted");var q_s=L_s,V_s=D_s,H_s=F_s,TDt=B_s;const vk=q_s,ry=V_s,ay=H_s,vx=j.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(TDt,{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}));vx.displayName=TDt.displayName;const MDt=j.createContext(void 0),Zt=s=>{const t=j.useContext(MDt);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},G_s=({client:s,children:t})=>(j.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(MDt.Provider,{value:s,children:t})),W_s={setTimeout:(s,t)=>setTimeout(s,t),clearTimeout:s=>clearTimeout(s),setInterval:(s,t)=>setInterval(s,t),clearInterval:s=>clearInterval(s)};var EP,KQe,cIt,K_s=(cIt=class{constructor(){ys(this,EP,W_s);ys(this,KQe,!1)}setTimeoutProvider(s){Yt(this,EP,s)}setTimeout(s,t){return ye(this,EP).setTimeout(s,t)}clearTimeout(s){ye(this,EP).clearTimeout(s)}setInterval(s,t){return ye(this,EP).setInterval(s,t)}clearInterval(s){ye(this,EP).clearInterval(s)}},EP=new WeakMap,KQe=new WeakMap,cIt);const t8=new K_s;function Y_s(s){setTimeout(s,0)}const Z_s=typeof window>"u"||"Deno"in globalThis;function a_(){}function X_s(s,t){return typeof s=="function"?s(t):s}function PDt(s){return typeof s=="number"&&s>=0&&s!==1/0}function IDt(s,t){return Math.max(s+(t||0)-Date.now(),0)}function qp(s,t){return typeof s=="function"?s(t):s}function Pgt(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==het(l,t.options))return!1}else if(!uG(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 Igt(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(D7(t.options.mutationKey)!==D7(i))return!1}else if(!uG(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function het(s,t){return((t==null?void 0:t.queryKeyHashFn)||D7)(s)}function D7(s){return JSON.stringify(s,(t,n)=>$Ve(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function uG(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=Lgt(s)&&Lgt(t);if(!r&&!($Ve(s)&&$Ve(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{t8.setTimeout(t,s)})}function UVe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?LDt(s,t):t}function ews(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function tws(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}const met=Symbol();function RDt(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===met?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function fet(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 nws=()=>Z_s;const pet=()=>nws();var GW=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(){}},j8,TP,GV,dIt,rws=(dIt=class extends GW{constructor(){super();ys(this,j8);ys(this,TP);ys(this,GV);Yt(this,GV,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){ye(this,TP)||this.setEventListener(ye(this,GV))}onUnsubscribe(){var t;this.hasListeners()||((t=ye(this,TP))==null||t.call(this),Yt(this,TP,void 0))}setEventListener(t){var n;Yt(this,GV,t),(n=ye(this,TP))==null||n.call(this),Yt(this,TP,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){ye(this,j8)!==t&&(Yt(this,j8,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof ye(this,j8)=="boolean"?ye(this,j8):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},j8=new WeakMap,TP=new WeakMap,GV=new WeakMap,dIt);const get=new rws,aws=Y_s;function iws(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=aws;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 y0=iws();var WV,MP,KV,uIt,ows=(uIt=class extends GW{constructor(){super();ys(this,WV,!0);ys(this,MP);ys(this,KV);Yt(this,KV,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,MP)||this.setEventListener(ye(this,KV))}onUnsubscribe(){var t;this.hasListeners()||((t=ye(this,MP))==null||t.call(this),Yt(this,MP,void 0))}setEventListener(t){var n;Yt(this,KV,t),(n=ye(this,MP))==null||n.call(this),Yt(this,MP,t(this.setOnline.bind(this)))}setOnline(t){ye(this,WV)!==t&&(Yt(this,WV,t),this.listeners.forEach(n=>{n(t)}))}isOnline(){return ye(this,WV)}},WV=new WeakMap,MP=new WeakMap,KV=new WeakMap,uIt);const hEe=new ows;function lws(s){return Math.min(1e3*2**s,3e4)}function DDt(s){return(s??"online")==="online"?hEe.isOnline():!0}var qVe=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function FDt(s){let t=!1,n=0,r,a="pending",i,l;const o=new Promise((b,w)=>{i=b,l=w});o.catch(a_);const c=()=>a!=="pending",d=b=>{var w;if(!c()){const S=new qVe(b);x(S),(w=s.onCancel)==null||w.call(s,S)}},u=()=>{t=!0},h=()=>{t=!1},m=()=>get.isFocused()&&(s.networkMode==="always"||hEe.isOnline())&&s.canRun(),f=()=>DDt(s.networkMode)&&s.canRun(),g=b=>{c()||(r==null||r(),a="resolved",i(b))},x=b=>{c()||(r==null||r(),a="rejected",l(b))},v=()=>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)}),y=()=>{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 A=s.retry??(pet()?0:3),E=s.retryDelay??lws,I=typeof E=="function"?E(n,S):E,P=A===!0||typeof A=="number"&&nm()?void 0:v()).then(()=>{t?x(S):y()})})};return{promise:o,status:()=>a,cancel:d,continue:()=>(r==null||r(),o),cancelRetry:u,continueRetry:h,canStart:f,start:()=>(f()?y():v().then(y),o)}}var N8,hIt,ODt=(hIt=class{constructor(){ys(this,N8)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),PDt(this.gcTime)&&Yt(this,N8,t8.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(pet()?1/0:3e5))}clearGcTimeout(){ye(this,N8)!==void 0&&(t8.clearTimeout(ye(this,N8)),Yt(this,N8,void 0))}},N8=new WeakMap,hIt);function cws(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 v=w=>{sws(w,()=>t.signal,()=>x=!0)},y=RDt(t.options,t.fetchOptions),b=async(w,S,A)=>{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:A?"backward":"forward",meta:t.options.meta};return v(O),O})(),P=await y(I),{maxPages:R}=t.options,D=A?tws:ews;return{pages:D(w.pages,P,R),pageParams:D(w.pageParams,S,R)}};if(a&&i.length){const w=a==="backward",S=w?zDt:VVe,A={pages:i,pageParams:l};o=await b(A,S(r,A),w)}else{const w=s??i.length;do{const S=c===0?l[0]??r.initialPageParam:VVe(r,o);if(c>0&&S==null)break;o=await b(o,S),c++}while(c{var x,v;return(v=(x=t.options).persister)==null?void 0:v.call(x,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function VVe(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 zDt(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 dws(s,t){return t?VVe(s,t)!=null:!1}function uws(s,t){return!t||!s.getPreviousPageParam?!1:zDt(s,t)!=null}var YV,k8,ZV,pN,S8,i0,qne,C8,pS,pA,mIt,hws=(mIt=class extends ODt{constructor(t){super();ys(this,pS);ys(this,YV);ys(this,k8);ys(this,ZV);ys(this,pN);ys(this,S8);ys(this,i0);ys(this,qne);ys(this,C8);Yt(this,C8,!1),Yt(this,qne,t.defaultOptions),this.setOptions(t.options),this.observers=[],Yt(this,S8,t.client),Yt(this,pN,ye(this,S8).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Yt(this,k8,Fgt(this.options)),this.state=t.state??ye(this,k8),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return ye(this,YV)}get promise(){var t;return(t=ye(this,i0))==null?void 0:t.promise}setOptions(t){if(this.options={...ye(this,qne),...t},t!=null&&t._type&&Yt(this,YV,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=Fgt(this.options);n.data!==void 0&&(this.setState(Dgt(n.data,n.dataUpdatedAt)),Yt(this,k8,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&ye(this,pN).remove(this)}setData(t,n){const r=UVe(this.state.data,t,this.options);return ds(this,pS,pA).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t){ds(this,pS,pA).call(this,{type:"setState",state:t})}cancel(t){var r,a;const n=(r=ye(this,i0))==null?void 0:r.promise;return(a=ye(this,i0))==null||a.cancel(t),n?n.then(a_).catch(a_):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return ye(this,k8)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>qp(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===met||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>qp(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:!IDt(this.state.dataUpdatedAt,t)}onFocus(){var t,n;(t=this.observers.find(r=>r.shouldFetchOnWindowFocus()))==null||t.refetch({cancelRefetch:!1}),(n=ye(this,i0))==null||n.continue()}onOnline(){var t,n;(t=this.observers.find(r=>r.shouldFetchOnReconnect()))==null||t.refetch({cancelRefetch:!1}),(n=ye(this,i0))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),ye(this,pN).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,i0)&&(ye(this,C8)||this.state.fetchStatus==="paused"&&this.state.status==="pending"?ye(this,i0).cancel({revert:!0}):ye(this,i0).cancelRetry()),this.scheduleGc()),ye(this,pN).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||ds(this,pS,pA).call(this,{type:"invalidate"})}async fetch(t,n){var d,u,h,m,f,g,x,v,y,b,w,S;if(this.state.fetchStatus!=="idle"&&((d=ye(this,i0))==null?void 0:d.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(ye(this,i0))return ye(this,i0).continueRetry(),ye(this,i0).promise}if(t&&this.setOptions(t),!this.options.queryFn){const A=this.observers.find(E=>E.options.queryFn);A&&this.setOptions(A.options)}const r=new AbortController,a=A=>{Object.defineProperty(A,"signal",{enumerable:!0,get:()=>(Yt(this,C8,!0),r.signal)})},i=()=>{const A=RDt(this.options,n),I=(()=>{const P={client:ye(this,S8),queryKey:this.queryKey,meta:this.meta};return a(P),P})();return Yt(this,C8,!1),this.options.persister?this.options.persister(A,I,this):A(I)},o=(()=>{const A={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:ye(this,S8),state:this.state,fetchFn:i};return a(A),A})();(u=ye(this,YV)==="infinite"?cws(this.options.pages):this.options.behavior)==null||u.onFetch(o,this),Yt(this,ZV,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((h=o.fetchOptions)==null?void 0:h.meta))&&ds(this,pS,pA).call(this,{type:"fetch",meta:(m=o.fetchOptions)==null?void 0:m.meta});const c=Yt(this,i0,FDt({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,onCancel:A=>{A instanceof qVe&&A.revert&&this.setState({...ye(this,ZV),fetchStatus:"idle"}),r.abort()},onFail:(A,E)=>{ds(this,pS,pA).call(this,{type:"failed",failureCount:A,error:E})},onPause:()=>{ds(this,pS,pA).call(this,{type:"pause"})},onContinue:()=>{ds(this,pS,pA).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const A=await c.start();if(A===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(A),(g=(f=ye(this,pN).config).onSuccess)==null||g.call(f,A,this),(v=(x=ye(this,pN).config).onSettled)==null||v.call(x,A,this.state.error,this),A}catch(A){if(A instanceof qVe){if(A.silent)return ye(this,i0).promise;if(A.revert){if(this.state.data===void 0)throw A;return this.state.data}}throw ds(this,pS,pA).call(this,{type:"error",error:A}),(b=(y=ye(this,pN).config).onError)==null||b.call(y,A,this),(S=(w=ye(this,pN).config).onSettled)==null||S.call(w,this.state.data,A,this),A}finally{ye(this,i0)===c&&Yt(this,i0,void 0),this.scheduleGc()}}},YV=new WeakMap,k8=new WeakMap,ZV=new WeakMap,pN=new WeakMap,S8=new WeakMap,i0=new WeakMap,qne=new WeakMap,C8=new WeakMap,pS=new WeakSet,pA=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,...BDt(r.data,this.options),fetchMeta:t.meta??null};case"success":const a={...r,...Dgt(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Yt(this,ZV,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),y0.batch(()=>{this.observers.slice().forEach(r=>{r.onQueryUpdate()}),ye(this,pN).notify({query:this,type:"updated",action:t})})},mIt);function BDt(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:DDt(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function Dgt(s,t){return{data:s,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Fgt(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 s_,Zu,Vne,n_,A8,XV,DA,Hne,QV,JV,E8,T8,PP,eH,am,JX,HVe,GVe,WVe,KVe,YVe,ZVe,XVe,QVe,fIt,$Dt=(fIt=class extends GW{constructor(t,n){super();ys(this,am);ys(this,s_);ys(this,Zu);ys(this,Vne);ys(this,n_);ys(this,A8);ys(this,XV);ys(this,DA);ys(this,Hne);ys(this,QV);ys(this,JV);ys(this,E8);ys(this,T8);ys(this,PP);ys(this,eH,new Set);this.options=n,Yt(this,s_,t),Yt(this,DA,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(ye(this,Zu).addObserver(this),Ogt(ye(this,Zu),this.options)?ds(this,am,JX).call(this):this.updateResult(),ds(this,am,YVe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return JVe(ye(this,Zu),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return JVe(ye(this,Zu),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,ds(this,am,ZVe).call(this),ds(this,am,XVe).call(this),ye(this,Zu).removeObserver(this)}setOptions(t){const n=this.options,r=ye(this,Zu);if(this.options=ye(this,s_).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof qp(this.options.enabled,ye(this,Zu))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");ds(this,am,QVe).call(this),ye(this,Zu).setOptions(this.options),n._defaulted&&!z4e(this.options,n)&&ye(this,s_).getQueryCache().notify({type:"observerOptionsUpdated",query:ye(this,Zu),observer:this});const a=this.hasListeners();a&&zgt(ye(this,Zu),r,this.options,n)&&ds(this,am,JX).call(this),this.updateResult(),a&&(ye(this,Zu)!==r||qp(this.options.enabled,ye(this,Zu))!==qp(n.enabled,ye(this,Zu))||qp(this.options.staleTime,ye(this,Zu))!==qp(n.staleTime,ye(this,Zu)))&&ds(this,am,GVe).call(this);const i=ds(this,am,WVe).call(this);a&&(ye(this,Zu)!==r||qp(this.options.enabled,ye(this,Zu))!==qp(n.enabled,ye(this,Zu))||i!==ye(this,PP))&&ds(this,am,KVe).call(this,i)}getOptimisticResult(t){const n=ye(this,s_).getQueryCache().build(ye(this,s_),t),r=this.createResult(n,t);return z4e(this.getCurrentResult(),r)||(Yt(this,n_,r),Yt(this,XV,this.options),Yt(this,A8,ye(this,Zu).state)),r}getCurrentResult(){return ye(this,n_)}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,eH).add(t)}getCurrentQuery(){return ye(this,Zu)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=ye(this,s_).defaultQueryOptions(t),r=ye(this,s_).getQueryCache().build(ye(this,s_),n);let a=()=>{},i;const l=new Promise(o=>{i=o,a=ye(this,s_).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 ds(this,am,JX).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),ye(this,n_)))}createResult(t,n){var E;const r=ye(this,Zu),a=this.options,i=ye(this,n_),l=ye(this,A8),o=ye(this,XV),c=t!==r?t.state:ye(this,Vne),{state:d}=t;let u={...d},h=!1,m;if(n._optimisticResults){const I=this.hasListeners(),P=!I&&Ogt(t,n),R=I&&zgt(t,r,n,a);(P||R)&&(u={...u,...BDt(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:f,errorUpdatedAt:g,status:x}=u;m=u.data;let v=!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,v=!0):I=typeof n.placeholderData=="function"?n.placeholderData((E=ye(this,JV))==null?void 0:E.state.data,ye(this,JV)):n.placeholderData,I!==void 0&&(x="success",m=UVe(i==null?void 0:i.data,I,n),h=!0)}if(n.select&&m!==void 0&&!v)if(i&&m===(l==null?void 0:l.data)&&n.select===ye(this,Hne))m=ye(this,QV);else try{Yt(this,Hne,n.select),m=n.select(m),m=UVe(i==null?void 0:i.data,m,n),Yt(this,QV,m),Yt(this,DA,null)}catch(I){Yt(this,DA,I)}else m===void 0&&Yt(this,DA,null);ye(this,DA)&&(f=ye(this,DA),m=ye(this,QV),g=Date.now(),x="error",h=!1);const y=u.fetchStatus==="fetching",b=x==="pending",w=x==="error",S=b&&y,A=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:y,isRefetching:y&&!b,isLoadingError:w&&!A,isPaused:u.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:w&&A,isStale:xet(t,n),refetch:this.refetch,isEnabled:qp(n.enabled,t)!==!1}}updateResult(){const t=ye(this,n_),n=this.createResult(ye(this,Zu),this.options);if(Yt(this,A8,ye(this,Zu).state),Yt(this,XV,this.options),ye(this,A8).data!==void 0&&Yt(this,JV,ye(this,Zu)),z4e(n,t))return;Yt(this,n_,n);const a=(()=>{if(!t)return!0;const{notifyOnChangeProps:i}=this.options,l=typeof i=="function"?i():i;if(l==="all"||!l&&!ye(this,eH).size)return!0;const o=new Set(l??ye(this,eH));return this.options.throwOnError&&o.add("error"),Object.keys(ye(this,n_)).some(c=>{const d=c;return ye(this,n_)[d]!==t[d]&&o.has(d)})})();y0.batch(()=>{a&&this.listeners.forEach(i=>{i(ye(this,n_))}),ye(this,s_).getQueryCache().notify({query:ye(this,Zu),type:"observerResultsUpdated"})})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&ds(this,am,YVe).call(this)}},s_=new WeakMap,Zu=new WeakMap,Vne=new WeakMap,n_=new WeakMap,A8=new WeakMap,XV=new WeakMap,DA=new WeakMap,Hne=new WeakMap,QV=new WeakMap,JV=new WeakMap,E8=new WeakMap,T8=new WeakMap,PP=new WeakMap,eH=new WeakMap,am=new WeakSet,JX=function(t){ds(this,am,QVe).call(this);let n=ye(this,Zu).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(a_)),n},HVe=function(t){return!pet()&&qp(this.options.enabled,ye(this,Zu))!==!1&&PDt(t)},GVe=function(){ds(this,am,ZVe).call(this);const t=qp(this.options.staleTime,ye(this,Zu));if(ye(this,n_).isStale||!ds(this,am,HVe).call(this,t))return;const n=IDt(ye(this,n_).dataUpdatedAt,t)+1;Yt(this,E8,t8.setTimeout(()=>{ye(this,n_).isStale||this.updateResult()},n))},WVe=function(){return qp(this.options.refetchInterval,ye(this,Zu))??!1},KVe=function(t){ds(this,am,XVe).call(this),Yt(this,PP,t),!(ye(this,PP)===0||!ds(this,am,HVe).call(this,ye(this,PP)))&&Yt(this,T8,t8.setInterval(()=>{(this.options.refetchIntervalInBackground||get.isFocused())&&ds(this,am,JX).call(this)},ye(this,PP)))},YVe=function(){ds(this,am,GVe).call(this),ds(this,am,KVe).call(this,ds(this,am,WVe).call(this))},ZVe=function(){ye(this,E8)!==void 0&&(t8.clearTimeout(ye(this,E8)),Yt(this,E8,void 0))},XVe=function(){ye(this,T8)!==void 0&&(t8.clearInterval(ye(this,T8)),Yt(this,T8,void 0))},QVe=function(){const t=ye(this,s_).getQueryCache().build(ye(this,s_),this.options);if(t===ye(this,Zu))return;const n=ye(this,Zu);Yt(this,Zu,t),Yt(this,Vne,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},fIt);function mws(s,t){return qp(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&qp(t.retryOnMount,s)===!1)}function Ogt(s,t){return mws(s,t)||s.state.data!==void 0&&JVe(s,t,t.refetchOnMount)}function JVe(s,t,n){if(qp(t.enabled,s)!==!1&&qp(t.staleTime,s)!=="static"){const r=qp(n,s);return r==="always"||r!==!1&&xet(s,t)}return!1}function zgt(s,t,n,r){return(s!==t||qp(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&xet(s,n)}function xet(s,t){return qp(t.enabled,s)!==!1&&s.isStaleByTime(qp(t.staleTime,s))}var fws=class extends $Dt{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:dws(t,n.data),hasPreviousPage:uws(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:m,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!m}}},Gne,P5,e1,M8,I5,OM,pIt,pws=(pIt=class extends ODt{constructor(t){super();ys(this,I5);ys(this,Gne);ys(this,P5);ys(this,e1);ys(this,M8);Yt(this,Gne,t.client),this.mutationId=t.mutationId,Yt(this,e1,t.mutationCache),Yt(this,P5,[]),this.state=t.state||UDt(),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,P5).includes(t)||(ye(this,P5).push(t),this.clearGcTimeout(),ye(this,e1).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Yt(this,P5,ye(this,P5).filter(n=>n!==t)),this.scheduleGc(),ye(this,e1).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){ye(this,P5).length||(this.state.status==="pending"?this.scheduleGc():ye(this,e1).remove(this))}continue(){var t;return((t=ye(this,M8))==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,v,y,b,w,S,A,E,I,P;const n=()=>{ds(this,I5,OM).call(this,{type:"continue"})},r={client:ye(this,Gne),meta:this.options.meta,mutationKey:this.options.mutationKey},a=Yt(this,M8,FDt({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(R,D)=>{ds(this,I5,OM).call(this,{type:"failed",failureCount:R,error:D})},onPause:()=>{ds(this,I5,OM).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>ye(this,e1).canRun(this)})),i=this.state.status==="pending",l=!a.canStart();try{if(i)n();else{ds(this,I5,OM).call(this,{type:"pending",variables:t,isPaused:l}),ye(this,e1).config.onMutate&&await ye(this,e1).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&&ds(this,I5,OM).call(this,{type:"pending",context:D,variables:t,isPaused:l})}const R=await a.start();return await((u=(d=ye(this,e1).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,e1).config).onSettled)==null?void 0:g.call(f,R,null,this.state.variables,this.state.context,this,r)),await((v=(x=this.options).onSettled)==null?void 0:v.call(x,R,null,t,this.state.context,r)),ds(this,I5,OM).call(this,{type:"success",data:R}),R}catch(R){try{await((b=(y=ye(this,e1).config).onError)==null?void 0:b.call(y,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=(A=ye(this,e1).config).onSettled)==null?void 0:E.call(A,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 ds(this,I5,OM).call(this,{type:"error",error:R}),R}finally{ye(this,M8)===a&&Yt(this,M8,void 0),ye(this,e1).runNext(this)}}},Gne=new WeakMap,P5=new WeakMap,e1=new WeakMap,M8=new WeakMap,I5=new WeakSet,OM=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),y0.batch(()=>{ye(this,P5).forEach(r=>{r.onMutationUpdate(t)}),ye(this,e1).notify({mutation:this,type:"updated",action:t})})},pIt);function UDt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var FA,gS,Wne,gIt,gws=(gIt=class extends GW{constructor(t={}){super();ys(this,FA);ys(this,gS);ys(this,Wne);this.config=t,Yt(this,FA,new Set),Yt(this,gS,new Map),Yt(this,Wne,0)}build(t,n,r){const a=new pws({client:t,mutationCache:this,mutationId:++Z0(this,Wne)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){ye(this,FA).add(t);const n=gce(t);if(typeof n=="string"){const r=ye(this,gS).get(n);r?r.push(t):ye(this,gS).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(ye(this,FA).delete(t)){const n=gce(t);if(typeof n=="string"){const r=ye(this,gS).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,gS).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){var r;const n=gce(t);if(typeof n=="string"){const a=(r=ye(this,gS).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=gce(t);return typeof n=="string"?((a=(r=ye(this,gS).get(n))==null?void 0:r.find(i=>i!==t&&i.state.isPaused))==null?void 0:a.continue())??Promise.resolve():Promise.resolve()}clear(){y0.batch(()=>{ye(this,FA).forEach(t=>{this.notify({type:"removed",mutation:t})}),ye(this,FA).clear(),ye(this,gS).clear()})}getAll(){return Array.from(ye(this,FA))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Igt(n,r))}findAll(t={}){return this.getAll().filter(n=>Igt(t,n))}notify(t){y0.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return y0.batch(()=>Promise.all(t.map(n=>n.continue().catch(a_))))}},FA=new WeakMap,gS=new WeakMap,Wne=new WeakMap,gIt);function gce(s){var t;return(t=s.options.scope)==null?void 0:t.id}var OA,IP,t1,zA,j4,eQ,eHe,xIt,xws=(xIt=class extends GW{constructor(n,r){super();ys(this,j4);ys(this,OA);ys(this,IP);ys(this,t1);ys(this,zA);Yt(this,OA,n),this.setOptions(r),this.bindMethods(),ds(this,j4,eQ).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,OA).defaultMutationOptions(n),z4e(this.options,r)||ye(this,OA).getMutationCache().notify({type:"observerOptionsUpdated",mutation:ye(this,t1),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&D7(r.mutationKey)!==D7(this.options.mutationKey)?this.reset():((a=ye(this,t1))==null?void 0:a.state.status)==="pending"&&ye(this,t1).setOptions(this.options)}onSubscribe(){this.listeners.size===1&&ye(this,t1)&&(ye(this,t1).addObserver(this),ds(this,j4,eQ).call(this))}onUnsubscribe(){var n;this.hasListeners()||(n=ye(this,t1))==null||n.removeObserver(this)}onMutationUpdate(n){ds(this,j4,eQ).call(this),ds(this,j4,eHe).call(this,n)}getCurrentResult(){return ye(this,IP)}reset(){var n;(n=ye(this,t1))==null||n.removeObserver(this),Yt(this,t1,void 0),ds(this,j4,eQ).call(this),ds(this,j4,eHe).call(this)}mutate(n,r){var a;return Yt(this,zA,r),(a=ye(this,t1))==null||a.removeObserver(this),Yt(this,t1,ye(this,OA).getMutationCache().build(ye(this,OA),this.options)),ye(this,t1).addObserver(this),ye(this,t1).execute(n)}},OA=new WeakMap,IP=new WeakMap,t1=new WeakMap,zA=new WeakMap,j4=new WeakSet,eQ=function(){var r;const n=((r=ye(this,t1))==null?void 0:r.state)??UDt();Yt(this,IP,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},eHe=function(n){y0.batch(()=>{var r,a,i,l,o,c,d,u;if(ye(this,zA)&&this.hasListeners()){const h=ye(this,IP).variables,m=ye(this,IP).context,f={client:ye(this,OA),meta:this.options.meta,mutationKey:this.options.mutationKey};if((n==null?void 0:n.type)==="success"){try{(a=(r=ye(this,zA)).onSuccess)==null||a.call(r,n.data,h,m,f)}catch(g){Promise.reject(g)}try{(l=(i=ye(this,zA)).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,zA)).onError)==null||c.call(o,n.error,h,m,f)}catch(g){Promise.reject(g)}try{(u=(d=ye(this,zA)).onSettled)==null||u.call(d,void 0,n.error,h,m,f)}catch(g){Promise.reject(g)}}}this.listeners.forEach(h=>{h(ye(this,IP))})})},xIt),L5,yIt,yws=(yIt=class extends GW{constructor(t={}){super();ys(this,L5);this.config=t,Yt(this,L5,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??het(a,n);let l=this.get(i);return l||(l=new hws({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){ye(this,L5).has(t.queryHash)||(ye(this,L5).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){ye(this,L5).get(t.queryHash)===t&&(t.destroy(),ye(this,L5).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){y0.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return ye(this,L5).get(t)}getAll(){return[...ye(this,L5).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Pgt(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Pgt(t,r)):n}notify(t){y0.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){y0.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){y0.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},L5=new WeakMap,yIt),gg,LP,RP,tH,sH,DP,nH,rH,vIt,vws=(vIt=class{constructor(s={}){ys(this,gg);ys(this,LP);ys(this,RP);ys(this,tH);ys(this,sH);ys(this,DP);ys(this,nH);ys(this,rH);Yt(this,gg,s.queryCache||new yws),Yt(this,LP,s.mutationCache||new gws),Yt(this,RP,s.defaultOptions||{}),Yt(this,tH,new Map),Yt(this,sH,new Map),Yt(this,DP,0)}mount(){Z0(this,DP)._++,ye(this,DP)===1&&(Yt(this,nH,get.subscribe(async s=>{s&&(await this.resumePausedMutations(),ye(this,gg).onFocus())})),Yt(this,rH,hEe.subscribe(async s=>{s&&(await this.resumePausedMutations(),ye(this,gg).onOnline())})))}unmount(){var s,t;Z0(this,DP)._--,ye(this,DP)===0&&((s=ye(this,nH))==null||s.call(this),Yt(this,nH,void 0),(t=ye(this,rH))==null||t.call(this),Yt(this,rH,void 0))}isFetching(s){return ye(this,gg).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return ye(this,LP).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=ye(this,gg).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=ye(this,gg).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(qp(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return ye(this,gg).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,gg).get(r.queryHash))==null?void 0:l.state.data,i=X_s(t,a);if(i!==void 0)return ye(this,gg).build(this,r).setData(i,{...n,manual:!0})}setQueriesData(s,t,n){return y0.batch(()=>ye(this,gg).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,gg).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=ye(this,gg);y0.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=ye(this,gg);return y0.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=y0.batch(()=>ye(this,gg).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then(a_).catch(a_)}invalidateQueries(s,t={}){return y0.batch(()=>(ye(this,gg).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=y0.batch(()=>ye(this,gg).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(a_)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(a_)}async query(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=ye(this,gg).build(this,t),r=n.isStaleByTime(qp(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,gg).build(this,t);return n.isStaleByTime(qp(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(a_).catch(a_)}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(a_).catch(a_)}ensureInfiniteQueryData(s){return s._type="infinite",this.ensureQueryData(s)}resumePausedMutations(){return hEe.isOnline()?ye(this,LP).resumePausedMutations():Promise.resolve()}getQueryCache(){return ye(this,gg)}getMutationCache(){return ye(this,LP)}getDefaultOptions(){return ye(this,RP)}setDefaultOptions(s){Yt(this,RP,s)}setQueryDefaults(s,t){ye(this,tH).set(D7(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...ye(this,tH).values()],n={};return t.forEach(r=>{uG(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){ye(this,sH).set(D7(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...ye(this,sH).values()],n={};return t.forEach(r=>{uG(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...ye(this,RP).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=het(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===met&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...ye(this,RP).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){ye(this,gg).clear(),ye(this,LP).clear()}},gg=new WeakMap,LP=new WeakMap,RP=new WeakMap,tH=new WeakMap,sH=new WeakMap,DP=new WeakMap,nH=new WeakMap,rH=new WeakMap,vIt);const qDt=j.createContext(!1),bws=()=>j.useContext(qDt);qDt.Provider;function _ws(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}const wws=j.createContext(_ws()),jws=()=>j.useContext(wws),Nws=(s,t,n)=>{const r=n!=null&&n.state.error&&typeof s.throwOnError=="function"?fet(s.throwOnError,[n.state.error,n]):s.throwOnError;(s.suspense||r)&&(t.isReset()||(s.retryOnMount=!1))},kws=s=>{j.useEffect(()=>{s.clearReset()},[s])},Sws=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||fet(n,[s.error,r])),Cws=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))}},Aws=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,Ews=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function VDt(s,t,n){const r=bws(),a=jws(),i=Zt(),l=i.defaultQueryOptions(s),o=i.getQueryCache().get(l.queryHash),c=s.subscribed!==!1;l._optimisticResults=r?"isRestoring":c?"optimistic":void 0,Cws(l),Nws(l,a,o),kws(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(y0.batchCalls(m)):a_;return d.updateResult(),f},[d,h]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),j.useEffect(()=>{d.setOptions(l)},[l,d]),Aws(l,u))throw Ews(l,d,a);if(Sws({result:u,errorResetBoundary:a,throwOnError:l.throwOnError,query:o,suspense:l.suspense}))throw u.error;return l.notifyOnChangeProps?u:d.trackResult(u)}function st(s,t){return VDt(s,$Dt)}function mt(s,t){const n=Zt(),[r]=j.useState(()=>new xws(n,s));j.useEffect(()=>{r.setOptions(s)},[r,s]);const a=j.useSyncExternalStore(j.useCallback(l=>r.subscribe(y0.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=j.useCallback((...l)=>{r.mutate(l[0],l[1]).catch(a_)},[r]);if(a.error&&fet(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function Tws(s,t){return VDt(s,fws)}/** * @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 Ute(){return Ute=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function HDt(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Pws(){return Math.random().toString(36).substr(2,8)}function $gt(s,t){return{usr:s.state,key:s.key,idx:t}}function tHe(s,t,n,r){return n===void 0&&(n=null),Ute({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?WW(t):t,{state:n,key:t&&t.key||r||Pws()})}function mEe(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 WW(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 Iws(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=hI.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(Ute({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=hI.Pop;let v=u(),y=v==null?null:v-d;d=v,c&&c({action:o,location:x.location,delta:y})}function m(v,y){o=hI.Push;let b=tHe(x.location,v,y);d=u()+1;let w=$gt(b,d),S=x.createHref(b);try{l.pushState(w,"",S)}catch(A){if(A instanceof DOMException&&A.name==="DataCloneError")throw A;a.location.assign(S)}i&&c&&c({action:o,location:x.location,delta:1})}function f(v,y){o=hI.Replace;let b=tHe(x.location,v,y);d=u();let w=$gt(b,d),S=x.createHref(b);l.replaceState(w,"",S),i&&c&&c({action:o,location:x.location,delta:0})}function g(v){let y=a.location.origin!=="null"?a.location.origin:a.location.href,b=typeof v=="string"?v:mEe(v);return b=b.replace(/ $/,"%20"),Bg(y,"No window.location.(origin|href) available to create URL for href: "+b),new URL(b,y)}let x={get action(){return o},get location(){return s(a,l)},listen(v){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(Bgt,h),c=v,()=>{a.removeEventListener(Bgt,h),c=null}},createHref(v){return t(a,v)},createURL:g,encodeLocation(v){let y=g(v);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:m,replace:f,go(v){return l.go(v)}};return x}var Ugt;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(Ugt||(Ugt={}));function Lws(s,t,n){return n===void 0&&(n="/"),Rws(s,t,n)}function Rws(s,t,n,r){let a=typeof t=="string"?WW(t):t,i=hG(a.pathname||"/",n);if(i==null)return null;let l=GDt(s);Dws(l);let o=null,c=Wws(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("/")&&(Bg(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=tL([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(Bg(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),GDt(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:qws(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 WDt(i.path))a(i,l,c)}),t}function WDt(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=WDt(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 Dws(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:Vws(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Fws=/^:[\w-]+$/,Ows=3,zws=2,Bws=1,$ws=10,Uws=-2,qgt=s=>s==="*";function qws(s,t){let n=s.split("/"),r=n.length;return n.some(qgt)&&(r+=Uws),t&&(r+=zws),n.filter(a=>!qgt(a)).reduce((a,i)=>a+(Fws.test(i)?Ows:i===""?Bws:$ws),r)}function Vws(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 Hws(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 Gws(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),HDt(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 Wws(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return HDt(!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 hG(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 Kws(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?WW(s):s,i;return n?(n=KDt(n),n.startsWith("/")?i=Vgt(n.substring(1),"/"):i=Vgt(n,t)):i=t,{pathname:i,search:Xws(r),hash:Qws(a)}}function Vgt(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 Cze(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 Yws(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function yet(s,t){let n=Yws(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function vet(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=WW(s):(a=Ute({},s),Bg(!a.pathname||!a.pathname.includes("?"),Cze("?","pathname","search",a)),Bg(!a.pathname||!a.pathname.includes("#"),Cze("#","pathname","hash",a)),Bg(!a.search||!a.search.includes("#"),Cze("#","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=Kws(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const KDt=s=>s.replace(/\/\/+/g,"/"),tL=s=>KDt(s.join("/")),Zws=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),Xws=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,Qws=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function Jws(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const YDt=["post","put","patch","delete"];new Set(YDt);const ejs=["get",...YDt];new Set(ejs);/** * 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 qte(){return qte=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=vet(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:tL([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const njs=j.createContext(null);function rjs(s){let t=j.useContext(r3).outlet;return t&&j.createElement(njs.Provider,{value:s},t)}function Wi(){let{matches:s}=j.useContext(r3),t=s[s.length-1];return t?t.params:{}}function tLe(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=j.useContext(CT),{matches:a}=j.useContext(r3),{pathname:i}=qu(),l=JSON.stringify(yet(a,r.v7_relativeSplatPath));return j.useMemo(()=>vet(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function ajs(s,t){return ijs(s,t)}function ijs(s,t,n,r){KW()||Bg(!1);let{navigator:a}=j.useContext(CT),{matches:i}=j.useContext(r3),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=qu(),u;if(t){var h;let v=typeof t=="string"?WW(t):t;c==="/"||(h=v.pathname)!=null&&h.startsWith(c)||Bg(!1),u=v}else u=d;let m=u.pathname||"/",f=m;if(c!=="/"){let v=c.replace(/^\//,"").split("/");f="/"+m.replace(/^\//,"").split("/").slice(v.length).join("/")}let g=Lws(s,{pathname:f}),x=ujs(g&&g.map(v=>Object.assign({},v,{params:Object.assign({},o,v.params),pathname:tL([c,a.encodeLocation?a.encodeLocation(v.pathname).pathname:v.pathname]),pathnameBase:v.pathnameBase==="/"?c:tL([c,a.encodeLocation?a.encodeLocation(v.pathnameBase).pathname:v.pathnameBase])})),i,n,r);return t&&x?j.createElement(eLe.Provider,{value:{location:qte({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:hI.Pop}},x):x}function ojs(){let s=pjs(),t=Jws(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 ljs=j.createElement(ojs,null);class cjs 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(r3.Provider,{value:this.props.routeContext},j.createElement(XDt.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function djs(s){let{routeContext:t,match:n,children:r}=s,a=j.useContext(JIe);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),j.createElement(r3.Provider,{value:t},r)}function ujs(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||Bg(!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,v=null;n&&(f=o&&h.route.id?o[h.route.id]:void 0,x=h.route.errorElement||ljs,c&&(d<0&&m===0?(xjs("route-fallback"),g=!0,v=null):d===m&&(g=!0,v=h.route.hydrateFallbackElement||null)));let y=t.concat(l.slice(0,m+1)),b=()=>{let w;return f?w=x:g?w=v:h.route.Component?w=j.createElement(h.route.Component,null):h.route.element?w=h.route.element:w=u,j.createElement(djs,{match:h,routeContext:{outlet:u,matches:y,isDataRoute:n!=null},children:w})};return n&&(h.route.ErrorBoundary||h.route.errorElement||m===0)?j.createElement(cjs,{location:n.location,revalidation:n.revalidation,component:x,error:f,children:b(),routeContext:{outlet:null,matches:y,isDataRoute:!0}}):b()},null)}var JDt=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(JDt||{}),eFt=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}(eFt||{});function hjs(s){let t=j.useContext(JIe);return t||Bg(!1),t}function mjs(s){let t=j.useContext(ZDt);return t||Bg(!1),t}function fjs(s){let t=j.useContext(r3);return t||Bg(!1),t}function tFt(s){let t=fjs(),n=t.matches[t.matches.length-1];return n.route.id||Bg(!1),n.route.id}function pjs(){var s;let t=j.useContext(XDt),n=mjs(),r=tFt();return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function gjs(){let{router:s}=hjs(JDt.UseNavigateStable),t=tFt(eFt.UseNavigateStable),n=j.useRef(!1);return QDt(()=>{n.current=!0}),j.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,qte({fromRouteId:t},i)))},[s,t])}const Hgt={};function xjs(s,t,n){Hgt[s]||(Hgt[s]=!0)}function yjs(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function eu(s){let{to:t,replace:n,state:r,relative:a}=s;KW()||Bg(!1);let{future:i,static:l}=j.useContext(CT),{matches:o}=j.useContext(r3),{pathname:c}=qu(),d=Zn(),u=vet(t,yet(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 bet(s){return rjs(s.context)}function rs(s){Bg(!1)}function vjs(s){let{basename:t="/",children:n=null,location:r,navigationType:a=hI.Pop,navigator:i,static:l=!1,future:o}=s;KW()&&Bg(!1);let c=t.replace(/^\/*/,"/"),d=j.useMemo(()=>({basename:c,navigator:i,static:l,future:qte({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=WW(r));let{pathname:u="/",search:h="",hash:m="",state:f=null,key:g="default"}=r,x=j.useMemo(()=>{let v=hG(u,c);return v==null?null:{location:{pathname:v,search:h,hash:m,state:f,key:g},navigationType:a}},[c,u,h,m,f,g,a]);return x==null?null:j.createElement(CT.Provider,{value:d},j.createElement(eLe.Provider,{children:n,value:x}))}function mG(s){let{children:t,location:n}=s;return ajs(nHe(t),n)}new Promise(()=>{});function nHe(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,nHe(r.props.children,i));return}r.type!==rs&&Bg(!1),!r.props.index||!r.props.children||Bg(!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=nHe(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 fEe(){return fEe=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 wjs(s,t){let n=rHe(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const jjs=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],Njs=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],kjs="6";try{window.__reactRouterVersion=kjs}catch{}const Sjs=j.createContext({isTransitioning:!1}),Cjs="startTransition",Ggt=jB[Cjs];function Ajs(s){let{basename:t,children:n,future:r,window:a}=s,i=j.useRef();i.current==null&&(i.current=Mws({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&&Ggt?Ggt(()=>c(h)):c(h)},[c,d]);return j.useLayoutEffect(()=>l.listen(u),[l,u]),j.useEffect(()=>yjs(r),[r]),j.createElement(vjs,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const Ejs=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Tjs=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,br=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=sFt(t,jjs),{basename:f}=j.useContext(CT),g,x=!1;if(typeof d=="string"&&Tjs.test(d)&&(g=d,Ejs))try{let w=new URL(window.location.href),S=d.startsWith("//")?new URL(w.protocol+d):new URL(d),A=hG(S.pathname,f);S.origin===w.origin&&A!=null?d=A+S.search+S.hash:x=!0}catch{}let v=tjs(d,{relative:a}),y=Pjs(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function b(w){r&&r(w),w.defaultPrevented||y(w)}return j.createElement("a",fEe({},m,{href:g||v,onClick:x||i?r:b,ref:n,target:c}))}),aP=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=sFt(t,Njs),m=tLe(c,{relative:h.relative}),f=qu(),g=j.useContext(ZDt),{navigator:x,basename:v}=j.useContext(CT),y=g!=null&&Ijs(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&&v&&(S=hG(S,v)||S);const A=b!=="/"&&b.endsWith("/")?b.length-1:b.length;let E=w===b||!l&&w.startsWith(b)&&w.charAt(A)==="/",I=S!=null&&(S===b||!l&&S.startsWith(b)&&S.charAt(b.length)==="/"),P={isActive:E,isPending:I,isTransitioning:y},R=E?r:void 0,D;typeof i=="function"?D=i(P):D=[i,E?"active":null,I?"pending":null,y?"transitioning":null].filter(Boolean).join(" ");let O=typeof o=="function"?o(P):o;return j.createElement(br,fEe({},h,{"aria-current":R,className:D,ref:n,style:O,to:c,viewTransition:d}),typeof u=="function"?u(P):u)});var aHe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(aHe||(aHe={}));var Wgt;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(Wgt||(Wgt={}));function Mjs(s){let t=j.useContext(JIe);return t||Bg(!1),t}function Pjs(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Zn(),d=qu(),u=tLe(s,{relative:l});return j.useCallback(h=>{if(_js(h,n)){h.preventDefault();let m=r!==void 0?r:mEe(d)===mEe(u);c(s,{replace:m,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function Nc(s){let t=j.useRef(rHe(s)),n=j.useRef(!1),r=qu(),a=j.useMemo(()=>wjs(r.search,n.current?null:t.current),[r.search]),i=Zn(),l=j.useCallback((o,c)=>{const d=rHe(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function Ijs(s,t){t===void 0&&(t={});let n=j.useContext(Sjs);n==null&&Bg(!1);let{basename:r}=Mjs(aHe.useViewTransitionState),a=tLe(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=hG(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=hG(n.nextLocation.pathname,r)||n.nextLocation.pathname;return sHe(a.pathname,l)!=null||sHe(a.pathname,i)!=null}var Ljs=typeof Element<"u",Rjs=typeof Map=="function",Djs=typeof Set=="function",Fjs=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function B4e(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(!B4e(s[r],t[r]))return!1;return!0}var i;if(Rjs&&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(!B4e(r.value[1],t.get(r.value[0])))return!1;return!0}if(Djs&&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(Fjs&&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(Ljs&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!B4e(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var Ojs=function(t,n){try{return B4e(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 zjs=ru(Ojs);var Bjs=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}},$js=Bjs;const Kgt=ru($js);var Ujs=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))(nFt||{}),Aze={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"]}},Ygt=Object.values(nFt),_et={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},Vjs=Object.entries(_et).reduce((s,[t,n])=>(s[n]=t,s),{}),qS="data-rh",gV={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},xV=(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},Hjs=s=>{let t=xV(s,"title");const n=xV(s,gV.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=xV(s,gV.DEFAULT_TITLE);return t||r||void 0},Gjs=s=>xV(s,gV.ON_CHANGE_CLIENT_STATE)||(()=>{}),Eze=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),Wjs=(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),pZ=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&Kjs(`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:Wjs(["href"],s),bodyAttributes:Eze("bodyAttributes",s),defer:xV(s,gV.DEFER),encode:xV(s,gV.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:Eze("htmlAttributes",s),linkTags:pZ("link",["rel","href"],s),metaTags:pZ("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:pZ("noscript",["innerHTML"],s),onChangeClientState:Gjs(s),scriptTags:pZ("script",["src","innerHTML"],s),styleTags:pZ("style",["cssText"],s),title:Hjs(s),titleAttributes:Eze("titleAttributes",s),prioritizeSeoTags:Yjs(s,gV.PRIORITIZE_SEO_TAGS)}),rFt=s=>Array.isArray(s)?s.join(""):s,Xjs=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(Xjs(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},Zgt=(s,t)=>({...s,[t]:void 0}),Qjs=["noscript","script","style"],iHe=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),aFt=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),Jjs=(s,t,n,r)=>{const a=aFt(n),i=rFt(t);return a?`<${s} ${qS}="true" ${a}>${iHe(i,r)}`:`<${s} ${qS}="true">${iHe(i,r)}`},e2s=(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}="${iHe(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=Qjs.indexOf(s)===-1;return`${r}<${s} ${qS}="true" ${l}${c?"/>":`>${o}`}`},""),iFt=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=_et[r];return n[a||r]=s[r],n},t),t2s=(s,t,n)=>{const r={key:t,[qS]:!0},a=iFt(n,r);return[Kt.createElement("title",a,t)]},$4e=(s,t)=>t.map((n,r)=>{const a={key:r,[qS]:!0};return Object.keys(n).forEach(i=>{const o=_et[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),Kt.createElement(s,a)}),fN=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>t2s(s,t.title,t.titleAttributes),toString:()=>Jjs(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>iFt(t),toString:()=>aFt(t)};default:return{toComponent:()=>$4e(s,t),toString:()=>e2s(s,t,n)}}},s2s=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=Tze(s,Aze.meta),i=Tze(t,Aze.link),l=Tze(n,Aze.script);return{priorityMethods:{toComponent:()=>[...$4e("meta",a.priority),...$4e("link",i.priority),...$4e("script",l.priority)],toString:()=>`${fN("meta",a.priority,r)} ${fN("link",i.priority,r)} ${fN("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},n2s=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}=s2s(s)),{priority:f,base:fN("base",t,r),bodyAttributes:fN("bodyAttributes",n,r),htmlAttributes:fN("htmlAttributes",a,r),link:fN("link",u,r),meta:fN("meta",h,r),noscript:fN("noscript",i,r),script:fN("script",m,r),style:fN("style",l,r),title:fN("title",{title:o,titleAttributes:c},r)}},oHe=n2s,xce=[],oFt=!!(typeof window<"u"&&window.document&&window.document.createElement),lHe=class{constructor(s,t){_r(this,"instances",[]);_r(this,"canUseDOM",oFt);_r(this,"context");_r(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?xce:this.instances,add:s=>{(this.canUseDOM?xce:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?xce:this.instances).indexOf(s);(this.canUseDOM?xce:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=oHe({baseTag:[],bodyAttributes:{},htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},r2s={},lFt=Kt.createContext(r2s),P8,cFt=(P8=class extends j.Component{constructor(n){super(n);_r(this,"helmetData");this.helmetData=new lHe(this.props.context||{},P8.canUseDOM)}render(){return Kt.createElement(lFt.Provider,{value:this.helmetData.value},this.props.children)}},_r(P8,"canUseDOM",oFt),P8),c$=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${qS}]`),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(qS,"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}},cHe=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(qS),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(qS):n.getAttribute(qS)!==l.join(",")&&n.setAttribute(qS,l.join(","))},a2s=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=rFt(s)),cHe("title",t)},Xgt=(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;cHe("body",r),cHe("html",a),a2s(h,m);const f={baseTag:c$("base",n),linkTags:c$("link",i),metaTags:c$("meta",l),noscriptTags:c$("noscript",o),scriptTags:c$("script",d),styleTags:c$("style",u)},g={},x={};Object.keys(f).forEach(v=>{const{newTags:y,oldTags:b}=f[v];y.length&&(g[v]=y),b.length&&(x[v]=f[v].oldTags)}),t&&t(),c(s,g,x)},gZ=null,i2s=s=>{gZ&&cancelAnimationFrame(gZ),s.defer?gZ=requestAnimationFrame(()=>{Xgt(s,()=>{gZ=null})}):(Xgt(s),gZ=null)},o2s=i2s,Qgt=class extends j.Component{constructor(){super(...arguments);_r(this,"rendered",!1)}shouldComponentUpdate(t){return!qjs(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=Zjs(t.get().map(i=>{const l={...i.props};return delete l.context,l}));cFt.canUseDOM?o2s(a):oHe&&(r=oHe(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}},Aqe,Dl=(Aqe=class extends j.Component{shouldComponentUpdate(s){return!zjs(Zgt(this.props,"helmetData"),Zgt(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 Kgt(Ygt.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 ${Ygt.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),Kgt(!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 Kt.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[Vjs[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 lHe)){const a=r;r=new lHe(a.context,!0),delete n.helmetData}return r?Kt.createElement(Qgt,{...n,context:r.value}):Kt.createElement(lFt.Consumer,null,a=>Kt.createElement(Qgt,{...n,context:a}))}},_r(Aqe,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),Aqe);const l2s=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>ri(async()=>{const{default:r}=await Promise.resolve().then(()=>YW);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class wet extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class c2s extends wet{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class d2s extends wet{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class jae extends wet{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var dHe;(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"})(dHe||(dHe={}));var u2s=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 h2s{constructor(t,{headers:n={},customFetch:r,region:a=dHe.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=l2s(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return u2s(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 c2s(g)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new d2s(u);if(!u.ok)throw new jae(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 fw={},jet={},sLe={},Nae={},nLe={},rLe={},m2s=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")},fG=m2s();const f2s=fG.fetch,dFt=fG.fetch.bind(fG),uFt=fG.Headers,p2s=fG.Request,g2s=fG.Response,YW=Object.freeze(Object.defineProperty({__proto__:null,Headers:uFt,Request:p2s,Response:g2s,default:dFt,fetch:f2s},Symbol.toStringTag,{value:"Module"})),x2s=qps(YW);var aLe={};Object.defineProperty(aLe,"__esModule",{value:!0});let y2s=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};aLe.default=y2s;var hFt=kp&&kp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(rLe,"__esModule",{value:!0});const v2s=hFt(x2s),b2s=hFt(aLe);let _2s=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=v2s.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 y=await i.text();y===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=y:u=JSON.parse(y))}const x=(l=this.headers.Prefer)===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),v=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");x&&v&&v.length>1&&(h=parseInt(v[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 b2s.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}};rLe.default=_2s;var w2s=kp&&kp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(nLe,"__esModule",{value:!0});const j2s=w2s(rLe);let N2s=class extends j2s.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}};nLe.default=N2s;var k2s=kp&&kp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Nae,"__esModule",{value:!0});const S2s=k2s(nLe);let C2s=class extends S2s.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}};Nae.default=C2s;var A2s=kp&&kp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(sLe,"__esModule",{value:!0});const xZ=A2s(Nae);let E2s=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 xZ.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 xZ.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 xZ.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 xZ.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 xZ.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};sLe.default=E2s;var iLe={},oLe={};Object.defineProperty(oLe,"__esModule",{value:!0});oLe.version=void 0;oLe.version="0.0.0-automated";Object.defineProperty(iLe,"__esModule",{value:!0});iLe.DEFAULT_HEADERS=void 0;const T2s=oLe;iLe.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${T2s.version}`};var mFt=kp&&kp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(jet,"__esModule",{value:!0});const M2s=mFt(sLe),P2s=mFt(Nae),I2s=iLe;let L2s=class fFt{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},I2s.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new M2s.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new fFt(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 P2s.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};jet.default=L2s;var ZW=kp&&kp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(fw,"__esModule",{value:!0});fw.PostgrestError=fw.PostgrestBuilder=fw.PostgrestTransformBuilder=fw.PostgrestFilterBuilder=fw.PostgrestQueryBuilder=fw.PostgrestClient=void 0;const pFt=ZW(jet);fw.PostgrestClient=pFt.default;const gFt=ZW(sLe);fw.PostgrestQueryBuilder=gFt.default;const xFt=ZW(Nae);fw.PostgrestFilterBuilder=xFt.default;const yFt=ZW(nLe);fw.PostgrestTransformBuilder=yFt.default;const vFt=ZW(rLe);fw.PostgrestBuilder=vFt.default;const bFt=ZW(aLe);fw.PostgrestError=bFt.default;var R2s=fw.default={PostgrestClient:pFt.default,PostgrestQueryBuilder:gFt.default,PostgrestFilterBuilder:xFt.default,PostgrestTransformBuilder:yFt.default,PostgrestBuilder:vFt.default,PostgrestError:bFt.default};const{PostgrestClient:D2s,PostgrestQueryBuilder:skr,PostgrestFilterBuilder:nkr,PostgrestTransformBuilder:rkr,PostgrestBuilder:akr,PostgrestError:ikr}=R2s;let uHe;typeof window>"u"?uHe=require("ws"):uHe=window.WebSocket;const F2s="2.11.10",O2s={"X-Client-Info":`realtime-js/${F2s}`},z2s="1.0.0",_Ft=1e4,B2s=1e3;var yV;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(yV||(yV={}));var e_;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(e_||(e_={}));var MS;(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"})(MS||(MS={}));var hHe;(function(s){s.websocket="websocket"})(hHe||(hHe={}));var qO;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(qO||(qO={}));class $2s{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 wFt{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 Bf;(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"})(Bf||(Bf={}));const Jgt=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=U2s(l,s,t,a),i),{})},U2s=(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)?jFt(i,l):mHe(l)},jFt=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return G2s(t,n)}switch(s){case Bf.bool:return q2s(t);case Bf.float4:case Bf.float8:case Bf.int2:case Bf.int4:case Bf.int8:case Bf.numeric:case Bf.oid:return V2s(t);case Bf.json:case Bf.jsonb:return H2s(t);case Bf.timestamp:return W2s(t);case Bf.abstime:case Bf.date:case Bf.daterange:case Bf.int4range:case Bf.int8range:case Bf.money:case Bf.reltime:case Bf.text:case Bf.time:case Bf.timestamptz:case Bf.timetz:case Bf.tsrange:case Bf.tstzrange:return mHe(t);default:return mHe(t)}},mHe=s=>s,q2s=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},V2s=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},H2s=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},G2s=(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=>jFt(t,o))}return s},W2s=s=>typeof s=="string"?s.replace(" ","T"):s,NFt=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class Mze{constructor(t,n,r={},a=_Ft){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 ext;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(ext||(ext={}));class iee{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=iee.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=iee.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=iee.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(v=>v.presence_ref),f=h.map(v=>v.presence_ref),g=u.filter(v=>f.indexOf(v.presence_ref)<0),x=h.filter(v=>m.indexOf(v.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 txt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(txt||(txt={}));var sxt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(sxt||(sxt={}));var kA;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(kA||(kA={}));class Net{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=e_.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 Mze(this,MS.join,this.params,this.timeout),this.rejoinTimer=new wFt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=e_.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=e_.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=e_.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=e_.errored,this.rejoinTimer.scheduleTimeout())}),this._on(MS.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new iee(this),this.broadcastEndpointURL=NFt(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(kA.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(kA.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(kA.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=e_.errored,t==null||t(kA.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(kA.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=e_.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(MS.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new Mze(this,MS.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 Mze(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}=MS;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,v;return((g=f.filter)===null||g===void 0?void 0:g.event)==="*"||((v=(x=f.filter)===null||x===void 0?void 0:x.event)===null||v===void 0?void 0:v.toLocaleLowerCase())===l}).map(f=>f.callback(m,r)):(i=this.bindings[l])===null||i===void 0||i.filter(f=>{var g,x,v,y,b,w;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in f){const S=f.id,A=(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))&&(A==="*"||(A==null?void 0:A.toLocaleLowerCase())===((v=n.data)===null||v===void 0?void 0:v.type.toLocaleLowerCase()))}else{const S=(b=(y=f==null?void 0:f.filter)===null||y===void 0?void 0:y.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:v,commit_timestamp:y,type:b,errors:w}=g;m=Object.assign(Object.assign({},{schema:x,table:v,commit_timestamp:y,eventType:b,new:{},old:{},errors:w}),this._getPayloadRecords(g))}f.callback(m,r)})}_isClosed(){return this.state===e_.closed}_isJoined(){return this.state===e_.joined}_isJoining(){return this.state===e_.joining}_isLeaving(){return this.state===e_.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&&Net.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(MS.close,{},t)}_onError(t){this._on(MS.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=e_.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=Jgt(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=Jgt(t.columns,t.old_record)),n}}const nxt=()=>{},K2s=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class Y2s{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=O2s,this.params={},this.timeout=_Ft,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=nxt,this.ref=0,this.logger=nxt,this.conn=null,this.sendBuffer=[],this.serializer=new $2s,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(()=>YW);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${hHe.websocket}`,this.httpEndpoint=NFt(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 wFt(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=uHe),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 Z2s(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:z2s}))}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 yV.connecting:return qO.Connecting;case yV.open:return qO.Open;case yV.closing:return qO.Closing;default:return qO.Closed}}isConnected(){return this.connectionState()===qO.Open}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new Net(`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(MS.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(B2s,"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(MS.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([K2s],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class Z2s{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=yV.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class ket extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function iv(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class X2s extends ket{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class fHe extends ket{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var Q2s=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 kFt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>ri(async()=>{const{default:r}=await Promise.resolve().then(()=>YW);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},J2s=()=>Q2s(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield ri(()=>Promise.resolve().then(()=>YW),void 0)).Response:Response}),pHe=s=>{if(Array.isArray(s))return s.map(n=>pHe(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]=pHe(r)}),t};var EB=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 Pze=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),eNs=(s,t,n)=>EB(void 0,void 0,void 0,function*(){const r=yield J2s();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new X2s(Pze(a),s.status||500))}).catch(a=>{t(new fHe(Pze(a),a))}):t(new fHe(Pze(s),s))}),tNs=(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 kae(s,t,n,r,a,i){return EB(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,tNs(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=>eNs(c,o,r))})})}function pEe(s,t,n,r){return EB(this,void 0,void 0,function*(){return kae(s,"GET",t,n,r)})}function iP(s,t,n,r,a){return EB(this,void 0,void 0,function*(){return kae(s,"POST",t,r,a,n)})}function sNs(s,t,n,r,a){return EB(this,void 0,void 0,function*(){return kae(s,"PUT",t,r,a,n)})}function nNs(s,t,n,r){return EB(this,void 0,void 0,function*(){return kae(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function SFt(s,t,n,r,a){return EB(this,void 0,void 0,function*(){return kae(s,"DELETE",t,r,a,n)})}var Z_=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 rNs={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},rxt={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=kFt(a)}uploadOrUpdate(t,n,r,a){return Z_(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},rxt),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(iv(i))return{data:null,error:i};throw i}})}upload(t,n,r){return Z_(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return Z_(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:rxt.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(iv(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return Z_(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 iP(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 ket("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(iv(r))return{data:null,error:r};throw r}})}update(t,n,r){return Z_(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return Z_(this,void 0,void 0,function*(){try{return{data:yield iP(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(iv(a))return{data:null,error:a};throw a}})}copy(t,n,r){return Z_(this,void 0,void 0,function*(){try{return{data:{path:(yield iP(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(iv(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return Z_(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield iP(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(iv(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return Z_(this,void 0,void 0,function*(){try{const a=yield iP(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(iv(a))return{data:null,error:a};throw a}})}download(t,n){return Z_(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 pEe(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(iv(o))return{data:null,error:o};throw o}})}info(t){return Z_(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield pEe(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:pHe(r),error:null}}catch(r){if(iv(r))return{data:null,error:r};throw r}})}exists(t){return Z_(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield nNs(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(iv(r)&&r instanceof fHe){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 Z_(this,void 0,void 0,function*(){try{return{data:yield SFt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(iv(n))return{data:null,error:n};throw n}})}list(t,n,r){return Z_(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},rNs),n),{prefix:t||""});return{data:yield iP(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(iv(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 iNs="2.7.1",oNs={"X-Client-Info":`storage-js/${iNs}`};var d$=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 lNs{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},oNs),n),this.fetch=kFt(r)}listBuckets(){return d$(this,void 0,void 0,function*(){try{return{data:yield pEe(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(iv(t))return{data:null,error:t};throw t}})}getBucket(t){return d$(this,void 0,void 0,function*(){try{return{data:yield pEe(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(iv(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return d$(this,void 0,void 0,function*(){try{return{data:yield iP(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(iv(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return d$(this,void 0,void 0,function*(){try{return{data:yield sNs(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(iv(r))return{data:null,error:r};throw r}})}emptyBucket(t){return d$(this,void 0,void 0,function*(){try{return{data:yield iP(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(iv(n))return{data:null,error:n};throw n}})}deleteBucket(t){return d$(this,void 0,void 0,function*(){try{return{data:yield SFt(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(iv(n))return{data:null,error:n};throw n}})}}class cNs extends lNs{constructor(t,n={},r){super(t,n,r)}from(t){return new aNs(this.url,this.headers,t,this.fetch)}}const dNs="2.49.10";let tQ="";typeof Deno<"u"?tQ="deno":typeof document<"u"?tQ="web":typeof navigator<"u"&&navigator.product==="ReactNative"?tQ="react-native":tQ="node";const uNs={"X-Client-Info":`supabase-js-${tQ}/${dNs}`},hNs={headers:uNs},mNs={schema:"public"},fNs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},pNs={};var gNs=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 xNs=s=>{let t;return s?t=s:typeof fetch>"u"?t=dFt:t=fetch,(...n)=>t(...n)},yNs=()=>typeof Headers>"u"?uFt:Headers,vNs=(s,t,n)=>{const r=xNs(n),a=yNs();return(i,l)=>gNs(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 bNs=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 _Ns(s){return s.endsWith("/")?s:s+"/"}function wNs(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:()=>bNs(this,void 0,void 0,function*(){return""})};return s.accessToken?m.accessToken=s.accessToken:delete m.accessToken,m}const CFt="2.69.1",cU=30*1e3,gHe=3,Ize=gHe*cU,jNs="http://localhost:9999",NNs="supabase.auth.token",kNs={"X-Client-Info":`gotrue-js/${CFt}`},xHe="X-Supabase-Api-Version",AFt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},SNs=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,CNs=6e5;class Cet extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function Ld(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class ANs extends Cet{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function ENs(s){return Ld(s)&&s.name==="AuthApiError"}class EFt extends Cet{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class QL extends Cet{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class zM extends QL{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function TNs(s){return Ld(s)&&s.name==="AuthSessionMissingError"}class Lze extends QL{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class yce extends QL{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class vce extends QL{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 MNs(s){return Ld(s)&&s.name==="AuthImplicitGrantRedirectError"}class axt extends QL{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 yHe extends QL{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function Rze(s){return Ld(s)&&s.name==="AuthRetryableFetchError"}class ixt extends QL{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class oee extends QL{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const oxt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),lxt=` \r=`.split(""),PNs=(()=>{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 cxt(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{RNs(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 LNs(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}INs(r,t)}}function RNs(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 DNs(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function ONs(s){return Math.round(Date.now()/1e3)+s}function zNs(){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 p5=()=>typeof window<"u"&&typeof document<"u",oR={tested:!1,writable:!1},lee=()=>{if(!p5())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(oR.tested)return oR.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),oR.tested=!0,oR.writable=!0}catch{oR.tested=!0,oR.writable=!1}return oR.writable};function BNs(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 MFt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>ri(async()=>{const{default:r}=await Promise.resolve().then(()=>YW);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},$Ns=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",PFt=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},bce=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},_ce=async(s,t)=>{await s.removeItem(t)};class lLe{constructor(){this.promise=new lLe.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}lLe.promiseConstructor=Promise;function Dze(s){const t=s.split(".");if(t.length!==3)throw new oee("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function qNs(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 VNs(s){return("0"+s.toString(16)).substr(-2)}function HNs(){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,VNs).join("")}async function GNs(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 WNs(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 GNs(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function u$(s,t,n=!1){const r=HNs();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await PFt(s,`${t}-code-verifier`,a);const i=await WNs(r);return[i,r===i?"plain":"s256"]}const KNs=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function YNs(s){const t=s.headers.get(xHe);if(!t||!t.match(KNs))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function ZNs(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 XNs(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 QNs=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),JNs=[502,503,504];async function dxt(s){var t;if(!$Ns(s))throw new yHe(AO(s),0);if(JNs.includes(s.status))throw new yHe(AO(s),s.status);let n;try{n=await s.json()}catch(i){throw new EFt(AO(i),i)}let r;const a=YNs(s);if(a&&a.getTime()>=AFt["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 ixt(AO(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new zM}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 ixt(AO(n),s.status,n.weak_password.reasons);throw new ANs(AO(n),s.status||500,r)}const eks=(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 Lu(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[xHe]||(i[xHe]=AFt["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 tks(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 tks(s,t,n,r,a,i){const l=eks(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new yHe(AO(c),0)}if(o.ok||await dxt(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await dxt(c)}}function BM(s){var t;let n=null;aks(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=ONs(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function uxt(s){const t=BM(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 wP(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function sks(s){return{data:s,error:null}}function nks(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=QNs(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 rks(s){return s}function aks(s){return s.access_token&&s.refresh_token&&s.expires_in}var iks=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)),v=JSON.parse(g.split(";")[1].split("=")[1]);d[`${v}Page`]=x}),d.total=parseInt(m)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if(Ld(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await Lu(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:wP})}catch(n){if(Ld(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await Lu(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:wP})}catch(r){if(Ld(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await Lu(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:wP})}catch(r){if(Ld(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await Lu(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(Ld(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await Lu(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(Ld(n))return{data:null,error:n};throw n}}}const lks={getItem:s=>lee()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{lee()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{lee()&&globalThis.localStorage.removeItem(s)}};function hxt(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function cks(){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 h$={debug:!!(globalThis&&lee()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class IFt extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class dks extends IFt{}async function uks(s,t,n){h$.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),h$.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){h$.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await n()}finally{h$.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw h$.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new dks(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(h$.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()}}))}cks();const hks={url:jNs,storageKey:NNs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:kNs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function mxt(s,t,n){return await n()}class Vte{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=Vte.nextInstanceID,Vte.nextInstanceID+=1,this.instanceID>0&&p5()&&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({},hks),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 oks({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=MFt(a.fetch),this.lock=a.lock||mxt,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:p5()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=uks:this.lock=mxt,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:lee()?this.storage=lks:(this.memoryStorage={},this.storage=hxt(this.memoryStorage)):(this.memoryStorage={},this.storage=hxt(this.memoryStorage)),p5()&&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} (${CFt}) ${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=BNs(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),p5()&&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),MNs(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 Ld(n)?{error:n}:{error:new EFt("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await Lu(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:BM}),{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(Ld(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 u$(this.storage,this.storageKey)),i=await Lu(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:BM})}else if("phone"in t){const{phone:u,password:h,options:m}=t;i=await Lu(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:BM})}else throw new yce("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(Ld(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 Lu(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:uxt})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await Lu(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:uxt})}else throw new yce("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 Lze}:(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(Ld(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 bce(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await Lu(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:BM});if(await _ce(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Lze}:(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(Ld(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 Lu(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:BM}),{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 Lze}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(n){if(Ld(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 u$(this.storage,this.storageKey));const{error:h}=await Lu(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 Lu(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 yce("You must provide either an email or phone number.")}catch(o){if(Ld(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 Lu(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:BM});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(Ld(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 u$(this.storage,this.storageKey)),await Lu(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:sks})}catch(i){if(Ld(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 zM;const{error:a}=await Lu(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(Ld(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 Lu(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 Lu(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 yce("You must provide either an email or phone number and a type")}catch(n){if(Ld(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 bce(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()(!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 Lu(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:wP}):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 zM}:await Lu(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:wP})})}catch(n){if(Ld(n))return TNs(n)&&(await this._removeSession(),await _ce(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 zM;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await u$(this.storage,this.storageKey));const{data:d,error:u}=await Lu(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:wP});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(Ld(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 zM;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=Dze(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(Ld(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 zM;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(Ld(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t,n){try{if(!p5())throw new vce("No browser detected.");if(t.error||t.error_description||t.error_code)throw new vce(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 axt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new vce("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 axt("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 vce("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<=cU&&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:v}=await this._getUser(i);if(v)throw v;const y={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:y,redirectType:t.type},error:null}}catch(r){if(Ld(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 bce(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&&!(ENs(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await _ce(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=zNs(),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 u$(this.storage,this.storageKey,!0));try{return await Lu(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(Ld(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(Ld(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 Lu(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 p5()&&!(!((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(Ld(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 Lu(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(Ld(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 qNs(async a=>(a>0&&await UNs(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await Lu(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:BM})),(a,i)=>{const l=200*Math.pow(2,a);return i&&Rze(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(),cU);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)/cU);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${cU}ms, refresh threshold is ${gHe} ticks`),a<=gHe&&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 IFt)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!p5()||!(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 u$(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 Lu(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(Ld(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 Lu(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(Ld(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 Lu(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(Ld(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 Lu(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(Ld(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}=Dze(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+CNs>Date.now()))return r;const{data:a,error:i}=await Lu(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 oee("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new oee("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}}=Dze(r);if(ZNs(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=XNs(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,FNs(`${o}.${c}`)))throw new oee("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(r){if(Ld(r))return{data:null,error:r};throw r}}}Vte.nextInstanceID=0;const mks=Vte;class fks extends mks{constructor(t){super(t)}}var pks=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 gks{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=_Ns(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:mNs,realtime:pNs,auth:Object.assign(Object.assign({},fNs),{storageKey:d}),global:hNs},h=wNs(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=vNs(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 D2s(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new h2s(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new cNs(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 pks(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 Y2s(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 xks=(s,t,n)=>new gks(s,t,n);function yks(){var v,y;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?((v=s.match(new RegExp("^(?:id-preview(?:-[a-z0-9]+)?|project)--("+r+")(?:-dev)?(?=\\.|$)","i")))==null?void 0:v[1])??((y=s.match(new RegExp("^("+r+")(?=[.-])","i")))==null?void 0:y[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(A=>{const E=m();let I=!1,P;const R=U=>{I||(I=!0,clearTimeout(P),window.removeEventListener("message",D),A(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(()=>{})),removeItem:b=>(localStorage.removeItem(b),f("lovable-preview-auth:remove",b).then(()=>{}))}}const vks="https://relzejiswnotikjgvjhz.supabase.co",bks="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",q=xks(vks,bks,{auth:{storage:yks(),persistSession:!0,autoRefreshToken:!0}}),_ks=Object.freeze(Object.defineProperty({__proto__:null,supabase:q},Symbol.toStringTag,{value:"Module"})),LFt=j.createContext(void 0),wks=({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,v]=j.useState(null),[y,b]=j.useState([]),[w,S]=j.useState(null),A=j.useRef(null),E=j.useRef(!1),I=j.useRef(!1),P=Zn(),R=()=>{u(!1),m(!1),g(!1),v(null),b([]),S(null),A.current=null,E.current=!1},D=async V=>{if(E.current&&A.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:Z,error:X},{data:ae,error:le},{data:re,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||le)console.error("Role RPC errors:",{isAdminError:X,isBrokerError:le,isCoachError:te}),u(!1),m(!1),g(!1);else{const ve=!!Z,fe=!!ae,ue=!!re;console.log("RPC roles result:",{adminValue:ve,brokerValue:fe,coachValue:ue}),u(ve),m(fe),g(ue)}A.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 ve=J.paused_reason;try{sessionStorage.setItem("accountPausedReason",ve||"")}catch{}await q.auth.signOut(),R(),P("/auth?paused=1",{replace:!0});return}if(v(!ce&&J?J.brokerage_id:null),ae){console.log("Fetching managed brokerages for user:",V);const{data:ve,error:fe}=await q.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",V);if(console.log("Managed brokerage assignments result:",{assignments:ve,assignmentsError:fe}),fe||!ve){console.error("Error fetching managed brokerage assignments:",fe),b([]);return}const ue=Array.from(new Set(ve.map(Ie=>Ie.brokerage_id).filter(Boolean)));if(ue.length===0){b([]);return}const{data:be,error:Ee}=await q.from("brokerages").select("id, name").in("id",ue);if(console.log("Managed brokerages details result:",{brokeragesData:be,brokeragesError:Ee}),Ee||!be){console.error("Error fetching managed brokerages details:",Ee),b([]);return}const ke=be.map(Ie=>({id:Ie.id,name:Ie.name})).sort((Ie,Fe)=>ue.indexOf(Ie.id)-ue.indexOf(Fe.id));console.log("Parsed managed brokerages:",ke),b(ke),ke.length>0&&S(Ie=>Ie??ke[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),b([]);A.current=V,E.current=!0}catch(Z){console.error("Unexpected error in checkRoles:",Z),R()}finally{window.clearTimeout(G),I.current=!1,c(!1)}};j.useEffect(()=>{let V=!0,G=!1;const Z=()=>{!V||G||(G=!0,l(!1))},{data:{subscription:X}}=q.auth.onAuthStateChange((le,re)=>{console.log("Auth event:",le),V&&(a(re),n((re==null?void 0:re.user)??null),Z(),le==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{P("/profile?reset=true")},100)),re!=null&&re.user?(!E.current||A.current!==re.user.id)&&setTimeout(()=>{D(re.user.id)},0):(R(),c(!1)))}),ae=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),Z()},8e3);return()=>{V=!1,window.clearTimeout(ae),X.unsubscribe()}},[]);const O=async(V,G)=>{var le;const Z=(V||"").trim().toLowerCase(),{data:X,error:ae}=await q.auth.signInWithPassword({email:Z,password:G});if(ae)throw ne.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((le=X.user)!=null&&le.id){const{data:re}=await q.from("profiles").select("is_paused, paused_reason").eq("id",X.user.id).maybeSingle();if(re!=null&&re.is_paused){const te=re.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",ne.error(J.message),J}}ne.success("Welcome back!")},U=async(V,G,Z)=>{var te;const X="https://dashboard.relevelup.com/dashboard",ae=localStorage.getItem("levelup_referral_code")||null,{data:le,error:re}=await q.auth.signUp({email:V,password:G,options:{emailRedirectTo:X,data:{name:Z,referred_by_code:ae}}});if(re)throw ne.error(re.message),re;if(ae&&((te=le.user)!=null&&te.id))try{await q.from("profiles").update({referred_by_code:ae}).eq("id",le.user.id),localStorage.removeItem("levelup_referral_code")}catch(J){console.warn("Failed to attach referral code to profile",J)}ne.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),ne.error(G.message)):ne.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");n(null),a(null),u(!1),m(!1),v(null),b([]),S(null),P("/auth")}catch(V){console.error("Unexpected sign out error:",V),P("/auth")}};return e.jsx(LFt.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:y,selectedBrokerageId:w,setSelectedBrokerageId:S},children:s})},_s=()=>{const s=j.useContext(LFt);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},RFt=j.createContext({onlineUsers:[],totalOnline:0}),jks=3*60*1e3,Nks=45*1e3,kks=30*1e3,Sks=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=_s(),[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()-jks).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 y;const v=g.get(x.user_id);return{id:x.user_id,name:(v==null?void 0:v.name)||((y=v==null?void 0:v.email)==null?void 0:y.split("@")[0])||"Member",avatarUrl:(v==null?void 0:v.avatar_url)||void 0,brokerageId:(v==null?void 0:v.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()},Nks),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(RFt.Provider,{value:{onlineUsers:d,totalOnline:d.length},children:s})},DFt=()=>j.useContext(RFt),FFt=j.createContext(void 0),lR="levelup_admin_session",gM="levelup_impersonation",Fze="levelup_impersonation_return",Cks=({children:s})=>{const[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1);j.useEffect(()=>{const d=sessionStorage.getItem(gM);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(gM)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:h}}=await q.auth.getSession();if(!h)return ne.error("No active session found"),!1;const m={access_token:h.access_token,refresh_token:h.refresh_token};sessionStorage.setItem(lR,JSON.stringify(m)),u&&sessionStorage.setItem(Fze,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(gM,JSON.stringify(x)),g.method==="session"){const{error:v}=await q.auth.setSession({access_token:g.access_token,refresh_token:g.refresh_token});if(v)throw console.error("Set session error:",v),sessionStorage.removeItem(lR),sessionStorage.removeItem(gM),new Error("Failed to establish impersonation session")}else{const v=g.type||"recovery",{error:y}=await q.auth.verifyOtp({token_hash:g.token_hash,type:v});if(y)throw console.error("Verify OTP error:",y),sessionStorage.removeItem(lR),sessionStorage.removeItem(gM),new Error("Failed to establish impersonation session")}return n(!0),a(x),ne.success(`Now viewing as ${x.name}`),window.location.href="/dashboard",!0}catch(h){return console.error("Impersonation error:",h),ne.error(h.message||"Failed to impersonate user"),sessionStorage.removeItem(lR),sessionStorage.removeItem(gM),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(lR);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(lR),sessionStorage.removeItem(gM),h){console.error("Failed to restore admin session:",h),ne.error("Admin session expired, please sign in again"),window.location.href="/auth";return}n(!1),a(null),ne.success("Returned to your account");const m=sessionStorage.getItem(Fze)||"/admin/members";sessionStorage.removeItem(Fze),window.location.href=m}catch(d){console.error("Stop impersonation error:",d),ne.error("Failed to restore admin session"),sessionStorage.removeItem(lR),sessionStorage.removeItem(gM),window.location.href="/auth"}finally{l(!1)}};return e.jsx(FFt.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},cLe=()=>{const s=j.useContext(FFt);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},Aks=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=cLe();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(Al,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(mr,{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"})]})})]})})},OFt=j.createContext(void 0),m$="levelup_acting_as",wce="levelup_acting_as_self",Eks=({children:s})=>{const{user:t}=_s(),[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(wce)==="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:A}=await q.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(A||!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(wce)==="true")f(!0),o(null),d({});else{const R=sessionStorage.getItem(m$);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(m$,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(m$,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(wce),b?(sessionStorage.setItem(m$,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(m$),d({}))},x=()=>{f(!0),o(null),d({}),sessionStorage.setItem(wce,"true"),sessionStorage.removeItem(m$)},v=b=>!n||m?!0:c[b]===!0,y=n&&l&&!m?l.id:(t==null?void 0:t.id)||null;return e.jsx(OFt.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:g,effectiveUserId:y,permissions:c,hasPermission:v,isLoading:u,isActingAsSelf:m,setActingAsSelf:x},children:s})},Sae=()=>{const s=j.useContext(OFt);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},Sa=()=>{const{effectiveUserId:s}=Sae();return s};var Tks=Object.defineProperty,lT=(s,t)=>Tks(s,"name",{value:t,configurable:!0}),zFt="Avatar",[Mks,okr]=ep(zFt),Pks=[0,()=>{}],[Iks,BFt]=Mks(zFt),$Ft=j.forwardRef(lT(function(t,n){const{__scopeAvatar:r,...a}=t,[i,l]=j.useState("idle"),[o,c]=HFt();return e.jsx(Iks,{scope:r,imageLoadingStatus:i,setImageLoadingStatus:l,imageCount:o,setImageCount:c,children:e.jsx(Ei.span,{...a,ref:n})})},"Avatar")),Lks="AvatarImage",UFt=j.forwardRef(lT(function(t,n){const{__scopeAvatar:r,src:a,onLoadingStatusChange:i,...l}=t,o=BFt(Lks,r);o.setImageCount;const c=VFt(a,{referrerPolicy:l.referrerPolicy,crossOrigin:l.crossOrigin,loadingStatus:o.imageLoadingStatus,setLoadingStatus:o.setImageLoadingStatus}),d=Kp(h=>{i==null||i(h)}),u=j.useRef(c);return Af(()=>{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")),Rks="AvatarFallback",qFt=j.forwardRef(lT(function(t,n){const{__scopeAvatar:r,delayMs:a,...i}=t,l=BFt(Rks,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 VFt(s,{loadingStatus:t,setLoadingStatus:n,referrerPolicy:r,crossOrigin:a}){return Af(()=>{if(!s){n("error");return}const i=new window.Image,l=lT(c=>{const d=c.currentTarget;n(vHe(d))},"handleLoad"),o=lT(()=>n("error"),"handleError");return i.addEventListener("load",l),i.addEventListener("error",o),r&&(i.referrerPolicy=r),i.crossOrigin=a??null,i.src=s,n(vHe(i)),()=>{i.removeEventListener("load",l),i.removeEventListener("error",o),n("idle")}},[s,a,r,n]),t}lT(VFt,"useImageLoadingStatus");function vHe(s){return s.complete?s.naturalWidth>0?"loaded":"error":"loading"}lT(vHe,"getImageLoadingStatus");function HFt(){return Pks}lT(HFt,"useImageCount");function Dks(s){}lT(Dks,"useUpdateImageCount");const Oa=j.forwardRef(({className:s,...t},n)=>e.jsx($Ft,{ref:n,className:Pt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));Oa.displayName=$Ft.displayName;const Ii=j.forwardRef(({className:s,...t},n)=>e.jsx(UFt,{ref:n,className:Pt("aspect-square h-full w-full",s),...t}));Ii.displayName=UFt.displayName;const za=j.forwardRef(({className:s,...t},n)=>e.jsx(qFt,{ref:n,className:Pt("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));za.displayName=qFt.displayName;const Fks=AB("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 $e({className:s,variant:t,...n}){return e.jsx("div",{className:Pt(Fks({variant:t}),s),...n})}var Oks=Object.defineProperty,zks=(s,t)=>Oks(s,"name",{value:t,configurable:!0}),Bks=j.createContext(void 0);function a3(s){const t=j.useContext(Bks);return s||t||"ltr"}zks(a3,"useDirection");var $ks=Object.defineProperty,Aet=(s,t)=>$ks(s,"name",{value:t,configurable:!0}),Oze=!1;function GFt(){const[s,t]=j.useState(Oze);return j.useEffect(()=>{Oze||(Oze=!0,t(!0))},[]),s}Aet(GFt,"useIsHydrated");var WFt=jB[" useSyncExternalStore ".trim().toString()];function KFt(){return()=>{}}Aet(KFt,"subscribe");function YFt(){return WFt(KFt,()=>!0,()=>!1)}Aet(YFt,"useIsHydratedModern");var Uks=typeof WFt=="function"?YFt:GFt,qks=Object.defineProperty,TB=(s,t)=>qks(s,"name",{value:t,configurable:!0}),zze="rovingFocusGroup.onEntryFocus",Vks={bubbles:!1,cancelable:!0},dLe="RovingFocusGroup",[bHe,ZFt,Hks]=SB(dLe),[Gks,JL]=ep(dLe,[Hks]),[Wks,Kks]=Gks(dLe),Yks=j.forwardRef(TB(function(t,n){return e.jsx(bHe.Provider,{scope:t.__scopeRovingFocusGroup,children:e.jsx(bHe.Slot,{scope:t.__scopeRovingFocusGroup,children:e.jsx(Zks,{...t,ref:n})})})},"RovingFocusGroup")),Zks=j.forwardRef(TB(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=a3(l),[v,y]=dy({prop:o,defaultProp:c??null,onChange:d,caller:dLe}),[b,w]=j.useState(!1),S=Kp(u),A=ZFt(r),E=j.useRef(!1),[I,P]=j.useState(0);return j.useEffect(()=>{const R=f.current;if(R)return R.addEventListener(zze,S),()=>R.removeEventListener(zze,S)},[S]),e.jsx(Wks,{scope:r,orientation:a,dir:x,loop:i,currentTabStopId:v,onItemFocus:j.useCallback(R=>y(R),[y]),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(zze,Vks);if(R.currentTarget.dispatchEvent(O),!O.defaultPrevented){const U=A().filter(X=>X.focusable),W=U.find(X=>X.active),V=U.find(X=>X.id===v),Z=[W,V,...U].filter(Boolean).map(X=>X.ref.current);Eet(Z,h)}}E.current=!1}),onBlur:Ra(t.onBlur,()=>w(!1))})})},"RovingFocusGroupImpl")),Xks="RovingFocusGroupItem",Qks=j.forwardRef(TB(function(t,n){const{__scopeRovingFocusGroup:r,focusable:a=!0,active:i=!1,tabStopId:l,children:o,...c}=t,d=cy(),u=l||d,h=Kks(Xks,r),m=h.currentTabStopId===u,f=ZFt(r),{onFocusableItemAdd:g,onFocusableItemRemove:x,currentTabStopId:v}=h,y=Uks();return Af(()=>{if(!(!y||!a))return g(),()=>x()},[y,a,g,x]),j.useEffect(()=>{if(!(y||!a))return g(),()=>x()},[y,a,g,x]),e.jsx(bHe.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=QFt(b,h.orientation,h.dir);if(w!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let A=f().filter(E=>E.focusable).map(E=>E.ref.current);if(w==="last")A.reverse();else if(w==="prev"||w==="next"){w==="prev"&&A.reverse();const E=A.indexOf(b.currentTarget);A=h.loop?JFt(A,E+1):A.slice(E+1)}setTimeout(()=>Eet(A))}}),children:typeof o=="function"?o({isCurrentTabStop:m,hasTabStop:v!=null}):o})})},"RovingFocusGroupItem")),Jks={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function XFt(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}TB(XFt,"getDirectionAwareKey");function QFt(s,t,n){const r=XFt(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Jks[r]}TB(QFt,"getFocusIntent");function Eet(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}TB(Eet,"focusFirst");function JFt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}TB(JFt,"wrapArray");var uLe=Yks,hLe=Qks,eSs=Object.defineProperty,Uh=(s,t)=>eSs(s,"name",{value:t,configurable:!0}),_He=["Enter"," "],tSs=["ArrowDown","PageUp","Home"],eOt=["ArrowUp","PageDown","End"],sSs=[...tSs,...eOt],nSs={ltr:[..._He,"ArrowRight"],rtl:[..._He,"ArrowLeft"]},rSs={ltr:["ArrowLeft"],rtl:["ArrowRight"]},mLe="Menu",[Hte,aSs,iSs]=SB(mLe),[MB,tOt]=ep(mLe,[iSs,n3,JL]),Tet=n3(),sOt=JL(),[oSs,PB]=MB(mLe),[lSs,Cae]=MB(mLe),cSs=Uh(s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=Tet(t),[c,d]=j.useState(null),u=j.useRef(!1),h=Kp(i),m=a3(a);return j.useEffect(()=>{const f=Uh(()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},"handleKeyDown"),g=Uh(()=>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=Uh(()=>h(!1),"handleBlur");return window.addEventListener("blur",f),()=>window.removeEventListener("blur",f)},[n,h]),e.jsx(bae,{...o,children:e.jsx(oSs,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(lSs,{scope:t,onClose:j.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:m,modal:l,children:r})})})},"Menu"),nOt=j.forwardRef(Uh(function(t,n){const{__scopeMenu:r,...a}=t,i=Tet(r);return e.jsx(_ae,{...i,...a,ref:n})},"MenuAnchor")),rOt="MenuPortal",[dSs,aOt]=MB(rOt,{forceMount:void 0}),uSs=Uh(s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=PB(rOt,t);return e.jsx(dSs,{scope:t,forceMount:n,children:e.jsx(my,{present:n||i.open,children:e.jsx(fae,{asChild:!0,container:a,children:r})})})},"MenuPortal"),sC="MenuContent",[hSs,Met]=MB(sC),mSs=j.forwardRef(Uh(function(t,n){const r=aOt(sC,t.__scopeMenu),{forceMount:a=r.forceMount,...i}=t,l=PB(sC,t.__scopeMenu),o=Cae(sC,t.__scopeMenu);return e.jsx(Hte.Provider,{scope:t.__scopeMenu,children:e.jsx(my,{present:a||l.open,children:e.jsx(Hte.Slot,{scope:t.__scopeMenu,children:o.modal?e.jsx(fSs,{...i,ref:n}):e.jsx(pSs,{...i,ref:n})})})})},"MenuContent")),fSs=j.forwardRef(Uh(function(t,n){const r=PB(sC,t.__scopeMenu),a=j.useRef(null),i=Vo(n,a);return j.useEffect(()=>{const l=a.current;if(l)return UIe(l)},[]),e.jsx(Pet,{...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")),pSs=j.forwardRef(Uh(function(t,n){const r=PB(sC,t.__scopeMenu);return e.jsx(Pet,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentNonModal")),gSs=hC("MenuContent.ScrollLock"),Pet=j.forwardRef(Uh(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,...v}=t,y=PB(sC,r),b=Cae(sC,r),w=Tet(r),S=sOt(r),A=aSs(r),[E,I]=j.useState(null),P=j.useRef(null),R=Vo(n,P,y.onContentChange),D=j.useRef(0),O=j.useRef(""),U=j.useRef(0),W=j.useRef(null),V=j.useRef("right"),G=j.useRef(0),Z=x?gae:j.Fragment,X=x?{as:gSs,allowPinchZoom:!0}:void 0,ae=Uh(re=>{var Ee,ke;const te=O.current+re,J=A().filter(Ie=>!Ie.disabled),ce=document.activeElement,ve=(Ee=J.find(Ie=>Ie.ref.current===ce))==null?void 0:Ee.textValue,fe=J.map(Ie=>Ie.textValue),ue=hOt(fe,te,ve),be=(ke=J.find(Ie=>Ie.textValue===ue))==null?void 0:ke.ref.current;Uh(function Ie(Fe){O.current=Fe,window.clearTimeout(D.current),Fe!==""&&(D.current=window.setTimeout(()=>Ie(""),1e3))},"updateSearch")(te),be&&setTimeout(()=>be.focus())},"handleTypeaheadSearch");j.useEffect(()=>()=>window.clearTimeout(D.current),[]),BW();const le=j.useCallback(re=>{var J,ce;return V.current===((J=W.current)==null?void 0:J.side)&&fOt(re,(ce=W.current)==null?void 0:ce.area)},[]);return e.jsx(hSs,{scope:r,searchRef:O,onItemEnter:j.useCallback(re=>{le(re)&&re.preventDefault()},[le]),onItemLeave:j.useCallback(re=>{var te;le(re)||((te=P.current)==null||te.focus(),I(null))},[le]),onTriggerLeave:j.useCallback(re=>{le(re)&&re.preventDefault()},[le]),pointerGraceTimerRef:U,onPointerGraceIntentChange:j.useCallback(re=>{W.current=re},[]),children:e.jsx(Z,{...X,children:e.jsx(BIe,{asChild:!0,trapped:i,onMountAutoFocus:Ra(l,re=>{var te;re.preventDefault(),(te=P.current)==null||te.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:e.jsx(CB,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:u,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:f,onDismiss:g,children:e.jsx(uLe,{asChild:!0,...S,dir:b.dir,orientation:"vertical",loop:a,currentTabStopId:E,onCurrentTabStopIdChange:I,onEntryFocus:Ra(d,re=>{b.isUsingKeyboardRef.current||re.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(wae,{role:"menu","aria-orientation":"vertical","data-state":Let(y.open),"data-radix-menu-content":"",dir:b.dir,...w,...v,ref:R,style:{outline:"none",...v.style},onKeyDown:Ra(v.onKeyDown,re=>{const J=re.target.closest("[data-radix-menu-content]")===re.currentTarget,ce=re.ctrlKey||re.altKey||re.metaKey,ve=re.key.length===1;J&&(re.key==="Tab"&&re.preventDefault(),!ce&&ve&&ae(re.key));const fe=P.current;if(re.target!==fe||!sSs.includes(re.key))return;re.preventDefault();const be=A().filter(Ee=>!Ee.disabled).map(Ee=>Ee.ref.current);eOt.includes(re.key)&&be.reverse(),dOt(be)}),onBlur:Ra(t.onBlur,re=>{re.currentTarget.contains(re.target)||(window.clearTimeout(D.current),O.current="")}),onPointerMove:Ra(t.onPointerMove,pG(re=>{const te=re.target,J=G.current!==re.clientX;if(re.currentTarget.contains(te)&&J){const ce=re.clientX>G.current?"right":"left";V.current=ce,G.current=re.clientX}}))})})})})})})},"MenuContentImpl")),xSs=j.forwardRef(Uh(function(t,n){const{__scopeMenu:r,...a}=t;return e.jsx(Ei.div,{...a,ref:n})},"MenuLabel")),wHe="MenuItem",fxt="menu.itemSelect",Iet=j.forwardRef(Uh(function(t,n){const{disabled:r=!1,onSelect:a,...i}=t,l=j.useRef(null),o=Cae(wHe,t.__scopeMenu),c=Met(wHe,t.__scopeMenu),d=Vo(n,l),u=j.useRef(!1),h=Uh(()=>{const m=l.current;if(!r&&m){const f=new CustomEvent(fxt,{bubbles:!0,cancelable:!0});m.addEventListener(fxt,g=>a==null?void 0:a(g),{once:!0}),DIe(m,f),f.defaultPrevented?u.current=!1:o.onClose()}},"handleSelect");return e.jsx(iOt,{...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===" "||_He.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})})},"MenuItem")),iOt=j.forwardRef(Uh(function(t,n){const{__scopeMenu:r,disabled:a=!1,textValue:i,...l}=t,o=Met(wHe,r),c=sOt(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(Hte.ItemSlot,{scope:r,disabled:a,textValue:i??f,children:e.jsx(hLe,{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,pG(x=>{a?o.onItemLeave(x):(o.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ra(t.onPointerLeave,pG(x=>o.onItemLeave(x))),onFocus:Ra(t.onFocus,()=>m(!0)),onBlur:Ra(t.onBlur,()=>m(!1))})})})},"MenuItemImpl")),ySs=j.forwardRef(Uh(function(t,n){const{checked:r=!1,onCheckedChange:a,...i}=t;return e.jsx(lOt,{scope:t.__scopeMenu,checked:r,children:e.jsx(Iet,{role:"menuitemcheckbox","aria-checked":Gte(r)?"mixed":r,...i,ref:n,"data-state":fLe(r),onSelect:Ra(i.onSelect,()=>a==null?void 0:a(Gte(r)?!0:!r),{checkForDefaultPrevented:!1})})})},"MenuCheckboxItem")),vSs="MenuRadioGroup",[lkr,bSs]=MB(vSs,{value:void 0,onValueChange:Uh(()=>{},"onValueChange")}),_Ss="MenuRadioItem",wSs=j.forwardRef(Uh(function(t,n){const{value:r,...a}=t,i=bSs(_Ss,t.__scopeMenu),l=r===i.value;return e.jsx(lOt,{scope:t.__scopeMenu,checked:l,children:e.jsx(Iet,{role:"menuitemradio","aria-checked":l,...a,ref:n,"data-state":fLe(l),onSelect:Ra(a.onSelect,()=>{var o;return(o=i.onValueChange)==null?void 0:o.call(i,r)},{checkForDefaultPrevented:!1})})})},"MenuRadioItem")),oOt="MenuItemIndicator",[lOt,jSs]=MB(oOt,{checked:!1}),NSs=j.forwardRef(Uh(function(t,n){const{__scopeMenu:r,forceMount:a,...i}=t,l=jSs(oOt,r);return e.jsx(my,{present:a||Gte(l.checked)||l.checked===!0,children:e.jsx(Ei.span,{...i,ref:n,"data-state":fLe(l.checked)})})},"MenuItemIndicator")),kSs=j.forwardRef(Uh(function(t,n){const{__scopeMenu:r,...a}=t;return e.jsx(Ei.div,{role:"separator","aria-orientation":"horizontal",...a,ref:n})},"MenuSeparator")),SSs="MenuSub",[ckr,cOt]=MB(SSs),jce="MenuSubTrigger",CSs=j.forwardRef(Uh(function(t,n){const r=PB(jce,t.__scopeMenu),a=Cae(jce,t.__scopeMenu),i=cOt(jce,t.__scopeMenu),l=Met(jce,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(nOt,{asChild:!0,...u,children:e.jsx(iOt,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":r.open?i.contentId:void 0,"data-state":Let(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,pG(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,pG(f=>{var x,v;h();const g=(x=r.content)==null?void 0:x.getBoundingClientRect();if(g){const y=(v=r.content)==null?void 0:v.dataset.side,b=y==="right",w=b?-5:5,S=g[b?"left":"right"],A=g[b?"right":"left"];l.onPointerGraceIntentChange({area:[{x:f.clientX+w,y:f.clientY},{x:S,y:g.top},{x:A,y:g.top},{x:A,y:g.bottom},{x:S,y:g.bottom}],side:y}),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===" "||nSs[a.dir].includes(f.key)&&(r.onOpenChange(!0),(x=r.content)==null||x.focus(),f.preventDefault())})})})},"MenuSubTrigger")),ASs="MenuSubContent",ESs=j.forwardRef(Uh(function(t,n){const r=aOt(sC,t.__scopeMenu),{forceMount:a=r.forceMount,align:i="start",...l}=t,o=PB(sC,t.__scopeMenu),c=Cae(sC,t.__scopeMenu),d=cOt(ASs,t.__scopeMenu),u=j.useRef(null),h=Vo(n,u);return e.jsx(Hte.Provider,{scope:t.__scopeMenu,children:e.jsx(my,{present:a||o.open,children:e.jsx(Hte.Slot,{scope:t.__scopeMenu,children:e.jsx(Pet,{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=rSs[c.dir].includes(m.key);f&&g&&(o.onOpenChange(!1),(x=d.trigger)==null||x.focus(),m.preventDefault())})})})})})},"MenuSubContent"));function Let(s){return s?"open":"closed"}Uh(Let,"getOpenState");function Gte(s){return s==="indeterminate"}Uh(Gte,"isIndeterminate");function fLe(s){return Gte(s)?"indeterminate":s?"checked":"unchecked"}Uh(fLe,"getCheckedState");function dOt(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}Uh(dOt,"focusFirst");function uOt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}Uh(uOt,"wrapArray");function hOt(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=uOt(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}Uh(hOt,"getNextMatch");function mOt(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}Uh(mOt,"isPointInPolygon");function fOt(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return mOt(n,t)}Uh(fOt,"isPointerInGraceArea");function pG(s){return t=>t.pointerType==="mouse"?s(t):void 0}Uh(pG,"whenMouse");var TSs=cSs,MSs=nOt,PSs=uSs,ISs=mSs,LSs=xSs,RSs=Iet,DSs=ySs,FSs=wSs,OSs=NSs,zSs=kSs,BSs=CSs,$Ss=ESs,USs=Object.defineProperty,bk=(s,t)=>USs(s,"name",{value:t,configurable:!0}),Ret="DropdownMenu",[qSs,dkr]=ep(Ret,[tOt]),_k=tOt(),[VSs,pOt]=qSs(Ret),HSs=bk(s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=_k(t),d=j.useRef(null),[u,h]=dy({prop:a,defaultProp:i??!1,onChange:l,caller:Ret});return e.jsx(VSs,{scope:t,triggerId:cy(),triggerRef:d,contentId:cy(),open:u,onOpenChange:h,onOpenToggle:j.useCallback(()=>h(m=>!m),[h]),modal:o,children:e.jsx(TSs,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})},"DropdownMenu"),GSs="DropdownMenuTrigger",WSs=j.forwardRef(bk(function(t,n){const{__scopeDropdownMenu:r,disabled:a=!1,...i}=t,l=pOt(GSs,r),o=_k(r),c=Vo(n,l.triggerRef);return e.jsx(MSs,{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")),KSs=bk(s=>{const{__scopeDropdownMenu:t,...n}=s,r=_k(t);return e.jsx(PSs,{...r,...n})},"DropdownMenuPortal"),YSs="DropdownMenuContent",ZSs=j.forwardRef(bk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=pOt(YSs,r),l=_k(r),o=j.useRef(!1);return e.jsx(ISs,{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")),XSs=j.forwardRef(bk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=_k(r);return e.jsx(LSs,{...i,...a,ref:n})},"DropdownMenuLabel")),QSs=j.forwardRef(bk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=_k(r);return e.jsx(RSs,{...i,...a,ref:n})},"DropdownMenuItem")),JSs=j.forwardRef(bk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=_k(r);return e.jsx(DSs,{...i,...a,ref:n})},"DropdownMenuCheckboxItem")),eCs=j.forwardRef(bk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=_k(r);return e.jsx(FSs,{...i,...a,ref:n})},"DropdownMenuRadioItem")),tCs=j.forwardRef(bk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=_k(r);return e.jsx(OSs,{...i,...a,ref:n})},"DropdownMenuItemIndicator")),sCs=j.forwardRef(bk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=_k(r);return e.jsx(zSs,{...i,...a,ref:n})},"DropdownMenuSeparator")),nCs=j.forwardRef(bk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=_k(r);return e.jsx(BSs,{...i,...a,ref:n})},"DropdownMenuSubTrigger")),rCs=j.forwardRef(bk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=_k(r);return e.jsx($Ss,{...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=HSs,iCs=WSs,oCs=KSs,gOt=ZSs,xOt=XSs,yOt=QSs,vOt=JSs,bOt=eCs,_Ot=tCs,wOt=sCs,jOt=nCs,NOt=rCs;const Bu=aCs,$u=iCs,lCs=j.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(jOt,{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"})]}));lCs.displayName=jOt.displayName;const cCs=j.forwardRef(({className:s,...t},n)=>e.jsx(NOt,{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}));cCs.displayName=NOt.displayName;const Cu=j.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(oCs,{children:e.jsx(gOt,{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})}));Cu.displayName=gOt.displayName;const ja=j.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(yOt,{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=yOt.displayName;const dCs=j.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(vOt,{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(_Ot,{children:e.jsx(ma,{className:"h-4 w-4"})})}),t]}));dCs.displayName=vOt.displayName;const uCs=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(bOt,{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(_Ot,{children:e.jsx(Dg,{className:"h-2 w-2 fill-current"})})}),t]}));uCs.displayName=bOt.displayName;const _L=j.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(xOt,{ref:r,className:Pt("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));_L.displayName=xOt.displayName;const P0=j.forwardRef(({className:s,...t},n)=>e.jsx(wOt,{ref:n,className:Pt("-mx-1 my-1 h-px bg-muted",s),...t}));P0.displayName=wOt.displayName;const hCs=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=Sae();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(Yn,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(Bu,{children:[e.jsx($u,{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(Ii,{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(wl,{className:"h-3 w-3"})]})}),e.jsxs(Cu,{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($e,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(P0,{}),n.map(o=>e.jsxs(ja,{onClick:()=>r(o),className:"gap-2",children:[e.jsxs(Oa,{className:"h-6 w-6",children:[e.jsx(Ii,{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($e,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx($e,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})};function bC(){var c,d;const{user:s,isAdmin:t}=_s(),{data:n,isLoading:r}=st({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 Det={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"},ukr=Object.keys(Det),mCs={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},pxt={"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 pCs(s){return s.id in pxt?pxt[s.id]:mCs[s.primaryCategory]??null}function gCs(s){return fCs[s]??null}const xCs=[["/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 kOt(s){let t=null;for(const n of xCs){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 je=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}));je.displayName="Card";const St=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Pt("flex flex-col space-y-1.5 p-6",s),...t}));St.displayName="CardHeader";const Et=j.forwardRef(({className:s,...t},n)=>e.jsx("h3",{ref:n,className:Pt("text-2xl font-semibold leading-none tracking-tight",s),...t}));Et.displayName="CardTitle";const Vn=j.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:Pt("text-sm text-muted-foreground",s),...t}));Vn.displayName="CardDescription";const Le=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Pt("p-6 pt-0",s),...t}));Le.displayName="CardContent";const gEe=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Pt("flex items-center p-6 pt-0",s),...t}));gEe.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 Os=qIe,jl=tet,yCs=VIe,hkr=vae,SOt=j.forwardRef(({className:s,...t},n)=>e.jsx($W,{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}));SOt.displayName=$W.displayName;const Fs=j.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs(yCs,{children:[e.jsx(SOt,{className:n}),e.jsxs(UW,{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(vae,{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(mr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fs.displayName=UW.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 Nr=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Nr.displayName="DialogFooter";const $s=j.forwardRef(({className:s,...t},n)=>e.jsx(xae,{ref:n,className:Pt("text-lg font-semibold leading-none tracking-tight",s),...t}));$s.displayName=xae.displayName;const Er=j.forwardRef(({className:s,...t},n)=>e.jsx(yae,{ref:n,className:Pt("text-sm text-muted-foreground",s),...t}));Er.displayName=yae.displayName;function vCs({featureKey:s,open:t,onOpenChange:n}){const{user:r}=_s(),a=Zt(),[i,l]=j.useState(""),{data:o}=st({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=mt({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"]}),ne.success("Request sent — we'll be in touch shortly."),l(""),n(!1)},onError:h=>ne.error((h==null?void 0:h.message)||"Could not send your request")}),u=Det[s]||s;return e.jsx(Os,{open:t,onOpenChange:n,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-5 w-5 text-primary"}),"Request ",u]}),e.jsxs(Er,{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(ma,{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(Nr,{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 bCs({featureKey:s}){const[t,n]=j.useState(!1),r=Det[s]||s;return e.jsxs("div",{className:"flex items-center justify-center py-16 px-4",children:[e.jsx(je,{className:"max-w-lg w-full border-border/60",children:e.jsxs(Le,{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(jc,{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(wn,{className:"h-4 w-4"})," Request access"]})]})}),e.jsx(vCs,{featureKey:s,open:t,onOpenChange:n})]})}const COt=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)}}}},AOt=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},_Cs=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},Aae=()=>{const{data:s,isLoading:t}=st({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")}},gxt="community_last_seen_post_at";function wCs(){const{user:s}=_s(),t=qu(),[n,r]=j.useState(0),[a,i]=j.useState(null);j.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${gxt}_${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||ne("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(`${gxt}_${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 jCs(){const{isAdmin:s}=_s(),{data:t=0}=st({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 Bze=s=>`levelup:activeTeam:${s}`,Eae=()=>{const s=Sa();return st({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})},Ow=()=>{const s=Sa(),t=Eae(),n=j.useMemo(()=>t.data||[],[t.data]),[r,a]=j.useState(()=>!s||typeof window>"u"?null:window.localStorage.getItem(Bze(s)));j.useEffect(()=>{!s||typeof window>"u"||a(window.localStorage.getItem(Bze(s)))},[s]);const i=j.useCallback(o=>{a(o),s&&typeof window<"u"&&window.localStorage.setItem(Bze(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}},VU="weekly_reels";function pLe(){const{user:s,loading:t,isAdmin:n}=_s(),{data:r,isLoading:a}=st({queryKey:["feature-entitlement",VU,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",VU).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 Vy=qIe,Tae=tet,NCs=VIe,EOt=j.forwardRef(({className:s,...t},n)=>e.jsx($W,{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}));EOt.displayName=$W.displayName;const kCs=AB("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"}}),uy=j.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(NCs,{children:[e.jsx(EOt,{}),e.jsxs(UW,{ref:a,className:Pt(kCs({side:s}),t),...r,children:[n,e.jsxs(vae,{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(mr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));uy.displayName=UW.displayName;const I0=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col space-y-2 text-center sm:text-left",s),...t});I0.displayName="SheetHeader";const TOt=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});TOt.displayName="SheetFooter";const L0=j.forwardRef(({className:s,...t},n)=>e.jsx(xae,{ref:n,className:Pt("text-lg font-semibold text-foreground",s),...t}));L0.displayName=xae.displayName;const IB=j.forwardRef(({className:s,...t},n)=>e.jsx(yae,{ref:n,className:Pt("text-sm text-muted-foreground",s),...t}));IB.displayName=yae.displayName;var SCs=Object.defineProperty,CCs=(s,t)=>SCs(s,"name",{value:t,configurable:!0});function gG(s,[t,n]){return Math.min(n,Math.max(t,s))}CCs(gG,"clamp");var ACs=Object.defineProperty,Nu=(s,t)=>ACs(s,"name",{value:t,configurable:!0});function MOt(s,t){return j.useReducer((n,r)=>t[n][r]??n,s)}Nu(MOt,"useStateMachine");var POt="ScrollArea",[IOt,mkr]=ep(POt),[ECs,wk]=IOt(POt),TCs=j.forwardRef(Nu(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),[v,y]=j.useState(null),[b,w]=j.useState(0),[S,A]=j.useState(0),[E,I]=j.useState(!1),[P,R]=j.useState(!1),D=Vo(n,d),O=a3(i);return e.jsx(ECs,{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:v,onScrollbarYChange:y,scrollbarYEnabled:P,onScrollbarYEnabledChange:R,onCornerWidthChange:w,onCornerHeightChange:A,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")),MCs="ScrollAreaViewport",PCs=j.forwardRef(Nu(function(t,n){const{__scopeScrollArea:r,children:a,nonce:i,...l}=t,o=wk(MCs,r),c=j.useRef(null),d=Vo(n,c,o.onViewportChange);return e.jsxs(e.Fragment,{children:[e.jsx(ICs,{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")),ICs=j.memo(Nu(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),AT="ScrollAreaScrollbar",LOt=j.forwardRef(Nu(function(t,n){const{forceMount:r,...a}=t,i=wk(AT,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(LCs,{...a,ref:n,forceMount:r}):i.type==="scroll"?e.jsx(RCs,{...a,ref:n,forceMount:r}):i.type==="auto"?e.jsx(ROt,{...a,ref:n,forceMount:r}):i.type==="always"?e.jsx(Fet,{...a,ref:n,"data-state":"visible"}):null},"ScrollAreaScrollbar")),LCs=j.forwardRef(Nu(function(t,n){const{forceMount:r,...a}=t,i=wk(AT,t.__scopeScrollArea),[l,o]=j.useState(!1);return j.useEffect(()=>{const c=i.scrollArea;let d=0;if(c){const u=Nu(()=>{window.clearTimeout(d),o(!0)},"handlePointerEnter"),h=Nu(()=>{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(my,{present:r||l,children:e.jsx(ROt,{"data-state":l?"visible":"hidden",...a,ref:n})})},"ScrollAreaScrollbarHover")),RCs=j.forwardRef(Nu(function(t,n){const{forceMount:r,...a}=t,i=wk(AT,t.__scopeScrollArea),l=t.orientation==="horizontal",o=Pae(()=>d("SCROLL_END"),100),[c,d]=MOt("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=Nu(()=>{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(my,{present:r||c!=="hidden",children:e.jsx(Fet,{"data-state":c==="hidden"?"hidden":"visible",...a,ref:n,onPointerEnter:Ra(t.onPointerEnter,()=>d("POINTER_ENTER")),onPointerLeave:Ra(t.onPointerLeave,()=>d("POINTER_LEAVE"))})})},"ScrollAreaScrollbarScroll")),ROt=j.forwardRef(Nu(function(t,n){const r=wk(AT,t.__scopeScrollArea),{forceMount:a,...i}=t,[l,o]=j.useState(!1),c=t.orientation==="horizontal",d=Pae(()=>{if(r.viewport){const u=r.viewport.offsetWidth0&&u<1,onThumbChange:Nu(f=>l.current=f,"onThumbChange"),onThumbPointerUp:Nu(()=>o.current=0,"onThumbPointerUp"),onThumbPointerDown:Nu(f=>o.current=f,"onThumbPointerDown")};function m(f,g){return zOt(f,o.current,c,g)}return Nu(m,"getScrollPosition"),r==="horizontal"?e.jsx(DCs,{...h,ref:n,onThumbPositionChange:()=>{if(i.viewport&&l.current){const f=i.viewport.scrollLeft,g=NHe(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(FCs,{...h,ref:n,onThumbPositionChange:()=>{if(i.viewport&&l.current){const f=i.viewport.scrollTop,g=NHe(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")),DCs=j.forwardRef(Nu(function(t,n){const{sizes:r,onSizesChange:a,...i}=t,l=wk(AT,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(FOt,{"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":Mae(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),Bet(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:Wte(o.paddingLeft),paddingEnd:Wte(o.paddingRight)}})}})},"ScrollAreaScrollbarX")),FCs=j.forwardRef(Nu(function(t,n){const{sizes:r,onSizesChange:a,...i}=t,l=wk(AT,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(FOt,{"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":Mae(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),Bet(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:Wte(o.paddingTop),paddingEnd:Wte(o.paddingBottom)}})}})},"ScrollAreaScrollbarY")),[OCs,DOt]=IOt(AT),FOt=j.forwardRef(Nu(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=wk(AT,r),[x,v]=j.useState(null),y=Vo(n,v),b=j.useRef(null),w=j.useRef(""),S=g.viewport,A=a.content-a.viewport,E=Kp(h),I=Kp(d),P=Pae(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 Nu(R,"handleDragScroll"),j.useEffect(()=>{const D=Nu(O=>{const U=O.target;(x==null?void 0:x.contains(U))&&E(O,A)},"handleWheel");return document.addEventListener("wheel",D,{passive:!1}),()=>document.removeEventListener("wheel",D,{passive:!1})},[S,x,A,E]),j.useEffect(I,[a,I]),F7(x,P),F7(g.content,P),e.jsx(OCs,{scope:r,scrollbar:x,hasThumb:i,onThumbChange:Kp(l),onThumbPointerUp:Kp(o),onThumbPositionChange:I,onThumbPointerDown:Kp(c),children:e.jsx(Ei.div,{...f,ref:y,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")),jHe="ScrollAreaThumb",zCs=j.forwardRef(Nu(function(t,n){const{forceMount:r,...a}=t,i=DOt(jHe,t.__scopeScrollArea);return e.jsx(my,{present:r||i.hasThumb,children:e.jsx(BCs,{ref:n,...a})})},"ScrollAreaThumb")),BCs=j.forwardRef(Nu(function(t,n){const{__scopeScrollArea:r,style:a,...i}=t,l=wk(jHe,r),o=DOt(jHe,r),{onThumbPositionChange:c}=o,d=Vo(n,o.onThumbChange),u=j.useRef(void 0),h=Pae(()=>{u.current&&(u.current(),u.current=void 0)},100);return j.useEffect(()=>{const m=l.viewport;if(m){const f=Nu(()=>{if(h(),!u.current){const g=qCs(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,v=m.clientY-g.top;o.onThumbPointerDown({x,y:v})}),onPointerUp:Ra(t.onPointerUp,o.onThumbPointerUp)})},"ScrollAreaThumbImpl")),OOt="ScrollAreaCorner",$Cs=j.forwardRef(Nu(function(t,n){const r=wk(OOt,t.__scopeScrollArea),a=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&a?e.jsx(UCs,{...t,ref:n}):null},"ScrollAreaCorner")),UCs=j.forwardRef(Nu(function(t,n){const{__scopeScrollArea:r,...a}=t,i=wk(OOt,r),[l,o]=j.useState(0),[c,d]=j.useState(0),u=!!(l&&c),{onCornerWidthChange:h,onCornerHeightChange:m}=i;return F7(i.scrollbarX,()=>{var g;const f=((g=i.scrollbarX)==null?void 0:g.offsetHeight)||0;i.onCornerHeightChange(f),d(f)}),F7(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 Wte(s){return s?parseInt(s,10):0}Nu(Wte,"toInt");function Oet(s,t){const n=s/t;return isNaN(n)?0:n}Nu(Oet,"getThumbRatio");function Mae(s){const t=Oet(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}Nu(Mae,"getThumbSize");function zOt(s,t,n,r="ltr"){const a=Mae(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 zet([c,d],h)(s)}Nu(zOt,"getScrollPositionFromPointer");function NHe(s,t,n="ltr"){const r=Mae(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=gG(s,c);return zet([0,l],[0,o])(d)}Nu(NHe,"getThumbOffsetFromScroll");function zet(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])}}Nu(zet,"linearScale");function Bet(s,t){return s>0&&s{})=>{let n={left:s.scrollLeft,top:s.scrollTop},r=0;return Nu(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 Pae(s,t){const n=Kp(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])}Nu(Pae,"useDebounceCallback");function F7(s,t){const n=Kp(t);Af(()=>{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])}Nu(F7,"useResizeObserver");var BOt=TCs,VCs=PCs,HCs=$Cs;const go=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(BOt,{ref:r,className:Pt("relative overflow-hidden",s),...n,children:[e.jsx(VCs,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Iae,{}),e.jsx(HCs,{})]}));go.displayName=BOt.displayName;const Iae=j.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(LOt,{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(zCs,{className:"relative flex-1 rounded-full bg-border"})}));Iae.displayName=LOt.displayName;const GCs="/assets/levelup-logo-Eif24dqY.png",WCs="/assets/levelup-logo-icon-C-7iromj.png",KCs="/assets/levelup-logo-mobile-B9skSjUG.png";var Lae=s=>s.type==="checkbox",gLe=s=>s.type==="file",mI=s=>s instanceof Date,cv=s=>s==null;const $et=s=>typeof s=="object";var Gp=s=>!cv(s)&&!Array.isArray(s)&&$et(s)&&!mI(s),kHe=s=>Gp(s)&&s.target?Lae(s.target)?s.target.checked:gLe(s.target)?s.target.files:s.target.value:s;const YCs=/[.[\]'"]/;var O7=s=>s.split(YCs).filter(Boolean);function ZCs(s,t){const n=O7(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("."))),xLe=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Uf(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(xLe&&(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]=Uf(s[i]));return a}const oP={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},MN={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oS={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},UOt="root",Uet=["__proto__","constructor","prototype"],XCs=/^\w*$/;var xG=s=>XCs.test(s),Oh=s=>s===void 0,Ri=(s,t,n)=>{if(!t||!Gp(s))return n;const r=xG(t)?[t]:O7(t);if(r.some(i=>Uet.includes(i)))return n;const a=r.reduce((i,l)=>cv(i)?void 0:i[l],s);return Oh(a)||a===s?Oh(s[t])?n:s[t]:a},Uj=s=>typeof s=="boolean",d1=s=>typeof s=="function",Qh=(s,t,n)=>{let r=-1;const a=xG(t)?[t]:O7(t),i=a.length,l=i-1;for(;++rKt.useContext(qet);var qOt=(s,t,n,r=!0)=>{const a={};for(const i in s)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==MN.all&&(t._proxyFormState[l]=!r||MN.all),n&&(n[l]=!0),s[l]}});return a};const Het=xLe?Kt.useLayoutEffect:Kt.useEffect;var QCs=s=>{const t=s.constructor&&s.constructor.prototype;return Gp(t)&&t.hasOwnProperty("isPrototypeOf")},SHe=s=>cv(s)||!$et(s);const xxt=(s,t)=>t.length===0&&!Array.isArray(s)&&!QCs(s);function dw(s,t,n=new WeakMap){if(s===t)return!0;if(SHe(s)||SHe(t))return Object.is(s,t);if(mI(s)&&mI(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(xxt(s,r)||xxt(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(mI(o)&&mI(c)||(Gp(o)||Array.isArray(o))&&(Gp(c)||Array.isArray(c))?!dw(o,c,n):!Object.is(o,c))return!1}}return!0}function Get(s){const t=Kt.useRef(!1),n=Kt.useRef(!1),r=Kt.useRef(void 0),a=Kt.useRef(0);a.current++,!n.current&&s&&(n.current=!0,r.current=Uf(s()));const i=Kt.useCallback((o,c,d)=>{if(o&&(t.current||n.current&&a.current>1)){const u=c();dw(r.current,u)||d(u)}t.current=!0},[]),l=Kt.useCallback((o,c)=>{o&&(r.current=Uf(c()))},[]);return{resyncIfNeeded:i,snapshot:l}}function JCs(s){const t=Vet(),{control:n=t,disabled:r,name:a,exact:i}=s||{},l=()=>({...n._formState,defaultValues:n._defaultValues}),[o,c]=Kt.useState(l),d=Kt.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),{resyncIfNeeded:u,snapshot:h}=Get(l);return Het(()=>{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]),Kt.useEffect(()=>{d.current.isValid&&n._setValid(!0)},[n]),Kt.useMemo(()=>qOt(o,n,d.current,!1),[o,n])}var mv=s=>typeof s=="string",CHe=(s,t,n,r,a)=>mv(s)?(r&&t.watch.add(s),Ri(n,s,a)):Array.isArray(s)?s.map(i=>(r&&t.watch.add(i),Ri(n,i,Ri(a,i)))):(r&&(t.watchAll=!0),n);function e5s(s){const t=Vet(),{control:n=t,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=Kt.useRef(a),d=Kt.useRef(o),u=Kt.useRef(n),h=Kt.useRef(r);d.current=o;const m=()=>{const R=n._getWatch(r,c.current);return d.current?d.current(R):R},[f,g]=Kt.useState(m),x=Kt.useRef(f),v=Kt.useCallback(R=>{const D=CHe(r,n._names,R||n._formValues,!1,c.current);return d.current?d.current(D):D},[n._formValues,n._names,r]),y=Kt.useCallback(R=>{if(!i){const D=CHe(r,n._names,R||n._formValues,!1,c.current);if(d.current){const O=d.current(D);dw(O,x.current)||(g(O),x.current=O)}else g(D)}},[n._formValues,n._names,i,r]),{resyncIfNeeded:b,snapshot:w}=Get(m),S=Kt.useRef(y);S.current=y;const A=Kt.useRef(v);A.current=v,Het(()=>{u.current!==n||!dw(h.current,r)?(u.current=n,h.current=r,S.current()):b(!i,()=>A.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,()=>A.current())}},[n,l,r,i,b,w]),Kt.useEffect(()=>n._removeUnmounted());const E=u.current!==n,I=h.current;return Kt.useMemo(()=>{if(i)return!1;const R=!E&&!dw(I,r);return E||R},[i,E,r,I])?v():f}function t5s(s){const t=Vet(),{name:n,disabled:r,control:a=t,shouldUnregister:i,defaultValue:l,exact:o=!0}=s,c=$Ot(a._names.array,n),d=Kt.useMemo(()=>{const S=Ri(a._formValues,n,Ri(a._defaultValues,n,l));return Oh(S)?ZCs(a,n):S},[a,n,l]),u=e5s({control:a,name:n,defaultValue:d,exact:o}),h=JCs({control:a,name:n,exact:o}),m=Kt.useRef(s),f=Kt.useRef(null),g=Kt.useRef(a.register(n,{...s.rules,value:u,...Uj(s.disabled)?{disabled:s.disabled}:{}}));m.current=s;const x=Kt.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!Ri(h.errors,n)},isDirty:{enumerable:!0,get:()=>!!Ri(h.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!Ri(h.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!Ri(h.validatingFields,n)},error:{enumerable:!0,get:()=>Ri(h.errors,n)}}),[h,n]),v=Kt.useCallback(S=>{const A=kHe(S);return Ri(a._fields,n)||(g.current=a.register(n,{...m.current.rules,value:A})),g.current.onChange({target:{value:kHe(S),name:n},type:oP.CHANGE})},[n,a]),y=Kt.useCallback(()=>g.current.onBlur({target:{value:Ri(a._formValues,n),name:n},type:oP.BLUR}),[n,a._formValues]),b=Kt.useCallback(S=>{S&&(f.current={focus:()=>d1(S.focus)&&S.focus(),select:()=>d1(S.select)&&S.select(),setCustomValidity:E=>d1(S.setCustomValidity)&&S.setCustomValidity(E),reportValidity:()=>d1(S.reportValidity)&&S.reportValidity()});const A=Ri(a._fields,n);A&&A._f&&S&&(A._f.ref=f.current)},[a._fields,n]),w=Kt.useMemo(()=>({name:n,value:u,...Uj(r)||h.disabled?{disabled:h.disabled||r}:{},onChange:v,onBlur:y,ref:b}),[n,r,h.disabled,v,y,b,u]);return Kt.useEffect(()=>{const S=a._options.shouldUnregister||i;g.current=a.register(n,{...m.current.rules,...Uj(m.current.disabled)?{disabled:m.current.disabled}:{}});const A=(E,I)=>{const P=Ri(a._fields,E);P&&P._f&&(P._f.mount=I)};if(A(n,!0),S){const E=Uf(Ri(i?a._defaultValues:a._options.values||a._defaultValues,n,Ri(a._options.defaultValues,n,m.current.defaultValue)));Qh(a._defaultValues,n,E),Oh(Ri(a._formValues,n))&&Qh(a._formValues,n,E)}if(!c&&a.register(n),f.current){const E=Ri(a._fields,n);E&&E._f&&(E._f.ref=f.current)}return()=>{(c?S&&!a._state.action:S)?a.unregister(n):A(n,!1)}},[n,a,c,i]),Kt.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),Kt.useMemo(()=>({field:w,formState:h,fieldState:x}),[w,h,x])}const s5s=s=>s.render(t5s(s));var Nce=s=>({isOnSubmit:!s||s===MN.onSubmit,isOnBlur:s===MN.onBlur,isOnChange:s===MN.onChange,isOnAll:s===MN.all,isOnTouch:s===MN.onTouched}),$ze=(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 cee=(s,t,n)=>{for(const r of n||Object.keys(s)){if(r==="_f")continue;const a=n?Ri(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(cee(a,t))return!0}else if((Gp(a)||Array.isArray(a))&&cee(a,t))return!0}}};var yxt=(s,t,n)=>{const r=Ri(s,n),a=Array.isArray(r)?r:[];return Qh(a,UOt,t[n]),Qh(s,n,a),s},ky=s=>Gp(s)&&!Object.keys(s).length,xEe=s=>{if(!xLe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Wet=s=>s.type==="radio",yEe=s=>s instanceof RegExp,VOt=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{};const vxt={value:!1,isValid:!1},bxt={value:!0,isValid:!0};var HOt=s=>{if(!Array.isArray(s))return vxt;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?vxt:!t.attributes||!("value"in t.attributes)||Oh(t.value)||t.value===""?bxt:{value:t.value,isValid:!0}};const _xt={isValid:!1,value:null};var GOt=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,_xt):_xt;function wxt(s,t,n="validate"){if(mv(s)||Array.isArray(s)&&s.every(mv)||Uj(s)&&!s)return{type:n,message:mv(s)?s:"",ref:t}}var f$=s=>Gp(s)&&!yEe(s)?s:{value:s,message:""},jxt=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:v,mount:y}=s._f,b=Ri(n,x);if(!y||t.has(x))return{};const w=o?o[0]:l,S=W=>{if(a&&w.reportValidity){const V=Uj(W)?"":W||"";o?o.forEach(G=>G.setCustomValidity(V)):w.setCustomValidity(V),w.reportValidity()}},A={},E=Wet(l),I=Lae(l),P=E||I,R=(v||gLe(l))&&Oh(l.value)&&Oh(b)||xEe(l)&&l.value===""||b===""||Array.isArray(b)&&!b.length,D=VOt.bind(null,x,r,A),O=(W,V,G,Z=oS.maxLength,X=oS.minLength)=>{const ae=W?V:G;A[x]={type:W?Z:X,message:ae,ref:l,...D(W?Z:X,ae)}};if(i?!Array.isArray(b)||!b.length:c&&(!P&&(R||cv(b))||Uj(b)&&!b||I&&!HOt(o).isValid||E&&!GOt(o).isValid)){const{value:W,message:V}=mv(c)?{value:!!c,message:c}:f$(c);if(W&&(A[x]={type:oS.required,message:V,ref:w,...D(oS.required,V)},!r))return S(V),A}if(!R&&(!cv(h)||!cv(m))){let W,V;const G=f$(m),Z=f$(h);if(!cv(b)&&!mI(b)&&!isNaN(b)){const X=l.valueAsNumber||b&&+b;cv(G.value)||(W=X>G.value),cv(Z.value)||(V=Xnew Date(new Date().toDateString()+" "+te),le=l.type=="time",re=l.type=="week";mv(G.value)&&b&&(W=le?ae(b)>ae(G.value):re?b>G.value:X>new Date(G.value)),mv(Z.value)&&b&&(V=le?ae(b)+W.value,Z=!cv(V.value)&&b.length<+V.value;if((G||Z)&&(O(G,W.message,V.message),!r))return S(A[x].message),A}if(f&&!R&&mv(b)){const{value:W,message:V}=f$(f);if(yEe(W)&&!b.match(W)&&(A[x]={type:oS.pattern,message:V,ref:l,...D(oS.pattern,V)},!r))return S(V),A}if(g){if(d1(g)){const W=await g(b,n),V=wxt(W,w);if(V&&(A[x]={...V,...D(oS.validate,V.message)},!r))return S(V.message),A}else if(Gp(g)){let W={};for(const V in g){if(!ky(W)&&!r)break;const G=wxt(await g[V](b,n),w,V);G&&(W={...G,...D(V,G.message)},r||S(G.message),r&&(A[x]=W))}if(!ky(W)&&(A[x]={ref:w,...W},!r))return A}}const U=A[x];return S(U?U.message:!0),A},U4e=s=>Array.isArray(s)?s:[s],WOt=s=>Array.isArray(s)?s.filter(Boolean):[];function n5s(s,t){const n=t.length-1;let r=0;for(;rUet.includes(String(l))))return s;const r=n.length===1?s:n5s(s,n),a=n.length-1,i=n[a];return r&&delete r[i],a!==0&&(Gp(r)&&ky(r)||Array.isArray(r)&&r5s(r))&&ox(s,n.slice(0,-1)),s}const Ket=Kt.createContext(null);Ket.displayName="HookFormContext";const a5s=()=>Kt.useContext(Ket),i5s=({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:v,register:y,setFocus:b,subscribe:w})=>{const S=Kt.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:v,register:y,setFocus:b,subscribe:w}),[l,v,u,r,a,n,g,y,m,f,h,i,b,o,c,w,d,x,t]);return Kt.createElement(Ket.Provider,{value:S},Kt.createElement(qet.Provider,{value:S.control},s))};var Nxt=()=>{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 KOt(s,t){const n={};for(const r in s)if(s.hasOwnProperty(r)){const a=s[r],i=t[r];if(a&&Gp(a)&&i){const l=KOt(a,i);Gp(l)&&(n[r]=l)}else s[r]&&(n[r]=i)}return n}const kxt=(s,t)=>s!==null&&$et(s)&&Object.prototype.hasOwnProperty.call(s,t);var o5s=(s,t)=>{if(!t)return!1;let n=s;for(const r of xG(t)?[t]:O7(t)){if(!kxt(n,r))return kxt(s,t);n=n[r]}return!0},YOt=s=>s.type==="select-multiple",l5s=s=>Wet(s)||Lae(s),Uze=s=>xEe(s)&&s.isConnected;function Sxt(s){return Array.isArray(s)||Gp(s)}function ZOt(s,t,n="",r=[]){for(const a in s){const i=n?`${n}.${a}`:a,l=s[a];Sxt(l)&&Sxt(Ri(t,i))?ZOt(l,t,i,r):r.push(i)}return r}var c5s=s=>{for(const t in s)if(d1(s[t]))return!0;return!1};function XOt(s){return Array.isArray(s)||Gp(s)&&!c5s(s)}function QOt(s){return!!(s&&"_f"in s)}function JOt(s){return Array.isArray(s)?!s.some(t=>!Oh(t)):!Object.keys(s).length}function AHe(s,t){Array.isArray(s)?s[t]=void 0:delete s[t]}function EHe(s,t={},n){for(const r in s){const a=s[r],i=n&&n[r];XOt(a)&&(!Array.isArray(a)||!QOt(i))?(t[r]=Array.isArray(a)?[]:{},EHe(a,t[r],i),JOt(t[r])&&AHe(t,r)):Oh(a)||(t[r]=!0)}return t}function $M(s,t,n,r){n||(n=EHe(t,{},r));for(const a in s){const i=s[a],l=r&&r[a];XOt(i)&&(!Array.isArray(i)||!QOt(l))?(Oh(t)||SHe(n[a])?n[a]=EHe(i,Array.isArray(i)?[]:{},l):$M(i,cv(t)?{}:t[a],n[a],l),JOt(n[a])&&AHe(n,a)):dw(i,t[a])?AHe(n,a):n[a]=!0}return n}var d5s=(s,t)=>{const n=t.split("."),r=[];let a=n[0];for(let i=1;iOh(s)?s:t?s===""?NaN:s&&+s:n&&mv(s)?new Date(s):r?r(s):s;function Cxt(s){const t=s.ref;return gLe(t)?t.files:Wet(t)?GOt(s.refs).value:YOt(t)?[...t.selectedOptions].map(({value:n})=>n):Lae(t)?HOt(s.refs).value:THe(t.value,s)}var u5s=(s,t,n,r)=>{const a={};for(const i of s){const l=Ri(t,i);l&&Qh(a,i,l._f)}return{criteriaMode:n,names:[...s],fields:a,shouldUseNativeValidation:r}},yZ=s=>Oh(s)?s:yEe(s)?s.source:Gp(s)?yEe(s.value)?s.value.source:s.value:s;const Axt="AsyncFunction";var h5s=s=>{if(!s||!s.validate)return!1;if(d1(s.validate))return s.validate.constructor.name===Axt;if(Gp(s.validate)){for(const t in s.validate)if(s.validate[t].constructor.name===Axt)return!0}return!1},m5s=s=>s.mount&&(s.required||!Oh(s.required)&&s.required!==!1||!Oh(s.min)||!Oh(s.max)||!Oh(s.maxLength)||!Oh(s.minLength)||s.pattern||s.validate);function Ext(s,t,n){const r=Ri(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=Ri(t,i),o=Ri(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 f5s=(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||MN.all))},p5s=(s,t,n)=>!s||!t||s===t||U4e(s).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),g5s=(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,x5s=(s,t)=>{const n=Ri(s,t);!WOt(n).length&&!(n!=null&&n.root)&&ox(s,t)};const y5s={mode:MN.onSubmit,reValidateMode:MN.onChange,shouldFocusError:!0},qze="form",v5s=(s,t)=>{for(const n in s)n in t||delete s[n];Object.assign(s,t)},e8t={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function b5s(s={}){let t={...y5s,...s},n={...Uf(e8t),isLoading:d1(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},a=Gp(t.defaultValues)||Gp(t.values)?Uf(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:Uf(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=Nce(t.mode),m=Nce(t.reValidateMode);const f={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={...f};let x={...g};const v=(...yt)=>yt.some(gs=>g[gs]||x[gs]),y={array:Nxt(),state:Nxt()};let b=0,w=0,S=t.criteriaMode===MN.all;const A=(yt,gs)=>Ss=>{clearTimeout(d[yt]),d[yt]=setTimeout(gs,Ss)},E=yt=>{clearTimeout(d[yt]),delete d[yt],delete c[yt]},I=yt=>{E(yt);const gs=`${yt}.`;for(const Ss of Object.keys(c))Ss.startsWith(gs)&&E(Ss)},P=async yt=>{if(!l.keepIsValid&&!t.disabled&&(v("isValid")||yt)){const gs=++b;let Ss;t.resolver?(Ss=ky((await le()).errors),gs===b&&R()):Ss=await J({fields:r,onlyCheckValid:!0,eventType:oP.VALID}),gs===b&&Ss!==n.isValid&&y.state.next({isValid:Ss})}},R=(yt,gs)=>{!t.disabled&&v("isValidating","validatingFields")&&((yt||o.mount).forEach(Ss=>{Ss&&(gs?Qh(n.validatingFields,Ss,gs):ox(n.validatingFields,Ss))}),y.state.next({validatingFields:n.validatingFields,isValidating:!ky(n.validatingFields)}))},D=()=>{n.dirtyFields=$M(a,i,void 0,r)},O=(yt,gs=[],Ss,Ds,Bt=!0,zt=!0)=>{if(Ds&&Ss&&!t.disabled){l.action=!0;const vs=Ri(r,yt);if(l.actionArrayLengths.has(yt)||l.actionArrayLengths.set(yt,Array.isArray(vs)?vs.length:0),zt&&Array.isArray(vs)){const Cn=Ss(vs,Ds.argA,Ds.argB);Bt&&Qh(r,yt,Cn)}const dn=Ri(n.errors,yt);if(zt&&Array.isArray(dn)){const Cn=dn.root,Rr=Ss(dn,Ds.argA,Ds.argB)||dn;Cn&&(Rr.root=Cn),Bt&&Qh(n.errors,yt,Rr),x5s(n.errors,yt)}const Ks=Ri(n.touchedFields,yt);if(v("touchedFields")&&zt&&Array.isArray(Ks)){const Cn=Ss(Ks,Ds.argA,Ds.argB);Bt&&Qh(n.touchedFields,yt,Cn)}v("dirtyFields")&&D(),y.state.next({name:yt,isDirty:ve(yt,gs),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Qh(i,yt,gs)},U=(yt,gs)=>{Qh(n.errors,yt,gs),n.errors={...n.errors},y.state.next({errors:n.errors})},W=yt=>{Object.keys(c).forEach(E),n.errors=yt,y.state.next({errors:n.errors,isValid:!1})},V=yt=>{const gs=xG(yt)?[yt]:O7(yt);let Ss=i,Ds=a;for(let Bt=0;Bt{if(!l.actionArrayLengths.size)return!1;const gs=xG(yt)?[yt]:O7(yt);let Ss=i,Ds="",Bt=-1,zt=0;for(let vs=0;vs=Ss.length)return Bt===-1?!1:vs===Bt?+dnBt&&+gs[Bt]{const Bt=Ri(r,yt);if(Bt){if(V(yt)||G(yt))return;const zt=Oh(Ri(i,yt)),vs=Ri(i,yt,Oh(Ss)?Ri(a,yt):Ss);Oh(vs)||Ds&&Ds.defaultChecked||gs?Qh(i,yt,gs?vs:Cxt(Bt._f)):be(yt,vs),l.mount&&!l.action&&(P(),zt&&n.isDirty&&v("isDirty")&&(ve()||(n.isDirty=!1,y.state.next({...n}))),s.shouldUnregister&&zt&&!Oh(Ri(i,yt))&&$ze(yt,o)&&(l.watch=!0))}},X=(yt,gs,Ss,Ds,Bt)=>{let zt=!1,vs=!1;const dn={name:yt};if(!t.disabled||Ds===!0){if(!Ss||Ds){const Ks=dw(Ri(a,yt),gs);v("isDirty")&&(vs=n.isDirty,n.isDirty=dn.isDirty=!Ks||ve(),zt=vs!==dn.isDirty),vs=!!Ri(n.dirtyFields,yt),Ks!==n.isDirty?v5s(n.dirtyFields,$M(a,i,void 0,r)):Ks?ox(n.dirtyFields,yt):Qh(n.dirtyFields,yt,!0),dn.dirtyFields=n.dirtyFields,zt=zt||v("dirtyFields")&&vs!==!Ks}if(Ss){const Ks=Ri(n.touchedFields,yt);Ks||(Qh(n.touchedFields,yt,Ss),dn.touchedFields=n.touchedFields,zt=zt||v("touchedFields")&&Ks!==Ss)}zt&&Bt&&y.state.next(dn)}return zt?dn:{}},ae=(yt,gs,Ss,Ds)=>{const Bt=Ri(n.errors,yt),zt=v("isValid")&&Uj(gs)&&n.isValid!==gs;if(t.delayError&&Ss?(c[yt]=A(yt,()=>U(yt,Ss)),c[yt](t.delayError)):(E(yt),Ss?Qh(n.errors,yt,Ss):ox(n.errors,yt),n.errors={...n.errors}),(Ss?!dw(Bt,Ss):Bt)||!ky(Ds)||zt){const vs={...Ds,...zt&&Uj(gs)?{isValid:gs}:{},errors:n.errors,name:yt};y.state.next(vs)}},le=async yt=>(R(yt,!0),await t.resolver(i,t.context,u5s(yt||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),re=async yt=>{const gs=w,{errors:Ss}=await le(yt);if(gs!==w)return Ss;if(R(yt),yt){for(const Ds of yt){const Bt=Ri(Ss,Ds);E(Ds);const zt=o.array.has(Ds)&&Gp(Bt)&&!Object.keys(Bt).some(Ks=>!Number.isNaN(Number(Ks))),vs=Ri(r,Ds),dn=Gp(vs)&&Object.keys(vs).some(Ks=>Ks!=="_f");zt?yxt(n.errors,{[Ds]:Bt},Ds):Bt!=null&&Bt.type||Bt!=null&&Bt.message||Array.isArray(Bt)||Gp(Bt)&&dn?Qh(n.errors,Ds,Bt):ox(n.errors,Ds)}n.errors={...n.errors}}else Object.keys(c).forEach(E),n.errors=Ss;return Ss},te=async({name:yt,eventType:gs})=>{if(s.validate){const Ss=await s.validate({formValues:i,formState:n,name:yt,eventType:gs});if(Gp(Ss))for(const Ds in Ss){const Bt=Ss[Ds];Bt&&Ve(`${qze}.${Ds}`,{message:mv(Bt.message)?Bt.message:"",type:Bt.type||oS.validate})}else mv(Ss)||!Ss?Ve(qze,{message:Ss||"",type:oS.validate}):ze(qze);return Ss}return!0},J=async({fields:yt,onlyCheckValid:gs,name:Ss,eventType:Ds,context:Bt={valid:!0,runRootValidation:!1}})=>{if(s.validate&&(Bt.runRootValidation=!0,!await te({name:Ss,eventType:Ds})&&(Bt.valid=!1,gs)))return Bt.valid;for(const zt in yt){const vs=yt[zt];if(vs){const{_f:dn,...Ks}=vs;if(dn){const Cn=o.array.has(dn.name),Rr=vs._f&&h5s(vs._f),ia=v("isValidating","validatingFields");Rr&&ia&&R([dn.name],!0);const Hs=await jxt(vs,o.disabled,i,S,t.shouldUseNativeValidation&&!gs,Cn);if(Rr&&ia&&R([dn.name]),Hs[dn.name]&&(Bt.valid=!1,gs)||(gs||(E(dn.name),Ri(Hs,dn.name)?Cn?yxt(n.errors,Hs,dn.name):Qh(n.errors,dn.name,Hs[dn.name]):ox(n.errors,dn.name)),s.shouldUseNativeValidation&&Hs[dn.name]))break}!ky(Ks)&&await J({context:Bt,onlyCheckValid:gs,fields:Ks,name:zt,eventType:Ds})}}return Bt.valid},ce=()=>{for(const yt of o.unMount){const gs=Ri(r,yt);gs&&(gs._f.refs?gs._f.refs.every(Ss=>!Uze(Ss)):!Uze(gs._f.ref))&&rt(yt)}o.unMount=new Set},ve=(yt,gs)=>(yt&&gs&&Qh(i,yt,gs),!dw(l.mount?i:a,a)),fe=(yt,gs,Ss)=>CHe(yt,o,{...l.mount?i:Oh(gs)||mv(yt)?a:gs},Ss,gs),ue=yt=>WOt(Ri(l.mount?i:a,yt,t.shouldUnregister?Ri(a,yt,[]):[])),be=(yt,gs,Ss={},Ds=!1,Bt=!1,zt=!1)=>{const vs=Ri(r,yt);let dn=gs;if(vs){const Ks=vs._f;Ks&&(!Ks.disabled&&Qh(i,yt,THe(gs,Ks)),dn=xEe(Ks.ref)&&cv(gs)?"":gs,YOt(Ks.ref)?[...Ks.ref.options].forEach(Cn=>Cn.selected=dn.includes(Cn.value)):Ks.refs?Lae(Ks.ref)?Ks.refs.forEach(Cn=>{(!Cn.defaultChecked||!Cn.disabled)&&(Array.isArray(dn)?Cn.checked=!!dn.find(Rr=>Rr===Cn.value):Cn.checked=dn===Cn.value||!!dn)}):Ks.refs.forEach(Cn=>Cn.checked=Cn.value===dn):gLe(Ks.ref)?Ks.ref.value="":(Ks.ref.value=dn,!Ks.ref.type&&!Bt&&!zt&&y.state.next({name:yt,values:Ds?i:Uf(i)})))}(Ss.shouldDirty||Ss.shouldTouch)&&X(yt,vs&&vs._f&&!vs._f.disabled&&(vs._f.valueAsNumber||vs._f.valueAsDate||vs._f.setValueAs)?THe(gs,vs._f):dn,Ss.shouldTouch,Ss.shouldDirty,!Bt),Ss.shouldValidate&&Se(yt,{delayError:Ss.delayError})},Ee=(yt,gs,Ss,Ds=!1,Bt=!1,zt=!1)=>{o.array.has(yt)&&y.array.next({name:yt,values:Ds?i:Uf(i)});for(const vs in gs){if(!gs.hasOwnProperty(vs))continue;const dn=gs[vs],Ks=yt+"."+vs,Cn=Ri(r,Ks);(o.array.has(yt)||Gp(dn)||Cn&&!Cn._f)&&!mI(dn)?Ee(Ks,dn,Ss,Ds,Bt,zt):be(Ks,dn,Ss,Ds,Bt,zt)}},ke=(yt,gs,Ss,Ds,Bt=!1)=>{const zt=Ri(r,yt),vs=o.array.has(yt),dn=Ds?gs:Uf(gs),Ks=Ri(i,yt),Cn=dw(Ks,dn);if(Cn||Qh(i,yt,dn),vs)y.array.next({name:yt,values:Ds?i:Uf(i)}),v("isDirty","dirtyFields")&&Ss.shouldDirty&&(D(),Bt||y.state.next({name:yt,dirtyFields:n.dirtyFields,isDirty:ve(yt,dn)}));else{const Rr=Array.isArray(dn)&&!dn.length||ky(dn),ia=!Cn&&!Bt;!zt||zt._f||cv(dn)||Rr?be(yt,dn,Ss,Ds,Bt,ia):Ee(yt,dn,Ss,Ds,Bt,ia)}if(!Cn&&!Bt){const Rr=$ze(yt,o),ia=Ds?i:Uf(i);if(y.state.next({...Rr&&n,name:l.mount||Rr?yt:void 0,values:ia}),!vs)for(const Hs of d5s(o.array,yt))y.state.next({name:Hs,values:ia})}},Ie=(yt,gs,Ss={})=>ke(yt,gs,Ss,!1),Fe=(yt,gs={})=>{const Ss=d1(yt)?yt(i):yt;if(!dw(i,Ss)){i={...i,...Ss};for(const Ds of o.mount)o5s(Ss,Ds)&&ke(Ds,Ri(Ss,Ds),gs,!0,!0);y.state.next({...n,name:void 0,type:void 0,...u?{values:i}:{}}),gs.shouldValidate&&P()}},Ne=async yt=>{l.mount=!0;const gs=yt.target;let Ss=gs.name,Ds=!0;const Bt=Ri(r,Ss),zt=vs=>{Ds=Number.isNaN(vs)||mI(vs)&&isNaN(vs.getTime())||dw(vs,Ri(i,Ss,vs))};if(Bt){let vs,dn;const Ks=gs.type?Cxt(Bt._f):kHe(yt),Cn=yt.type===oP.BLUR||yt.type===oP.FOCUS_OUT,Rr=!m5s(Bt._f)&&!s.validate&&!t.resolver&&!Ri(n.errors,Ss)&&!Bt._f.deps,ia=Rr||g5s(Cn,Ri(n.touchedFields,Ss),n.isSubmitted,m,h),Hs=$ze(Ss,o,Cn);if(Qh(i,Ss,Uf(Ks)),Cn){if(!gs||!gs.readOnly){Bt._f.onBlur&&Bt._f.onBlur(yt);const Wn=c[Ss];Wn&&Wn(0)}}else Bt._f.onChange&&Bt._f.onChange(yt);const Br=X(Ss,Ks,Cn),Ur=!ky(Br)||Hs;if(!Cn&&y.state.next({name:Ss,type:yt.type,...u?{values:Uf(i)}:{}}),ia)return(!Rr||!n.isValid)&&v("isValid")&&(t.mode==="onBlur"?Cn&&P():Cn||P()),Ur&&y.state.next({name:Ss,...Hs?{}:Br});if(!t.resolver&&s.validate&&await te({name:Ss,eventType:yt.type}),!Cn&&Hs&&y.state.next({...n}),t.resolver){const{errors:Wn}=await le([Ss]);if(R([Ss]),zt(Ks),!Ds){!ky(Br)&&y.state.next(Br);return}const Sn=Ext(n.errors,r,Ss),Fn=Ext(Wn,r,Sn.name||Ss);vs=Fn.error,Ss=Fn.name,dn=ky(Wn)}else R([Ss],!0),vs=(await jxt(Bt,o.disabled,i,S,t.shouldUseNativeValidation))[Ss],R([Ss]),zt(Ks),Ds&&(vs?dn=!1:v("isValid")&&(dn=await J({fields:r,onlyCheckValid:!0,name:Ss,eventType:yt.type})));Ds&&(Bt._f.deps&&(!Array.isArray(Bt._f.deps)||Bt._f.deps.length>0)&&Se(Bt._f.deps),ae(Ss,dn,vs,Br))}},Be=(yt,gs)=>{if(Ri(n.errors,gs)&&yt.focus)return yt.focus(),1},Se=async(yt,gs={})=>{let Ss,Ds;const Bt=U4e(yt);if(t.resolver){const zt=w,vs=await re(Oh(yt)?yt:Bt);if(Ss=ky(vs),Ds=yt?!Bt.some(dn=>Ri(vs,dn)):Ss,zt!==w)return Ds}else yt?(Ds=(await Promise.all(Bt.map(async zt=>{const vs=Ri(r,zt);return await J({fields:vs&&vs._f?{[zt]:vs}:vs,eventType:oP.TRIGGER})}))).every(Boolean),!(!Ds&&!n.isValid)&&P()):Ds=Ss=await J({fields:r,name:yt,eventType:oP.TRIGGER});if(gs.delayError&&t.delayError&&mv(yt)){const zt=Ri(n.errors,yt);zt?(ox(n.errors,yt),c[yt]=A(yt,()=>U(yt,zt)),c[yt](t.delayError)):E(yt)}if(gs.shouldTouch)for(const zt of yt?Bt:o.mount)!o.array.has(zt)&&Qh(n.touchedFields,zt,!0);return y.state.next({...!mv(yt)||v("isValid")&&Ss!==n.isValid?{}:{name:yt},...t.resolver||!yt?{isValid:Ss}:{},...gs.shouldTouch&&v("touchedFields")?{touchedFields:n.touchedFields}:{},errors:n.errors}),gs.shouldFocus&&!Ds&&cee(r,Be,yt?Bt:o.mount),Ds},Ae=(yt,gs)=>{let Ss={...l.mount?i:a};return gs&&(Ss=KOt(gs.dirtyFields?n.dirtyFields:n.touchedFields,Ss)),Oh(yt)?Ss:mv(yt)?Ri(Ss,yt):yt.map(Ds=>Ri(Ss,Ds))},Ce=yt=>Oh(yt)?{...n.errors}:mv(yt)?Ri(n.errors,yt):yt.map(gs=>Ri(n.errors,gs)),qe=(yt,gs)=>{const Ss=gs||n,Ds=Ri(Ss.errors,yt);return{invalid:!!Ds,isDirty:!!Ri(Ss.dirtyFields,yt),error:Ds,isValidating:!!Ri(Ss.validatingFields,yt),isTouched:!!Ri(Ss.touchedFields,yt)}},ze=yt=>{const gs=yt?U4e(yt):void 0;gs?gs.forEach(Ss=>{I(Ss),ox(n.errors,Ss),y.state.next({name:Ss,errors:n.errors})}):(Object.keys(c).forEach(E),n.errors={},y.state.next({errors:n.errors}))},Ve=(yt,gs,Ss)=>{E(yt);const Ds=(Ri(r,yt,{_f:{}})._f||{}).ref,Bt=Ri(n.errors,yt)||{},{ref:zt,message:vs,type:dn,types:Ks,...Cn}=Bt;Qh(n.errors,yt,{...Cn,...gs,ref:Ds}),y.state.next({name:yt,errors:n.errors,isValid:!1}),Ss&&Ss.shouldFocus&&Ds&&Ds.focus&&Ds.focus()},ht=(yt,gs)=>{if(d1(yt)){u++;const{unsubscribe:Ss}=y.state.subscribe({next:Bt=>"values"in Bt&&yt(Bt.values||fe(void 0,gs),Bt)});let Ds=!1;return{unsubscribe:()=>{Ds||(Ds=!0,u--,Ss())}}}return fe(yt,gs,!0)},Qe=yt=>{var gs;const Ss=!!(!((gs=yt.formState)===null||gs===void 0)&&gs.values);Ss&&u++;const{unsubscribe:Ds}=y.state.subscribe({next:zt=>{if(p5s(yt.name,zt.name,yt.exact)&&f5s(zt,yt.formState||g,Ft,yt.reRenderRoot)){const vs={...i};yt.callback({values:vs,...n,...zt,defaultValues:a})}}});if(!Ss)return Ds;let Bt=!1;return()=>{Bt||(Bt=!0,u--,Ds())}},at=yt=>(l.mount=!0,x={...x,...yt.formState},Qe({...yt,formState:{...f,...yt.formState}})),rt=(yt,gs={})=>{for(const Ss of yt?U4e(yt):o.mount)o.mount.delete(Ss),o.array.delete(Ss),o.disabled.delete(Ss),gs.keepValue||(ox(r,Ss),ox(i,Ss)),gs.keepError||(I(Ss),ox(n.errors,Ss)),!gs.keepDirty&&ox(n.dirtyFields,Ss),!gs.keepTouched&&ox(n.touchedFields,Ss),!gs.keepIsValidating&&ox(n.validatingFields,Ss),!t.shouldUnregister&&!gs.keepDefaultValue&&ox(a,Ss);u&&y.state.next({values:Uf(i)}),y.state.next({...n,...gs.keepDirty?{}:{isDirty:ve()},...gs.keepIsValidating?{}:{isValidating:!ky(n.validatingFields)}}),!gs.keepIsValid&&P()},Ke=({disabled:yt,name:gs})=>{if(Uj(yt)&&l.mount||yt||o.disabled.has(gs)){const Bt=o.disabled.has(gs)!==!!yt;yt?o.disabled.add(gs):o.disabled.delete(gs),Bt&&l.mount&&!l.action&&P()}},Je=(yt,gs={})=>{let Ss=Ri(r,yt);const Ds=Uj(gs.disabled)||Uj(t.disabled),Bt=!o.registerName.has(yt)&&Ss&&Ss._f&&!Ss._f.mount;return Qh(r,yt,{...Ss||{},_f:{...Ss&&Ss._f?Ss._f:{ref:{name:yt}},name:yt,mount:!0,...gs}}),o.mount.add(yt),Ss&&!Bt?Ke({disabled:Uj(gs.disabled)?gs.disabled:t.disabled,name:yt}):Z(yt,!0,gs.value),{...Ds?{disabled:gs.disabled||t.disabled}:{},...t.progressive?{required:!!gs.required,min:yZ(gs.min),max:yZ(gs.max),minLength:yZ(gs.minLength),maxLength:yZ(gs.maxLength),pattern:yZ(gs.pattern)}:{},name:yt,onChange:Ne,onBlur:Ne,ref:zt=>{if(zt){o.registerName.add(yt),Je(yt,gs),o.registerName.delete(yt),Ss=Ri(r,yt);const vs=Oh(zt.value)&&zt.querySelectorAll&&zt.querySelectorAll("input,select,textarea")[0]||zt,dn=l5s(vs),Ks=Ss._f.refs||[];if(dn?Ks.find(Rr=>Rr===vs):vs===Ss._f.ref)return;const Cn={...Ss._f};dn?(Cn.refs=[...Ks.filter(Uze),vs,...Array.isArray(Ri(a,yt))?[{}]:[]],Cn.ref={type:vs.type,name:yt}):(Cn.ref=vs,delete Cn.refs),Qh(r,yt,{_f:Cn}),Z(yt,!1,void 0,vs)}else Ss=Ri(r,yt,{}),Ss._f&&(Ss._f.mount=!1),(t.shouldUnregister||gs.shouldUnregister)&&!($Ot(o.array,yt)&&l.action)&&o.unMount.add(yt)}}},ft=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&cee(r,Be,o.mount),gt=yt=>{Uj(yt)&&(y.state.next({disabled:yt}),cee(r,(gs,Ss)=>{const Ds=Ri(r,Ss);Ds&&(gs.disabled=Ds._f.disabled||yt,Array.isArray(Ds._f.refs)&&Ds._f.refs.forEach(Bt=>{Bt.disabled=Ds._f.disabled||yt}))},0))},es=(yt,gs)=>async Ss=>{let Ds,Bt;Ss&&(Ss.preventDefault&&Ss.preventDefault(),Ss.persist&&Ss.persist());let zt=Uf(i);if(y.state.next({isSubmitting:!0}),t.resolver){const vs=w,{errors:dn,values:Ks}=await le();if(vs!==w)return;R(),Object.keys(c).forEach(E),n.errors=dn,zt=Uf(Ks)}else await J({fields:r,eventType:oP.SUBMIT}),ox(n.errors,UOt);if(o.disabled.size)for(const vs of o.disabled)ox(zt,vs);if(ky(n.errors)){y.state.next({errors:{}});try{Ds=await yt(zt,Ss)}catch(vs){Bt=vs}}else gs&&await gs({...n.errors},Ss),ft(),setTimeout(ft);if(y.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:ky(n.errors)&&!Bt,submitCount:n.submitCount+1,errors:n.errors}),Bt)throw Bt;return Ds},Ht=(yt,gs={})=>{Ri(r,yt)&&(ox(n.validatingFields,yt),Oh(gs.defaultValue)?Ie(yt,Uf(Ri(a,yt))):(Ie(yt,gs.defaultValue),Qh(a,yt,Uf(gs.defaultValue))),gs.keepTouched||ox(n.touchedFields,yt),gs.keepDirty||(ox(n.dirtyFields,yt),n.isDirty=gs.defaultValue?ve(yt,Uf(Ri(a,yt))):ve()),gs.keepError||(E(yt),ox(n.errors,yt),P()),y.state.next({...n,isValidating:!ky(n.validatingFields)}))},as=(yt,gs={})=>{w++;const Ss=yt?Uf(yt):a,Ds=Uf(Ss),Bt=ky(yt),zt=Ds,vs=r;if(Object.keys(c).forEach(E),gs.keepDefaultValues||(a=Ss),!gs.keepValues){if(gs.keepDirtyValues){const dn=new Set([...o.mount,...ZOt($M(a,i,void 0,vs),n.dirtyFields)]);for(const Ks of dn){const Cn=Ri(n.dirtyFields,Ks),Rr=Ri(i,Ks),ia=Ri(zt,Ks);Cn&&!Oh(Rr)?Qh(zt,Ks,Rr):!Cn&&!Oh(ia)&&Ie(Ks,ia)}}else{if(xLe&&Oh(yt))for(const dn of o.mount){const Ks=Ri(r,dn);if(Ks&&Ks._f){const Cn=Array.isArray(Ks._f.refs)?Ks._f.refs[0]:Ks._f.ref;if(xEe(Cn)){const Rr=Cn.closest("form");if(Rr){Rr.reset();break}}}}if(gs.keepFieldsRef)for(const dn of o.mount)Ie(dn,Ri(zt,dn));else r={}}if(t.shouldUnregister){if(i=gs.keepDefaultValues?Uf(a):{},gs.keepFieldsRef)for(const dn of o.mount)Qh(i,dn,Ri(zt,dn))}else i=Uf(zt);y.array.next({values:{...zt}}),y.state.next({name:void 0,type:void 0,values:{...zt}})}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&&!ky(zt),l.watch=!!t.shouldUnregister,l.keepIsValid=!!gs.keepIsValid,l.action=!1,l.actionArrayLengths.clear(),gs.keepErrors||(n.errors={}),y.state.next({submitCount:gs.keepSubmitCount?n.submitCount:0,isDirty:Bt?!1:gs.keepDirty?n.isDirty:gs.keepValues?ve():!!(gs.keepDefaultValues&&!dw(yt,a)),isSubmitted:gs.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:Bt?{}:gs.keepDirtyValues?gs.keepDefaultValues&&i?$M(a,i,void 0,vs):n.dirtyFields:gs.keepDefaultValues&&yt?$M(a,yt,void 0,vs):gs.keepDirty?n.dirtyFields:gs.keepValues?$M(a,i,void 0,vs):{},touchedFields:gs.keepTouched?n.touchedFields:{},...!gs.keepIsValidating&&(n.isValidating||!ky(n.validatingFields))?{validatingFields:{},isValidating:!1}:null,errors:gs.keepErrors?n.errors:{},isSubmitSuccessful:gs.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:a})},bs=(yt,gs)=>as(d1(yt)?yt(i):yt,{...t.resetOptions,...gs}),Ut=(yt,gs={})=>{const Ss=Ri(r,yt),Ds=Ss&&Ss._f;if(Ds){const Bt=Ds.refs?Ds.refs[0]:Ds.ref;Bt.focus&&setTimeout(()=>{Bt.focus(),gs.shouldSelect&&d1(Bt.select)&&Bt.select()})}},Ft=yt=>{const{name:gs,type:Ss,values:Ds,...Bt}=yt;n={...n,...Bt}};y.state.subscribe({next:Ft});const zs={control:{register:Je,unregister:rt,getFieldState:qe,handleSubmit:es,setError:Ve,_subscribe:Qe,_runSchema:le,_updateIsValidating:R,_focusError:ft,_getWatch:fe,_getDirty:ve,_setValid:P,_setFieldArray:O,_setDisabledField:Ke,_setErrors:W,_getFieldArray:ue,_reset:as,_resetDefaultValues:()=>d1(t.defaultValues)&&t.defaultValues().then(yt=>{bs(yt,t.resetOptions),y.state.next({isLoading:!1})}),_removeUnmounted:ce,_disableForm:gt,_subjects:y,_proxyFormState:g,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(yt){l=yt},get _defaultValues(){return a},get _names(){return o},set _names(yt){o=yt},get _formState(){return n},get _options(){return t},set _options(yt){t={...t,...yt},h=Nce(t.mode),m=Nce(t.reValidateMode),S=t.criteriaMode===MN.all}},subscribe:at,trigger:Se,register:Je,handleSubmit:es,watch:ht,setValue:Ie,setValues:Fe,getValues:Ae,getErrors:Ce,reset:bs,resetField:Ht,resetDefaultValues:(yt,gs={})=>{if(a=Uf(yt),!gs.keepDirty){const Ss=$M(a,i,void 0,r);n.dirtyFields=Ss,n.isDirty=!ky(Ss)}gs.keepIsValid||P(),y.state.next({...n,defaultValues:a})},clearErrors:ze,unregister:rt,setError:Ve,setFocus:Ut,getFieldState:qe};return{...zs,formControl:zs}}function yLe(s={}){const t=Kt.useRef(void 0),n=Kt.useRef(void 0),r=Kt.useRef(s.formControl),[a,i]=Kt.useState(()=>({...Uf(e8t),isLoading:d1(s.defaultValues),errors:s.errors||{},disabled:s.disabled||!1,defaultValues:d1(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:a},s.defaultValues&&!d1(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:u,...h}=b5s(s);t.current={...h,formState:a}}const l=t.current.control;l._options=s;const o=()=>({...l._formState,defaultValues:l._defaultValues}),{resyncIfNeeded:c,snapshot:d}=Get(o);return Het(()=>{c(!0,o,i);const u=l._subscribe({formState:l._proxyFormState,callback:()=>i({...l._formState,defaultValues:l._defaultValues}),reRenderRoot:!0});return i(h=>({...h,isReady:!0})),l._formState.isReady=!0,()=>{u(),d(!0,o)}},[l,c,d]),Kt.useEffect(()=>l._disableForm(s.disabled),[l,s.disabled]),Kt.useEffect(()=>{s.mode&&(l._options.mode=s.mode),s.reValidateMode&&(l._options.reValidateMode=s.reValidateMode)},[l,s.mode,s.reValidateMode]),Kt.useEffect(()=>{s.errors&&(l._setErrors(s.errors),l._focusError())},[l,s.errors]),Kt.useEffect(()=>{s.shouldUnregister&&l._subjects.state.next({values:l._getWatch()})},[l,s.shouldUnregister]),Kt.useEffect(()=>{if(l._proxyFormState.isDirty){const u=l._getDirty();u!==a.isDirty&&l._subjects.state.next({isDirty:u})}},[l,a.isDirty]),Kt.useEffect(()=>{var u;s.values&&!dw(s.values,n.current)?(l._reset(s.values,{keepFieldsRef:!0,...l._options.resetOptions}),!((u=l._options.resetOptions)===null||u===void 0)&&u.keepIsValid||l._setValid(),n.current=s.values,i(h=>({...h}))):l._resetDefaultValues()},[l,s.values]),Kt.useEffect(()=>{l._state.mount||(l._setValid(),l._state.mount=!0),l._state.watch&&(l._state.watch=!1,l._subjects.state.next({...l._formState})),l._removeUnmounted()}),t.current.formState=Kt.useMemo(()=>qOt(a,l),[l,a]),t.current}const Txt=(s,t,n)=>{if(s&&"reportValidity"in s){const r=Ri(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},t8t=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?Txt(r.ref,n,s):r.refs&&r.refs.forEach(a=>Txt(a,n,s))}},_5s=(s,t)=>{t.shouldUseNativeValidation&&t8t(s,t);const n={};for(const r in s){const a=Ri(t.fields,r),i=Object.assign(s[r]||{},{ref:a&&a.ref});if(w5s(t.names||Object.keys(s),r)){const l=Object.assign({},Ri(n,r));Qh(l,"root",i),Qh(n,r,l)}else Qh(n,r,i)}return n},w5s=(s,t)=>s.some(n=>n.startsWith(t+"."));var j5s=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]=VOt(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},vLe=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&&t8t({},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:_5s(j5s(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};function MHe(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 Mxt(s,t="|"){return s.map(n=>o8t(n)).join(t)}function PHe(s,t){return typeof t=="bigint"?t.toString():t}class N5s{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 Yet(s){return new N5s(s)}function k5s(s){return s==null}function Zet(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function S5s(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}):r8t(s,i,r?r(l.value,i):l.value))}}function C5s(s,t){for(const n of Reflect.ownKeys(t)){const r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?n8t(s,n,()=>t[n]):r8t(s,n,r.value))}}function Hj(...s){const t={};for(const n of s){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function A5s(s){return JSON.stringify(s)}function E5s(s){return s.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const a8t="captureStackTrace"in Error?Error.captureStackTrace:(...s)=>{};function vEe(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const T5s=Yet(()=>{var s;if(V4.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 Kte(s){if(vEe(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(vEe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function i8t(s){return Kte(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const M5s=new Set(["string","number","symbol"]);function yG(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function e6(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 Ml(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 o8t(s){return typeof s=="bigint"?s.toString()+"n":typeof s=="string"?`"${s}"`:`${s}`}function P5s(s){return Object.keys(s).filter(t=>s[t]._zod.optin!==void 0&&s[t]._zod.optout==="optional")}const l8t={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]},I5s={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function L5s(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 z7(i,s,bLe(s,t)),e6(s,Hj(n,{shape:i,checks:[]}))}function bLe(s,t){var a;const n=cT(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 R5s(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(bLe(s,t)),l={};return z7(l,s,Reflect.ownKeys(cT(s)).filter(o=>!i.has(o))),e6(s,Hj(n,{shape:l,checks:[]}))}function D5s(s,t){if(!Kte(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=cT(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 e6(s,Hj(s._zod.def,{shape:c8t(s,t)}))}function c8t(s,t){const n={};return z7(n,s,Reflect.ownKeys(cT(s))),C5s(n,t),n}function F5s(s,t){if(!Kte(t))throw new Error("Invalid input to safeExtend: expected a plain object");return e6(s,Hj(s._zod.def,{shape:c8t(s,t)}))}function O5s(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={};z7(n,s,Reflect.ownKeys(cT(s))),z7(n,t,Reflect.ownKeys(cT(t)));const r=Hj(s._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return e6(s,r)}function Pxt(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(bLe(t,n)):void 0,c={};return z7(c,t,Reflect.ownKeys(cT(t)),s&&((d,u)=>o&&!o.has(u)?d:new s({type:"optional",innerType:d}))),e6(t,Hj(t._zod.def,{shape:c,checks:[]}))}function z5s(s,t,n){const r=n?new Set(bLe(t,n)):void 0,a={};return z7(a,t,Reflect.ownKeys(cT(t)),(i,l)=>r&&!r.has(l)?i:new s({type:"nonoptional",innerType:i})),e6(t,Hj(t._zod.def,{shape:a}))}function gE(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 vZ(s){return typeof s=="string"?s:s==null?void 0:s.message}function Ixt(s,t,n){var r;for(let a=t;as;return t[K5s]=!0,t}var Lxt;const Hze={value:void 0,enumerable:!1};let Rxt="captureStackTrace"in Error?Error:null;function Z5s(s){const t=Rxt;if(t){const n=t.stackTraceLimit;if(typeof n=="number"){try{t.stackTraceLimit=0}catch{return Rxt=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{Hze.value=new i(f);try{Object.defineProperty(m,"_zod",Hze)}finally{Hze.value=void 0}}if(m._zod.traits.add(s),t(m,f),o){const x=Object.getPrototypeOf(m),v=m._zod.constr.prototype;let y=x;for(;y&&y!==v;)y=Object.getPrototypeOf(y);const b=y??x;o.has(b)||(o.add(b),q5s(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 v;const f=r!=null&&r.Parent?Z5s(u):this;c(f,m);const g=f._zod.deferred;if(g){for(const y of g)y();f._zod.deferred=void 0}const x=(v=globalThis.__zod_globalConfig)==null?void 0:v.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 n7 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class m8t extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Lxt=globalThis).__zod_globalConfig??(Lxt.__zod_globalConfig={});const V4=globalThis.__zod_globalConfig;function t6(s){return s&&Object.assign(V4,s),V4}function X5s(){const s=this._zod;return s.message??(s.message=JSON.stringify(s.def,PHe,2)),s.message}function Q5s(s){this._zod.message=s}const J5s={get:X5s,set:Q5s,enumerable:!0,configurable:!0},Gze={value:void 0,enumerable:!1},Dxt=new WeakSet([Object.prototype,Error.prototype]),e4s=(s,t)=>{s.name="$ZodError",Gze.value=t,Object.defineProperty(s,"issues",Gze),Gze.value=void 0,Object.defineProperty(s,"message",J5s);const n=Object.getPrototypeOf(s);Dxt.has(n)||(Dxt.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})}}))},t4s=Ma("$ZodError",e4s);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 n4s(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 r4s(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 n7;if(o.issues.length){const c=new((i==null?void 0:i.Err)??s)(o.issues.map(d=>XW(d,l,t6())));throw a8t(c,(i==null?void 0:i.callee)??t),c}return o.value};return t},ett=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=>XW(d,l,t6())));throw a8t(c,(i==null?void 0:i.callee)??t),c}return o.value};return t},ttt=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 n7;return i.issues.length?f8t(s,i.issues,a):{success:!0,data:i.value}};function f8t(s,t,n){let r;return{success:!1,get error(){return r||(r=new s(t.map(a=>XW(a,n,t6()))),t=void 0,n=void 0),r},set error(a){r=a,t=void 0,n=void 0}}}const stt=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?f8t(s,i.issues,a):{success:!0,data:i.value}},a4s=Symbol.for("zod.compile.invalid"),i4s=Symbol.for("zod.compile.fallback"),o4s=(s,t,n)=>{const r=s._zod.bag.validator;if(r!==void 0){if(r(t)!==a4s)return!0;if(r.definite===!0&&n===void 0)return!1}return l4s(s,t,n)};function l4s(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[i4s]=!0,i=a({value:t,issues:[]},r)):i=s._zod.run({value:t,issues:[]},r),i instanceof Promise)throw new n7;return i.issues.length===0}const c4s=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},d4s=s=>{const t=Jet(s),n=(r,a,i,l)=>{const o=i?{...i,direction:"backward"}:{direction:"backward"};return t(r,a,o,_Le(n,l))};return n},u4s=s=>{const t=Jet(s),n=(r,a,i,l)=>t(r,a,i,_Le(n,l));return n},h4s=s=>{const t=ett(s),n=async(r,a,i,l)=>{const o=i?{...i,direction:"backward"}:{direction:"backward"};return await t(r,a,o,_Le(n,l))};return n},m4s=s=>{const t=ett(s),n=async(r,a,i,l)=>await t(r,a,i,_Le(n,l));return n},f4s=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return ttt(s)(t,n,a)},p4s=s=>(t,n,r)=>ttt(s)(t,n,r),g4s=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return stt(s)(t,n,a)},x4s=s=>async(t,n,r)=>stt(s)(t,n,r),y4s=/^[cC][0-9a-z]{6,}$/,v4s=/^[0-9a-z]+$/,b4s=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,_4s=/^[0-9a-vA-V]{20}$/,w4s=/^[A-Za-z0-9]{27}$/,j4s=/^[a-zA-Z0-9_-]{21}$/;function N4s(s){return new RegExp(`^[a-zA-Z0-9_-]{${s}}$`)}const k4s=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,S4s=/^([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})$/,Fxt=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)$/,C4s=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,A4s="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function E4s(){return new RegExp(A4s,"u")}const T4s=/^(?:(?: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])$/,M4s=/^(([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}|:))$/,P4s=/^((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])$/,I4s=/^(([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])$/,L4s=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,R4s=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,D4s=/^https?$/,F4s=/^\+[1-9]\d{6,14}$/,p8t="(?:(?:\\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 O4s(s){return new RegExp(`^${s}$`)}const z4s=O4s(p8t);function IHe(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 B4s(s){return new RegExp(`^${IHe(s)}$`)}function $4s(s){const t=["Z"];s.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${IHe({precision:s.precision,seconds:!0})}(?:${t.join("|")})`,r=s.local?`${n}|${IHe({precision:s.precision})}`:n;return new RegExp(`^${p8t}T(?:${r})$`)}const U4s=/^[\s\S]{0,}$/,q4s=/^-?\d+(?:\.\d+)?$/,V4s=/^(?:true|false)$/i,H4s=/^[^A-Z]*$/,G4s=/^[^a-z]*$/,zw=Ma("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),ntt=s=>{const t=s.value;return!k5s(t)&&t.length!==void 0},bEe={number:"number",bigint:"bigint",object:"date"},g8t=Ma("$ZodCheckLessThan",(s,t)=>{zw.init(s,t);const n=bEe[typeof t.value];s._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value{zw.init(s,t);const n=bEe[typeof t.value];s._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:bEe[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})}}),W4s=Ma("$ZodCheckMultipleOf",(s,t)=>{zw.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):S5s(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})}}),K4s=Ma("$ZodCheckNumberFormat",(s,t)=>{var l;zw.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]=l8t[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})}}),Y4s=Ma("$ZodCheckMaxLength",(s,t)=>{var n;zw.init(s,t),(n=s._zod.def).when??(n.when=ntt),s._zod.check=r=>{const a=r.value,i=a.length;if((typeof a=="string"&&i>t.maximum?Xet(a):i)<=t.maximum)return;const o=Qet(a);r.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),Z4s=Ma("$ZodCheckMinLength",(s,t)=>{var n;zw.init(s,t),(n=s._zod.def).when??(n.when=ntt),s._zod.check=r=>{const a=r.value,i=a.length;if((typeof a=="string"&&i>=t.minimum&&i=t.minimum)return;const o=Qet(a);r.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),X4s=Ma("$ZodCheckLengthEquals",(s,t)=>{var n;zw.init(s,t),(n=s._zod.def).when??(n.when=ntt),s._zod.check=r=>{const a=r.value,i=a.length,l=typeof a=="string"&&i>=t.length&&i<=t.length*2?Xet(a):i;if(l===t.length)return;const o=Qet(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})}}),wLe=Ma("$ZodCheckStringFormat",(s,t)=>{var n,r;zw.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=()=>{})}),Q4s=Ma("$ZodCheckRegex",(s,t)=>{wLe.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})}}),J4s=Ma("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=H4s),wLe.init(s,t)}),e3s=Ma("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=G4s),wLe.init(s,t)}),t3s=Ma("$ZodCheckIncludes",(s,t)=>{zw.init(s,t);const n=yG(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)=>{zw.init(s,t);const n=new RegExp(`^${yG(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})}}),n3s=Ma("$ZodCheckEndsWith",(s,t)=>{zw.init(s,t);const n=new RegExp(`.*${yG(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})}}),r3s=Ma("$ZodCheckOverwrite",(s,t)=>{zw.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class a3s{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 i3s={major:4,minor:6,patch:5},Ex=Ma("$ZodType",(s,t)=>{var i;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=i3s;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=gE(c),m;for(const f of d){if(f._zod.def.when){if(B5s(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 n7;if(m||x instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await x,c.issues.length!==g&&(Ixt(c.issues,g,s),h||(h=gE(c,g)))});else{if(c.issues.length===g)continue;Ixt(c.issues,g,s),h||(h=gE(c,g))}}return m?m.then(()=>c):c},o=(c,d,u)=>{if(gE(c))return c.aborted=!0,c;const h=l(d,a,u);if(h instanceof Promise){if(u.async===!1)throw new n7;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 n7;return u.then(h=>l(h,a,d))}return l(u,a,d)}}},{get"~standard"(){return u8t(this,"~standard",v8t(this))},set"~standard"(s){wL(this,"~standard",s)}}),y8t=(s,t)=>s.issues.length?{issues:s.issues.map(n=>XW(n,t,t6()))}:{value:s.value};async function o3s(s,t){const n={async:!0};return y8t(await s._zod.run({value:t,issues:[]},n),n)}function v8t(s){return{validate:t=>{const n={async:!1};try{const r=s._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return y8t(r,n)}catch{}return o3s(s,t)},vendor:"zod",version:1}}const rtt=Ma("$ZodString",(s,t)=>{Ex.init(s,t),s._zod.pattern=t.pattern??U4s,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}}),eg=Ma("$ZodStringFormat",(s,t)=>{wLe.init(s,t),rtt.init(s,t)}),l3s=Ma("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=S4s),eg.init(s,t)}),c3s=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=Fxt(r))}else t.pattern??(t.pattern=Fxt());eg.init(s,t)}),d3s=Ma("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=C4s),eg.init(s,t)}),b8t=1,_Ee=2;function _8t(s){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(s):(new URL(s),!0)}catch{return!1}}function u3s(s,t){return!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t)?_8t(s)||_Ee:h3s(s,t)}function h3s(s,t){var n;if(!t.normalize&&((n=t.protocol)==null?void 0:n.source)===D4s.source&&!/^https?:\/\//i.test(s))return b8t;try{if(typeof URL<"u"){const r=URL;if(typeof r.parse=="function")return r.parse(s)??_Ee}return new URL(s)}catch{return _Ee}}const m3s=/[\t\n\r]/g;function Oxt(s){return s.replace(m3s,"")}function f3s(s,t){return t.lastIndex=0,t.test(s.hostname)}function p3s(s,t){return t.lastIndex=0,t.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)}const g3s=Ma("$ZodURL",(s,t)=>{eg.init(s,t),s._zod.check=n=>{try{const r=n.value.trim(),a=u3s(r,t);if(a===b8t){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:s,continue:!t.abort});return}if(a===_Ee){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:s,continue:!t.abort});return}if(a===!0){n.value=Oxt(r);return}t.hostname&&!f3s(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&&!p3s(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:Oxt(r);return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:s,continue:!t.abort})}}}),x3s=Ma("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=E4s()),eg.init(s,t)}),y3s=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?j4s:N4s(t.length)),eg.init(s,t)}),v3s=Ma("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=y4s),eg.init(s,t)}),b3s=Ma("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=v4s),eg.init(s,t)}),_3s=Ma("$ZodULID",(s,t)=>{t.pattern??(t.pattern=b4s),eg.init(s,t)}),w3s=Ma("$ZodXID",(s,t)=>{t.pattern??(t.pattern=_4s),eg.init(s,t)}),j3s=Ma("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=w4s),eg.init(s,t)}),N3s=Ma("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=$4s(t)),eg.init(s,t)}),k3s=Ma("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=z4s),eg.init(s,t)}),S3s=Ma("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=B4s(t)),eg.init(s,t)}),C3s=Ma("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=k4s),eg.init(s,t)}),A3s=Ma("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=T4s),eg.init(s,t)}),E3s=/^[0-9a-fA-F:.]+$/;function w8t(s){return E3s.test(s)?_8t(`http://[${s}]`):!1}const T3s=Ma("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=M4s),eg.init(s,t),s._zod.check=n=>{w8t(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:s,continue:!t.abort})}}),M3s=Ma("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=P4s),eg.init(s,t)});function P3s(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:w8t(n)}const I3s=Ma("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=I4s),eg.init(s,t),s._zod.check=n=>{P3s(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:s,continue:!t.abort})}});function j8t(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const N8t=/^[0-9a-zA-Z+/]*={0,2}$/,L3s=Ma("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=N8t),eg.init(s,t),s._zod.check=n=>{j8t(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}}),att=/^[A-Za-z0-9_-]*$/;function R3s(s){if(!att.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return j8t(n)}const D3s=Ma("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=att),eg.init(s,t),s._zod.check=n=>{R3s(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),F3s=Ma("$ZodE164",(s,t)=>{t.pattern??(t.pattern=F4s),eg.init(s,t)});function O3s(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 z3s=Ma("$ZodJWT",(s,t)=>{eg.init(s,t),s._zod.check=n=>{O3s(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),k8t=Ma("$ZodNumber",(s,t)=>{Ex.init(s,t),s._zod.pattern=q4s,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}}),B3s=Ma("$ZodNumberFormat",(s,t)=>{K4s.init(s,t),k8t.init(s,t)}),$3s=Ma("$ZodBoolean",(s,t)=>{Ex.init(s,t),s._zod.pattern=V4s,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}}),U3s=Ma("$ZodUnknown",(s,t)=>{Ex.init(s,t),s._zod.parse=n=>n}),q3s=Ma("$ZodNever",(s,t)=>{Ex.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function zxt(s,t,n){s.issues.length&&t.issues.push(...d8t(n,s.issues)),t.value[n]=s.value}const V3s=Ma("$ZodArray",(s,t)=>{Ex.init(s,t);const n=V4.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;czxt(h,r,c)));else if(zxt(u,r,c),o&&u.issues.length!==0&&gE(u))break}return l.length?Promise.all(l).then(()=>r):r}});function wEe(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(...d8t(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 H3s=[];function S8t(s){var l,o,c,d;const t=Object.keys(s.shape),n=Object.getOwnPropertySymbols(s.shape),r=n.length?n:H3s,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=P5s(s.shape);return{...s,allKeys:a,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}}function C8t(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(gE(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(v=>wEe(v,n,g,t,h,m))):wEe(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 G3s=Ma("$ZodObject",(s,t)=>{Ex.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=Yet(()=>S8t(t));xm(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)||LB(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=vEe,l=t.catchall;let o;const c=V4.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 v of o.allKeys){if(g&&d.issues.length!==x){if(gE(d,x))break;x=d.issues.length}if(v==="__proto__")continue;const y=f[v],b=y._zod.optin,w=y._zod.optout,S=y._zod.run({value:h[v],issues:[]},u);S instanceof Promise?m.push(S.then(A=>wEe(A,d,v,h,b,w))):wEe(S,d,v,h,b,w)}return l?C8t(m,h,d,u,a.value,s,g===!0):m.length?Promise.all(m).then(()=>d):d}}),W3s=Ma("$ZodObjectJIT",(s,t)=>{G3s.init(s,t);const n=s._zod.parse,r=Yet(()=>S8t(t)),a=V4.memoizer,i=f=>{var A,E;const g=r.value,x=g.symbolKeys,v=new a3s(["payload","ctx"],{shape:f,inst:s,memo:a,syms:x}),y=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; }`;v.write("const input = payload.value;");const w=Object.create(null);let S=0;for(const I of g.allKeys)w[I]=`key_${S++}`;v.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)}]`:A5s(I),D=`${R} in input`,O=f[I],U=(A=O==null?void 0:O._zod)==null?void 0:A.optin,W=U!==void 0,V=((E=O==null?void 0:O._zod)==null?void 0:E.optout)==="optional";if(v.write(`const ${P} = ${y(R)};`),W&&V){const G=U==="optional"?`${P}_present`:`${P}.value !== undefined || ${P}_present`;v.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?(v.write(` if (${P}.issues.length) {${b(P,R)} } `),U==="defaulted"?v.write(`newResult[${R}] = ${P}.value;`):v.write(` if (${P}.value !== undefined || ${D}) { newResult[${R}] = ${P}.value; } `)):v.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 v.write("payload.value = newResult;"),v.write("return payload;"),v.compile()};let l;const o=vEe,c=!V4.jitless,u=c&&T5s.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?C8t([],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 Bxt(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=>!gE(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=>XW(l,r,t6())))}),t)}const K3s=Ma("$ZodUnion",(s,t)=>{Ex.init(s,t),xm(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),xm(s,"optout",r=>r.def.options.some(a=>a._zod.optout==="optional")?"optional":void 0),xm(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)))}),xm(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=>Zet(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=>Bxt(o,r,s,a)):Bxt(l,r,s,a)}}),Y3s=Ma("$ZodIntersection",(s,t)=>{Ex.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])=>$xt(n,c,d)):$xt(n,i,l)}});function LHe(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(Kte(s)&&Kte(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=LHe(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=LHe(t.value,n.value);if(!c.valid){if(gE(s))return s;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return s.value=c.data,s}const Z3s=Ma("$ZodEnum",(s,t)=>{Ex.init(s,t);const n=MHe(t.entries),r=new Set(n);s._zod.values=r,xm(s,"pattern",a=>{const i=MHe(a.def.entries).filter(l=>M5s.has(typeof l));return new RegExp(i.length?`^(${i.map(l=>yG(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}}),X3s=Ma("$ZodLiteral",(s,t)=>{Ex.init(s,t);const n=new Set(t.values);s._zod.values=n,xm(s,"pattern",r=>{const a=r.def.values;return new RegExp(a.length?`^(${a.map(i=>typeof i=="string"?yG(i):i?yG(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}}),Q3s=Ma("$ZodTransform",(s,t)=>{var n;Ex.init(s,t),s._zod.optin="optional",(n=V4.memoizer)==null||n.guard(s),s._zod.parse=(r,a)=>{if(a.direction==="backward")throw new m8t(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 n7;return r.value=i,r}});function Uxt(s,t){return s.value=t.issues.length?void 0:t.value,s}const A8t=Ma("$ZodOptional",(s,t)=>{Ex.init(s,t),xm(s,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),s._zod.optout="optional",xm(s,"values",n=>{const r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),xm(s,"pattern",n=>{const r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Zet(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=>Uxt(n,i)):Uxt(n,a)}return t.innerType._zod.run(n,r)}}),J3s=Ma("$ZodExactOptional",(s,t)=>{A8t.init(s,t),xm(s,"values",n=>n.def.innerType._zod.values),xm(s,"pattern",n=>n.def.innerType._zod.pattern),s._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),eAs=Ma("$ZodNullable",(s,t)=>{Ex.init(s,t),xm(s,"optin",n=>n.def.innerType._zod.optin),xm(s,"optout",n=>n.def.innerType._zod.optout),xm(s,"pattern",n=>{const r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Zet(r.source)}|null)$`):void 0}),xm(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)}),tAs=Ma("$ZodDefault",(s,t)=>{Ex.init(s,t),s._zod.optin="defaulted",xm(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=>qxt(i,t)):qxt(a,t)}});function qxt(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const sAs=Ma("$ZodPrefault",(s,t)=>{Ex.init(s,t),s._zod.optin="defaulted",xm(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))}),nAs=Ma("$ZodNonOptional",(s,t)=>{Ex.init(s,t),xm(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=>Vxt(i,s)):Vxt(a,s)}});function Vxt(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 Hxt(s,t,n,r){return t.issues.length?(s.value=n.catchValue({...t,value:s.value,error:{issues:t.issues.map(a=>XW(a,r,t6()))},input:s.value}),s):(s.value=t.value,t.memo&&(s.memo=!0),s)}const rAs=Ma("$ZodCatch",(s,t)=>{Ex.init(s,t),xm(s,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),xm(s,"optout",n=>n.def.innerType._zod.optout),xm(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=>Hxt(n,i,t,r)):Hxt(n,a,t,r)}}),aAs=Ma("$ZodPipe",(s,t)=>{Ex.init(s,t),xm(s,"values",n=>n.def.in._zod.values),xm(s,"optin",n=>n.def.in._zod.optin),xm(s,"optout",n=>n.def.out._zod.optout),xm(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=>kce(l,t.in,r)):kce(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>kce(i,t.out,r)):kce(a,t.out,r)}});function kce(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 iAs=Ma("$ZodReadonly",(s,t)=>{Ex.init(s,t),xm(s,"propValues",n=>n.def.innerType._zod.propValues),xm(s,"values",n=>n.def.innerType._zod.values),xm(s,"optin",n=>{var r,a;return(a=(r=n.def.innerType)==null?void 0:r._zod)==null?void 0:a.optin}),xm(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(Gxt):Gxt(a)}});function Gxt(s){return s.memo||(s.value=Object.freeze(s.value)),s}const oAs=Ma("$ZodCustom",(s,t)=>{zw.init(s,t),Ex.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=>Wxt(i,n,r,s));Wxt(a,n,r,s)}});function Wxt(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(Yte(a))}}class lAs extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}const RHe="~memo",Kxt=[];function E8t(s){return s!==null&&typeof s=="object"}function Wze(s){return s.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}const T8t=new WeakMap,sQ=0,q4e=1,dee=2;function V4e(s,t,n){const r=T8t.get(s);if(r!==void 0)return r?dee:sQ;if(t.has(s))return dee;t.add(s);let a=sQ;const i=u=>{if(a!==dee&&(u!=null&&u._zod)){const h=V4e(u,t);h>a&&(a=h)}},l=(u,h)=>{var f;let m=sQ;for(const g of Reflect.ownKeys(u)){const x=Object.getOwnPropertyDescriptor(u,g);if(!x.enumerable)continue;const v=x.get?q4e:(f=x.value)!=null&&f._zod?V4e(x.value,t):sQ;v>m&&(m=v)}return m},o=u=>{u>a&&(a=u)},c=s._zod.def;switch(c.type){case"object":{const u=s8t(c);o(u?l(u):q4e),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?V4e(u,t):q4e);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),cAs(s,a)}function cAs(s,t){return t!==q4e&&T8t.set(s,t===dee),t}function dAs(s,t){let n=s.buckets.get(t);return n||(n=new WeakMap,s.buckets.set(t,n)),n}let Sce;const Cce=[],uAs={alloc(s,t,n){const r=Sce;if(!r)return n;Sce=void 0;const a={value:n,issues:null};return r.set(t.value,a),Cce.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"&&mAs(i,a.value))throw new lAs;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 y=V4e(s,new Set);if(y===sQ)return s._zod.parse=l,s._zod.run===o&&(s._zod.run=l),l(c,d);y===dee||r?n=!0:r=!0}const u=c.value;if(!E8t(u))return l(c,d);let h=d[RHe];h||(h={buckets:new WeakMap,backEdges:void 0},d[RHe]=h);let m;a===d?m=i:(m=dAs(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(...Wze(f.issues)):(c.memo=!0,h.backEdges??(h.backEdges=new WeakSet),h.backEdges.add(f.value)),c;Sce=m;const g=Cce.length,x=l(c,d);Sce=void 0;const v=Cce.length>g?Cce.pop():void 0;return x instanceof Promise?x.then(y=>(v&&(v.issues=y.issues.length?Wze(y.issues):Kxt),y)):(v&&(v.issues=x.issues.length?Wze(x.issues):Kxt),x)};s._zod.parse=o,s._zod.run===l&&(s._zod.run=o)})}};function hAs(){return uAs}function mAs(s,t){var r;const n=(r=s[RHe])==null?void 0:r.backEdges;return n!==void 0&&E8t(t)&&n.has(t)}const fAs=()=>{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=U5s(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 ${o8t(i.values[0])}`:`Invalid option: expected one of ${Mxt(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":""}: ${Mxt(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 pAs(){return{localeError:fAs()}}var Yxt;class gAs{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 xAs(){return new gAs}(Yxt=globalThis).__zod_globalRegistry??(Yxt.__zod_globalRegistry=xAs());const nQ=globalThis.__zod_globalRegistry;function M8t(s){return s.checks&&(s.checks=[...s.checks]),s}function yAs(s,t){return new s(M8t({type:"string",...Ml(t)}))}function vAs(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...Ml(t)})}function bAs(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...Ml(t)})}function _As(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...Ml(t)})}function wAs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ml(t)})}function jAs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ml(t)})}function NAs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ml(t)})}function kAs(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...Ml(t)})}function SAs(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...Ml(t)})}function CAs(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ml(t)})}function AAs(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...Ml(t)})}function EAs(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ml(t)})}function TAs(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...Ml(t)})}function MAs(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...Ml(t)})}function PAs(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ml(t)})}function IAs(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ml(t)})}function LAs(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ml(t)})}function RAs(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ml(t)})}function DAs(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ml(t)})}function FAs(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...Ml(t)})}function OAs(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...Ml(t)})}function zAs(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...Ml(t)})}function BAs(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...Ml(t)})}function $As(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ml(t)})}function UAs(s,t){return new s({type:"string",format:"date",check:"string_format",...Ml(t)})}function qAs(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...Ml(t)})}function VAs(s,t){return new s({type:"string",format:"duration",check:"string_format",...Ml(t)})}function HAs(s,t){return new s(M8t({type:"number",checks:[],...Ml(t)}))}function GAs(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...Ml(t)})}function WAs(s,t){return new s({type:"boolean",...Ml(t)})}function KAs(s){return new s({type:"unknown"})}function YAs(s,t){return new s({type:"never",...Ml(t)})}function Zxt(s,t){return new g8t({check:"less_than",...Ml(t),value:s,inclusive:!1})}function Kze(s,t){return new g8t({check:"less_than",...Ml(t),value:s,inclusive:!0})}function Xxt(s,t){return new x8t({check:"greater_than",...Ml(t),value:s,inclusive:!1})}function Yze(s,t){return new x8t({check:"greater_than",...Ml(t),value:s,inclusive:!0})}function Qxt(s,t){return new W4s({check:"multiple_of",...Ml(t),value:s})}function P8t(s,t){return new Y4s({check:"max_length",...Ml(t),maximum:s})}function jEe(s,t){return new Z4s({check:"min_length",...Ml(t),minimum:s})}function I8t(s,t){return new X4s({check:"length_equals",...Ml(t),length:s})}function ZAs(s,t){return new Q4s({check:"string_format",format:"regex",...Ml(t),pattern:s})}function XAs(s){return new J4s({check:"string_format",format:"lowercase",...Ml(s)})}function QAs(s){return new e3s({check:"string_format",format:"uppercase",...Ml(s)})}function JAs(s,t){return new t3s({check:"string_format",format:"includes",...Ml(t),includes:s})}function eEs(s,t){return new s3s({check:"string_format",format:"starts_with",...Ml(t),prefix:s})}function tEs(s,t){return new n3s({check:"string_format",format:"ends_with",...Ml(t),suffix:s})}function QW(s){return new r3s({check:"overwrite",tx:s})}function sEs(s){return QW(t=>t.normalize(s))}function nEs(){return QW(s=>s.trim())}function rEs(){return QW(s=>s.toLowerCase())}function aEs(){return QW(s=>s.toUpperCase())}function iEs(){return QW(s=>E5s(s))}function oEs(s,t,n){return new s({type:"array",element:t,...Ml(n)})}function lEs(s,t,n){return new s({type:"custom",check:"custom",fn:t,...Ml(n)})}function cEs(s,t){const n=dEs(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(Yte(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(Yte(i))}},s(r.value,r)),t);return n}function dEs(s,t){const n=new zw({check:"custom",...Ml(t)});return n._zod.check=s,n}function uee(s,...t){for(const n of t)for(const r of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,r)&&LB(s,r,n[r]);return s}function L8t(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)??nQ,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 jL(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 kb(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),kb(f,t,m),t.seen.get(f).isParent=!0)}const c=t.metadataRegistry.get(s);return c&&uee(l.schema,c),t.io==="input"&&Y1(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 Jxt(s){return s.replace(/~/g,"~0").replace(/\//g,"~1")}function R8t(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 v=(x=s.external.registry.get(u[0]))==null?void 0:x.id,y=s.external.uri??(w=>w);if(v)return{ref:y(v)};const b=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=b,{defId:b,ref:`${y("__shared")}#/${h}/${Jxt(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+Jxt(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 D8t(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;D8t(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 F8t=new Set(["type","properties","required","additionalProperties"]),eyt=["oneOf","anyOf"];function tyt(s){const t=s.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function DHe(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(!F8t.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])??tyt(u);h!=null&&(c.some(m=>JSON.stringify(m)===JSON.stringify(h))||c.push(h))}const d=c.length===1?c[0]:DHe(c)??{allOf:c};LB(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=tyt(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 uEs(s){const t=s.allOf;if(!Array.isArray(t)||t.length<2)return;for(const a of F8t)if(a in s)return;const n=t.filter(a=>eyt.some(i=>Array.isArray(a[i])));let r=null;if(!n.length)r=DHe(t);else{const a=n[0],i=eyt.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=>DHe([...l,c]));if(o.some(c=>!c))return;r={[i]:o}}r&&(delete s.allOf,uee(s,r))}function O8t(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 y=s.seen.get(x),b=y.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)):uee(f,b),uee(f,g),h._zod.parent===x)for(const S in f)S==="$ref"||S==="allOf"||S in g||delete f[S];if(b.$ref&&y.def)for(const S in f)S==="$ref"||S==="allOf"||S in y.def&&JSON.stringify(f[S])===JSON.stringify(y.def[S])&&delete f[S]}const v=h._zod.parent;if(v&&v!==x){r(v);const y=s.seen.get(v);if(y!=null&&y.schema.$ref&&(f.$ref=y.schema.$ref,y.def))for(const b in f)b==="$ref"||b==="allOf"||b in y.def&&JSON.stringify(f[b])===JSON.stringify(y.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())D8t(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)??[])uEs(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)}uee(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,LB(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:NEe(t,"input",s.processors),output:NEe(t,"output",s.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function Y1(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 Y1(r.element,n);if(r.type==="set")return Y1(r.valueType,n);if(r.type==="lazy")return Y1(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 Y1(r.innerType,n);if(r.type==="intersection")return Y1(r.left,n)||Y1(r.right,n);if(r.type==="record"||r.type==="map")return Y1(r.keyType,n)||Y1(r.valueType,n);if(r.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:Y1(r.in,n)||Y1(r.out,n);if(r.type==="object"){for(const a in r.shape)if(Y1(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(Y1(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(Y1(a,n))return!0;return!!(r.rest&&Y1(r.rest,n))}return!1}const hEs=(s,t={})=>n=>{const r=L8t({...n,processors:t});return kb(s,r),R8t(r,s),O8t(r,s)},NEe=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=L8t({...a??{},target:i,io:t,processors:n});return kb(s,l),R8t(l,s),O8t(l,s)},vG=(s,t,n)=>{(s[t]===void 0||n>s[t])&&(s[t]=n)},bG=(s,t,n)=>{(s[t]===void 0||n{vG(s,"minimum",t),bG(s,"maximum",t)},z8t=(s,t)=>{s.multipleOf??(s.multipleOf=[]),s.multipleOf.includes(t)||s.multipleOf.push(t)},B8t=(s,t)=>{s.patterns??(s.patterns=new Set),s.patterns.add(t)},$8t=(s,t)=>{s.mime=s.mime?s.mime.filter(n=>t.includes(n)):[...t]},U8t=(s,t)=>{s.format=t,t.includes("int")&&(s.isInt=!0)},nyt=(s,t)=>vG(s,"minimum",t.minimum),ryt=(s,t)=>bG(s,"maximum",t.maximum),ayt=s=>(t,n)=>{U8t(t,n.format);const[r,a]=s[n.format];vG(t,"minimum",r),bG(t,"maximum",a)},Zze={greater_than:(s,t)=>vG(s,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(s,t)=>bG(s,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(s,t)=>z8t(s,t.value),number_format:ayt(l8t),bigint_format:ayt(I5s),min_length:nyt,max_length:ryt,length_equals:(s,t)=>syt(s,t.length),min_size:nyt,max_size:ryt,size_equals:(s,t)=>syt(s,t.size),string_format:(s,t)=>{U8t(s,t.format),t.pattern&&B8t(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)=>$8t(s,t.mime)};function f4(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=Zze[l._zod.def.check])==null||i.call(Zze,t,l._zod.def);const a=s._zod.bag;a.minimum!==void 0&&vG(t,"minimum",a.minimum),a.exclusiveMinimum!==void 0&&vG(t,"exclusiveMinimum",a.exclusiveMinimum),a.maximum!==void 0&&bG(t,"maximum",a.maximum),a.exclusiveMaximum!==void 0&&bG(t,"exclusiveMaximum",a.exclusiveMaximum),a.multipleOf!==void 0&&z8t(t,a.multipleOf),a.format!==void 0&&(t.format??(t.format=a.format),a.format.includes("int")&&(t.isInt=!0)),a.mime&&$8t(t,a.mime);for(const l of a.patterns??[])B8t(t,l);return t}const mEs={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},fEs=new Map([[N8t,L4s],[att,R4s]]),pEs=s=>fEs.get(s)??s,gEs=(s,t,n,r)=>{const a=n;a.type="string";const{minimum:i,maximum:l,format:o,patterns:c,contentEncoding:d,laxFormat:u}=f4(s);if(typeof i=="number"&&(a.minLength=i),typeof l=="number"&&(a.maxLength=l),o&&(a.format=mEs[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(pEs);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}))])}},xEs=(s,t,n,r)=>{const a=n,{minimum:i,maximum:l,multipleOf:o,exclusiveMaximum:c,exclusiveMinimum:d,isInt:u}=f4(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 y of o)Number.isFinite(y)&&y!==0?g.add(Math.abs(y)):jL(s,t,a,r,`A multipleOf divisor of ${y} cannot be represented in JSON Schema`);const[x,...v]=g;x!==void 0&&(a.multipleOf=x),v.length&&(a.allOf=[...a.allOf??[],...v.map(y=>({multipleOf:y}))])}},yEs=(s,t,n,r)=>{n.type="boolean"},vEs=(s,t,n,r)=>{n.not={}},bEs=(s,t,n,r)=>{},_Es=(s,t,n,r)=>{const a=s._zod.def,i=MHe(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},wEs=(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(jL(s,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof l=="bigint"){if(jL(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},jEs=(s,t,n,r)=>{jL(s,t,n,r,"Custom types cannot be represented in JSON Schema")},NEs=(s,t,n,r)=>{jL(s,t,n,r,"Transforms cannot be represented in JSON Schema")},kEs=(s,t,n,r)=>{const a=n,i=s._zod.def,{minimum:l,maximum:o}=f4(s);typeof l=="number"&&(a.minItems=l),typeof o=="number"&&(a.maxItems=o),a.type="array",a.items=kb(i.element,t,{...r,path:[...r.path,"items"]})};function FHe(s){const t=s._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?FHe(t.out):t.type==="catch"?FHe(t.innerType):s._zod.optin}const SEs=(s,t,n,r)=>{var d;const a=n,i=s._zod.def,l=i.shape;if(Object.getOwnPropertySymbols(l).length&&jL(s,t,a,r,"Symbol keys cannot be represented in JSON Schema"))return;a.type="object",a.properties={};for(const u in l)LB(a.properties,u,kb(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"?FHe(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=kb(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},CEs=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>kb(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},AEs=(s,t,n,r)=>{const a=s._zod.def,i=kb(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=kb(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)},EEs=(s,t,n,r)=>{const a=s._zod.def,i=kb(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"}]},TEs=(s,t,n,r)=>{const a=s._zod.def;kb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},itt=Symbol();function q8t(s,t,n,r,a){let i=!1;const l=JSON.stringify(s,(o,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(jL(t,n,r,a,"BigInt defaults cannot be represented in JSON Schema"),itt):JSON.parse(l)}const MEs=(s,t,n,r)=>{const a=s._zod.def;kb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType;const l=q8t(a.defaultValue,s,t,n,r);l!==itt&&(n.default=l)},PEs=(s,t,n,r)=>{const a=s._zod.def;kb(a.innerType,t,r);const i=t.seen.get(s);if(i.ref=a.innerType,t.io!=="input")return;const l=q8t(a.defaultValue,s,t,n,r);l!==itt&&(n._prefault=l)},IEs=(s,t,n,r)=>{const a=s._zod.def;kb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType;let l;try{l=a.catchValue(void 0)}catch{jL(s,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=l},LEs=(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;kb(l,t,r);const o=t.seen.get(s);o.ref=l},REs=(s,t,n,r)=>{const a=s._zod.def;kb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},V8t=(s,t,n,r)=>{const a=s._zod.def;kb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},iyt=new WeakSet([Object.prototype,Error.prototype]);function Ace(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 H8t=(s,t)=>{t4s.init(s,t),s.name="ZodError";const n=Object.getPrototypeOf(s);iyt.has(n)||(iyt.add(n),Ace(n,"format",r=>a=>r4s(r,a)),Ace(n,"flatten",r=>a=>n4s(r,a)),Ace(n,"addIssue",r=>a=>{r.issues.push(a),r.message=JSON.stringify(r.issues,PHe,2)}),Ace(n,"addIssues",r=>a=>{r.issues.push(...a),r.message=JSON.stringify(r.issues,PHe,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},DEs=Ma("ZodError",H8t),jk=Ma("ZodError",H8t,void 0,{Parent:Error}),FEs=Jet(jk),OEs=ett(jk),zEs=ttt(jk),BEs=stt(jk),$Es=d4s(jk),UEs=u4s(jk),qEs=h4s(jk),VEs=m4s(jk),HEs=f4s(jk),GEs=p4s(jk),WEs=g4s(jk),KEs=x4s(jk);function YEs(){V4.localeError||t6(pAs())}function ott(){V4.memoizer||t6({memoizer:hAs()})}const Tx=Ma("ZodType",(s,t)=>(YEs(),Ex.init(s,t),s.def=t,s.type=t.type,s),{check(...s){const t=this.def;return this.clone(Hj(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 e6(this,s,t)},brand(){return this},register(s,t){return s.add(this,t),this},refine(s,t){return this.check(KTs(s,t))},superRefine(s,t){return this.check(YTs(s,t))},overwrite(s){return this.check(QW(s))},optional(){return cyt(this)},exactOptional(){return RTs(this)},nullable(){return dyt(this)},nullish(){return cyt(dyt(this))},nonoptional(s){return $Ts(this,s)},array(){return STs(this)},or(s){return ETs([this,s])},and(s){return MTs(this,s)},transform(s){return uyt(this,LTs(s))},default(s){return OTs(this,s)},prefault(s){return BTs(this,s)},catch(s){return qTs(this,s)},pipe(s){return uyt(this,s)},readonly(){return GTs(this)},describe(s){const t=this.clone();return nQ.add(t,{description:s}),t},meta(...s){if(s.length===0)return nQ.get(this);const t=this.clone();return nQ.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 u8t(this,"~standard",{...v8t(this),jsonSchema:{input:NEe(this,"input"),output:NEe(this,"output")}})},set"~standard"(s){wL(this,"~standard",s)},parse:function s(t,n){return FEs(this,t,n,{callee:s})},parseAsync:async function s(t,n){return await OEs(this,t,n,{callee:s})},safeParse(s,t){return zEs(this,s,t)},async safeParseAsync(s,t){return BEs(this,s,t)},get spa(){return this==null?void 0:this.safeParseAsync},set spa(s){wL(this,"spa",s)},validate(s,t){return o4s(this,s,t)},validateAsync(s,t){return c4s(this,s,t)},encode:function s(t,n){return $Es(this,t,n,{callee:s})},decode:function s(t,n){return UEs(this,t,n,{callee:s})},encodeAsync:async function s(t,n){return await qEs(this,t,n,{callee:s})},decodeAsync:async function s(t,n){return await VEs(this,t,n,{callee:s})},safeEncode(s,t){return HEs(this,s,t)},safeDecode(s,t){return GEs(this,s,t)},async safeEncodeAsync(s,t){return WEs(this,s,t)},async safeDecodeAsync(s,t){return KEs(this,s,t)},toJSONSchema(s){return hEs(this,{})(s)},get description(){var s;return(s=nQ.get(this))==null?void 0:s.description},get _def(){return this._zod.def}}),G8t=Ma("_ZodString",(s,t)=>{rtt.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>gEs(s,n,r)},h8t({format:s=>f4(s).format??null,minLength:s=>f4(s).minimum??null,maxLength:s=>f4(s).maximum??null},{regex(...s){return this.check(ZAs(...s))},includes(...s){return this.check(JAs(...s))},startsWith(...s){return this.check(eEs(...s))},endsWith(...s){return this.check(tEs(...s))},min(...s){return this.check(jEe(...s))},max(...s){return this.check(P8t(...s))},length(...s){return this.check(I8t(...s))},nonempty(...s){return this.check(jEe(1,...s))},lowercase(s){return this.check(XAs(s))},uppercase(s){return this.check(QAs(s))},trim(){return this.check(nEs())},normalize(...s){return this.check(sEs(...s))},toLowerCase(){return this.check(rEs())},toUpperCase(){return this.check(aEs())},slugify(){return this.check(iEs())}})),ZEs=Ma("ZodString",(s,t)=>{rtt.init(s,t),G8t.init(s,t)},{email(s){return this.check(vAs(tTs,s))},url(s){return this.check(kAs(nTs,s))},jwt(s){return this.check(BAs(yTs,s))},emoji(s){return this.check(SAs(rTs,s))},guid(s){return this.check(bAs(sTs,s))},uuid(s){return this.check(_As(Ece,s))},uuidv4(s){return this.check(wAs(Ece,s))},uuidv6(s){return this.check(jAs(Ece,s))},uuidv7(s){return this.check(NAs(Ece,s))},nanoid(s){return this.check(CAs(aTs,s))},cuid(s){return this.check(AAs(iTs,s))},cuid2(s){return this.check(EAs(oTs,s))},ulid(s){return this.check(TAs(lTs,s))},base64(s){return this.check(FAs(pTs,s))},base64url(s){return this.check(OAs(gTs,s))},xid(s){return this.check(MAs(cTs,s))},ksuid(s){return this.check(PAs(dTs,s))},ipv4(s){return this.check(IAs(uTs,s))},ipv6(s){return this.check(LAs(hTs,s))},cidrv4(s){return this.check(RAs(mTs,s))},cidrv6(s){return this.check(DAs(fTs,s))},e164(s){return this.check(zAs(xTs,s))},datetime(s){return this.check($As(XEs,s))},date(s){return this.check(UAs(QEs,s))},time(s){return this.check(qAs(JEs,s))},duration(s){return this.check(VAs(eTs,s))}});function yl(s){return yAs(ZEs,s)}const Vg=Ma("ZodStringFormat",(s,t)=>{eg.init(s,t),G8t.init(s,t)}),XEs=Ma("ZodISODateTime",(s,t)=>{N3s.init(s,t),Vg.init(s,t)}),QEs=Ma("ZodISODate",(s,t)=>{k3s.init(s,t),Vg.init(s,t)}),JEs=Ma("ZodISOTime",(s,t)=>{S3s.init(s,t),Vg.init(s,t)}),eTs=Ma("ZodISODuration",(s,t)=>{C3s.init(s,t),Vg.init(s,t)}),tTs=Ma("ZodEmail",(s,t)=>{d3s.init(s,t),Vg.init(s,t)}),sTs=Ma("ZodGUID",(s,t)=>{l3s.init(s,t),Vg.init(s,t)}),Ece=Ma("ZodUUID",(s,t)=>{c3s.init(s,t),Vg.init(s,t)}),nTs=Ma("ZodURL",(s,t)=>{g3s.init(s,t),Vg.init(s,t)}),rTs=Ma("ZodEmoji",(s,t)=>{x3s.init(s,t),Vg.init(s,t)}),aTs=Ma("ZodNanoID",(s,t)=>{y3s.init(s,t),Vg.init(s,t)}),iTs=Ma("ZodCUID",(s,t)=>{v3s.init(s,t),Vg.init(s,t)}),oTs=Ma("ZodCUID2",(s,t)=>{b3s.init(s,t),Vg.init(s,t)}),lTs=Ma("ZodULID",(s,t)=>{_3s.init(s,t),Vg.init(s,t)}),cTs=Ma("ZodXID",(s,t)=>{w3s.init(s,t),Vg.init(s,t)}),dTs=Ma("ZodKSUID",(s,t)=>{j3s.init(s,t),Vg.init(s,t)}),uTs=Ma("ZodIPv4",(s,t)=>{A3s.init(s,t),Vg.init(s,t)}),hTs=Ma("ZodIPv6",(s,t)=>{T3s.init(s,t),Vg.init(s,t)}),mTs=Ma("ZodCIDRv4",(s,t)=>{M3s.init(s,t),Vg.init(s,t)}),fTs=Ma("ZodCIDRv6",(s,t)=>{I3s.init(s,t),Vg.init(s,t)}),pTs=Ma("ZodBase64",(s,t)=>{L3s.init(s,t),Vg.init(s,t)}),gTs=Ma("ZodBase64URL",(s,t)=>{D3s.init(s,t),Vg.init(s,t)}),xTs=Ma("ZodE164",(s,t)=>{F3s.init(s,t),Vg.init(s,t)}),yTs=Ma("ZodJWT",(s,t)=>{z3s.init(s,t),Vg.init(s,t)}),W8t=Ma("ZodNumber",(s,t)=>{k8t.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>xEs(s,n,r,a),s.isFinite=!0},h8t({minValue:s=>{const{minimum:t,exclusiveMinimum:n}=f4(s);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:s=>{const{maximum:t,exclusiveMaximum:n}=f4(s);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:s=>{const{isInt:t,multipleOf:n}=f4(s);return!!t||!!(n!=null&&n.some(Number.isSafeInteger))},format:s=>f4(s).format??null},{gt(s,t){return this.check(Xxt(s,t))},gte(s,t){return this.check(Yze(s,t))},min(s,t){return this.check(Yze(s,t))},lt(s,t){return this.check(Zxt(s,t))},lte(s,t){return this.check(Kze(s,t))},max(s,t){return this.check(Kze(s,t))},int(s){return this.check(oyt(s))},safe(s){return this.check(oyt(s))},positive(s){return this.check(Xxt(0,s))},nonnegative(s){return this.check(Yze(0,s))},negative(s){return this.check(Zxt(0,s))},nonpositive(s){return this.check(Kze(0,s))},multipleOf(s,t){return this.check(Qxt(s,t))},step(s,t){return this.check(Qxt(s,t))},finite(){return this}}));function hee(s){return HAs(W8t,s)}const vTs=Ma("ZodNumberFormat",(s,t)=>{B3s.init(s,t),W8t.init(s,t)});function oyt(s){return GAs(vTs,s)}const bTs=Ma("ZodBoolean",(s,t)=>{$3s.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>yEs(s,n,r)});function _Ts(s){return WAs(bTs,s)}const wTs=Ma("ZodUnknown",(s,t)=>{U3s.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>bEs()});function lyt(){return KAs(wTs)}const jTs=Ma("ZodNever",(s,t)=>{q3s.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>vEs(s,n,r)});function NTs(s){return YAs(jTs,s)}const kTs=Ma("ZodArray",(s,t)=>{ott(),V3s.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>kEs(s,n,r,a),s.element=t.element},{min(s,t){return this.check(jEe(s,t))},nonempty(s){return this.check(jEe(1,s))},max(s,t){return this.check(P8t(s,t))},length(s,t){return this.check(I8t(s,t))},unwrap(){return this.element}});function STs(s,t){return oEs(kTs,s,t)}const CTs=Ma("ZodObject",(s,t)=>{ott(),W3s.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>SEs(s,n,r,a),W5s(s,"shape",n=>n._zod.def.shape,!1)},{keyof(){return ltt(Object.keys(this._zod.def.shape))},catchall(s){return this.clone(Hj(this._zod.def,{catchall:s}))},passthrough(){return this.clone(Hj(this._zod.def,{catchall:lyt()}))},loose(){return this.clone(Hj(this._zod.def,{catchall:lyt()}))},strict(){return this.clone(Hj(this._zod.def,{catchall:NTs()}))},strip(){return this.clone(Hj(this._zod.def,{catchall:void 0}))},extend(s){return D5s(this,s)},safeExtend(s){return F5s(this,s)},merge(s){return O5s(this,s)},pick(s){return L5s(this,s)},omit(s){return R5s(this,s)},partial(...s){return Pxt(K8t,this,s[0])},exactPartial(...s){return Pxt(Y8t,this,s[0],"exactPartial")},required(...s){return z5s(Z8t,this,s[0])}});function F2(s,t){const n={type:"object",shape:s??{},...Ml(t)};return new CTs(n)}const ATs=Ma("ZodUnion",(s,t)=>{K3s.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>CEs(s,n,r,a),s.options=t.options});function ETs(s,t){return new ATs({type:"union",options:s,...Ml(t)})}const TTs=Ma("ZodIntersection",(s,t)=>{Y3s.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>AEs(s,n,r,a)});function MTs(s,t){return new TTs({type:"intersection",left:s,right:t})}const OHe=Ma("ZodEnum",(s,t)=>{Z3s.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(r,a,i)=>_Es(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 OHe({...t,checks:[],...Ml(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 OHe({...t,checks:[],...Ml(a),entries:i})}});function ltt(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new OHe({type:"enum",entries:n,...Ml(t)})}const PTs=Ma("ZodLiteral",(s,t)=>{X3s.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>wEs(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 fx(s,t){return new PTs({type:"literal",values:Array.isArray(s)?s:[s],...Ml(t)})}const ITs=Ma("ZodTransform",(s,t)=>{ott(),Q3s.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>NEs(s,n,r,a),s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new m8t(s.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(Yte(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(Yte(l))}};const a=t.transform(n.value,n);return a instanceof Promise?a.then(i=>(n.value=i,n)):(n.value=a,n)}});function LTs(s){return new ITs({type:"transform",transform:s})}const K8t=Ma("ZodOptional",(s,t)=>{A8t.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>V8t(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function cyt(s){return new K8t({type:"optional",innerType:s})}const Y8t=Ma("ZodExactOptional",(s,t)=>{J3s.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>V8t(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function RTs(s){return new Y8t({type:"optional",innerType:s})}const DTs=Ma("ZodNullable",(s,t)=>{eAs.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>EEs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function dyt(s){return new DTs({type:"nullable",innerType:s})}const FTs=Ma("ZodDefault",(s,t)=>{tAs.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>MEs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function OTs(s,t){return new FTs({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():i8t(t)}})}const zTs=Ma("ZodPrefault",(s,t)=>{sAs.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>PEs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function BTs(s,t){return new zTs({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():i8t(t)}})}const Z8t=Ma("ZodNonOptional",(s,t)=>{nAs.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>TEs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function $Ts(s,t){return new Z8t({type:"nonoptional",innerType:s,...Ml(t)})}const UTs=Ma("ZodCatch",(s,t)=>{rAs.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>IEs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function qTs(s,t){return new UTs({type:"catch",innerType:s,catchValue:typeof t=="function"?t:Y5s(t)})}const VTs=Ma("ZodPipe",(s,t)=>{aAs.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>LEs(s,n,r,a),s.in=t.in,s.out=t.out});function uyt(s,t){return new VTs({type:"pipe",in:s,out:t})}const HTs=Ma("ZodReadonly",(s,t)=>{iAs.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>REs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function GTs(s){return new HTs({type:"readonly",innerType:s})}const WTs=Ma("ZodCustom",(s,t)=>{oAs.init(s,t),Tx.init(s,t),s._zod.processJSONSchema=(n,r,a)=>jEs(s,n,r,a)});function KTs(s,t={}){return lEs(WTs,s,t)}function YTs(s,t){return cEs(s,t)}var ZTs=Object.defineProperty,XTs=(s,t)=>ZTs(s,"name",{value:t,configurable:!0}),QTs=j.forwardRef(XTs(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")),X8t=QTs;const JTs=AB("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ee=j.forwardRef(({className:s,...t},n)=>e.jsx(X8t,{ref:n,className:Pt(JTs(),s),...t}));ee.displayName=X8t.displayName;const jLe=i5s,Q8t=j.createContext({}),_g=({...s})=>e.jsx(Q8t.Provider,{value:{name:s.name},children:e.jsx(s5s,{...s})}),NLe=()=>{const s=j.useContext(Q8t),t=j.useContext(J8t),{getFieldState:n,formState:r}=a5s(),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}},J8t=j.createContext({}),Bp=j.forwardRef(({className:s,...t},n)=>{const r=j.useId();return e.jsx(J8t.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:Pt("space-y-2",s),...t})})});Bp.displayName="FormItem";const $p=j.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=NLe();return e.jsx(ee,{ref:n,className:Pt(r&&"text-destructive",s),htmlFor:a,...t})});$p.displayName="FormLabel";const Up=j.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=NLe();return e.jsx(VJe,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});Up.displayName="FormControl";const H4e=j.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=NLe();return e.jsx("p",{ref:n,id:r,className:Pt("text-sm text-muted-foreground",s),...t})});H4e.displayName="FormDescription";const m_=j.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=NLe(),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});m_.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 eMs=Object.defineProperty,tMs=(s,t)=>eMs(s,"name",{value:t,configurable:!0});function ctt(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])}tMs(ctt,"usePrevious");var sMs=Object.defineProperty,Ru=(s,t)=>sMs(s,"name",{value:t,configurable:!0}),nMs=[" ","Enter","ArrowUp","ArrowDown"],rMs=[" ","Enter"],_G="Select",[kLe,SLe,aMs]=SB(_G),[RB,fkr]=ep(_G,[aMs,n3]),dtt=n3(),[iMs,s6]=RB(_G),[oMs,lMs]=RB(_G);function ezt(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,v=dtt(t),[y,b]=j.useState(null),[w,S]=j.useState(null),[A,E]=j.useState(!1),I=a3(d),[P,R]=dy({prop:r,defaultProp:a??!1,onChange:i,caller:_G}),[D,O]=dy({prop:l,defaultProp:o,onChange:c,caller:_G}),U=j.useRef(null),W=j.useRef(D);j.useEffect(()=>{const J=g?y==null?void 0:y.ownerDocument.getElementById(g):y==null?void 0:y.form;if(J instanceof HTMLFormElement){const ce=Ru(()=>O(W.current),"reset");return J.addEventListener("reset",ce),()=>J.removeEventListener("reset",ce)}},[g,y,O]);const V=y?!!g||!!y.closest("form"):!0,[G,Z]=j.useState(new Set),X=cy(),ae=Array.from(G).map(J=>J.props.value).join(";"),le=j.useCallback(J=>{Z(ce=>new Set(ce).add(J))},[]),re=j.useCallback(J=>{Z(ce=>{const ve=new Set(ce);return ve.delete(J),ve})},[]),te={required:f,trigger:y,onTriggerChange:b,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:A,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(bae,{...v,children:e.jsx(iMs,{scope:t,...te,children:e.jsx(kLe.Provider,{scope:t,children:e.jsx(oMs,{scope:t,onNativeOptionAdd:le,onNativeOptionRemove:re,children:uzt(x)?x(te):n})})})})}Ru(ezt,"SelectProvider");var cMs=Ru(s=>{const{__scopeSelect:t,children:n,...r}=s;return e.jsx(ezt,{__scopeSelect:t,...r,internal_do_not_use_render:({isFormControl:a})=>e.jsxs(e.Fragment,{children:[n,a?e.jsx(LMs,{__scopeSelect:t}):null]})})},"Select"),dMs="SelectTrigger",tzt=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,disabled:a=!1,...i}=t,l=dtt(r),o=s6(dMs,r),c=o.disabled||a,d=Vo(n,o.onTriggerChange),u=SLe(r),h=j.useRef("touch"),[m,f,g]=htt(v=>{const y=u().filter(S=>!S.disabled),b=y.find(S=>S.value===o.value),w=mtt(y,v,b);w!==void 0&&o.onValueChange(w.value)}),x=Ru(v=>{c||(o.onOpenChange(!0),g()),v&&(o.triggerPointerDownPosRef.current={x:Math.round(v.pageX),y:Math.round(v.pageY)})},"handleOpen");return e.jsx(_ae,{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":Rae(o.value)?"":void 0,...i,ref:d,onClick:Ra(i.onClick,v=>{v.currentTarget.focus(),h.current!=="mouse"&&x(v)}),onPointerDown:Ra(i.onPointerDown,v=>{h.current=v.pointerType;const y=v.target;y.hasPointerCapture(v.pointerId)&&y.releasePointerCapture(v.pointerId),v.button===0&&v.ctrlKey===!1&&v.pointerType==="mouse"&&(x(v),v.preventDefault())}),onKeyDown:Ra(i.onKeyDown,v=>{const y=m.current!=="";!(v.ctrlKey||v.altKey||v.metaKey)&&v.key.length===1&&f(v.key),!(y&&v.key===" ")&&nMs.includes(v.key)&&(x(),v.preventDefault())})})})},"SelectTrigger")),uMs="SelectValue",hMs=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,className:a,style:i,children:l,placeholder:o="",...c}=t,d=s6(uMs,r),{onValueNodeHasChildrenChange:u}=d,h=l!==void 0,m=Vo(n,d.onValueNodeChange);Af(()=>{u(h)},[u,h]);const f=Rae(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")),mMs=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,children:a,...i}=t;return e.jsx(Ei.span,{"aria-hidden":!0,...i,ref:n,children:a||"▼"})},"SelectIcon")),fMs="SelectPortal",[pMs,gMs]=RB(fMs,{forceMount:void 0}),xMs=Ru(s=>{const{__scopeSelect:t,forceMount:n,...r}=s;return e.jsx(pMs,{scope:s.__scopeSelect,forceMount:n,children:e.jsx(fae,{asChild:!0,...r})})},"SelectPortal"),B7="SelectContent",szt=j.forwardRef(Ru(function(t,n){const r=gMs(B7,t.__scopeSelect),{forceMount:a=r.forceMount,...i}=t,l=s6(B7,t.__scopeSelect),[o,c]=j.useState();return Af(()=>{c(new DocumentFragment)},[]),e.jsx(my,{present:a||l.open,children:({present:d})=>d?e.jsx(bMs,{...i,ref:n}):e.jsx(yMs,{...i,fragment:o})})},"SelectContent")),yMs=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,children:a,fragment:i}=t;return i?yv.createPortal(e.jsx(nzt,{scope:r,children:e.jsx(kLe.Slot,{scope:r,children:e.jsx("div",{ref:n,children:a})})}),i):null},"SelectContentFragment")),lS=10,[nzt,DB]=RB(B7),vMs=hC("SelectContent.RemoveScroll"),bMs=j.forwardRef(Ru(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:v,avoidCollisions:y,...b}=t,w=s6(B7,r),[S,A]=j.useState(null),[E,I]=j.useState(null),P=Vo(n,A),[R,D]=j.useState(null),[O,U]=j.useState(null),W=SLe(r),[V,G]=j.useState(!1),Z=j.useRef(!1);j.useEffect(()=>{if(S)return UIe(S)},[S]),BW();const X=j.useCallback(Ee=>{const[ke,...Ie]=W().map(Be=>Be.ref.current),[Fe]=Ie.slice(-1),Ne=document.activeElement;for(const Be of Ee)if(Be===Ne||(Be==null||Be.scrollIntoView({block:"nearest"}),Be===ke&&E&&(E.scrollTop=0),Be===Fe&&E&&(E.scrollTop=E.scrollHeight),Be==null||Be.focus(),document.activeElement!==Ne))return},[W,E]),ae=j.useCallback(()=>X([R,S]),[X,R,S]);j.useEffect(()=>{V&&ae()},[V,ae]);const{onOpenChange:le,triggerPointerDownPosRef:re}=w;j.useEffect(()=>{if(S){let Ee={x:0,y:0};const ke=Ru(Fe=>{var Ne,Be;Ee={x:Math.abs(Math.round(Fe.pageX)-(((Ne=re.current)==null?void 0:Ne.x)??0)),y:Math.abs(Math.round(Fe.pageY)-(((Be=re.current)==null?void 0:Be.y)??0))}},"handlePointerMove"),Ie=Ru(Fe=>{Ee.x<=10&&Ee.y<=10?Fe.preventDefault():Fe.composedPath().includes(S)||le(!1),document.removeEventListener("pointermove",ke),re.current=null},"handlePointerUp");return re.current!==null&&(document.addEventListener("pointermove",ke),document.addEventListener("pointerup",Ie,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ke),document.removeEventListener("pointerup",Ie,{capture:!0})}}},[S,le,re]),j.useEffect(()=>{const Ee=Ru(()=>le(!1),"close");return window.addEventListener("blur",Ee),window.addEventListener("resize",Ee),()=>{window.removeEventListener("blur",Ee),window.removeEventListener("resize",Ee)}},[le]);const[te,J]=htt(Ee=>{const ke=W().filter(Ne=>!Ne.disabled),Ie=ke.find(Ne=>Ne.ref.current===document.activeElement),Fe=mtt(ke,Ee,Ie);Fe&&setTimeout(()=>{var Ne;return(Ne=Fe.ref.current)==null?void 0:Ne.focus()})}),ce=j.useCallback((Ee,ke,Ie)=>{const Fe=!Z.current&&!Ie;(w.value!==void 0&&w.value===ke||Fe)&&(D(Ee),Fe&&(Z.current=!0))},[w.value]),ve=j.useCallback(()=>S==null?void 0:S.focus(),[S]),fe=j.useCallback((Ee,ke,Ie)=>{const Fe=!Z.current&&!Ie;(w.value!==void 0&&w.value===ke||Fe)&&U(Ee)},[w.value]),ue=a==="popper"?hyt:_Ms,be=ue===hyt?{side:c,sideOffset:d,align:u,alignOffset:h,arrowPadding:m,collisionBoundary:f,collisionPadding:g,sticky:x,hideWhenDetached:v,avoidCollisions:y}:{};return e.jsx(nzt,{scope:r,content:S,viewport:E,onViewportChange:I,itemRefCallback:ce,selectedItem:R,onItemLeave:ve,itemTextRefCallback:fe,focusSelectedItem:ae,selectedItemText:O,position:a,isPositioned:V,searchRef:te,children:e.jsx(gae,{as:vMs,allowPinchZoom:!0,children:e.jsx(BIe,{asChild:!0,trapped:w.open,onMountAutoFocus:Ee=>{Ee.preventDefault()},onUnmountAutoFocus:Ra(i,Ee=>{var ke;(ke=w.trigger)==null||ke.focus({preventScroll:!0}),Ee.preventDefault()}),children:e.jsx(CB,{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,...be,onPlaced:()=>G(!0),ref:P,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:Ra(b.onKeyDown,Ee=>{const ke=Ee.ctrlKey||Ee.altKey||Ee.metaKey;if(Ee.key==="Tab"&&Ee.preventDefault(),!ke&&Ee.key.length===1&&J(Ee.key),["ArrowUp","ArrowDown","Home","End"].includes(Ee.key)){let Fe=W().filter(Ne=>!Ne.disabled).map(Ne=>Ne.ref.current);if(["ArrowUp","End"].includes(Ee.key)&&(Fe=Fe.slice().reverse()),["ArrowUp","ArrowDown"].includes(Ee.key)){const Ne=Ee.target,Be=Fe.indexOf(Ne);Fe=Fe.slice(Be+1)}setTimeout(()=>X(Fe)),Ee.preventDefault()}})})})})})})},"SelectContentImpl")),_Ms=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,onPlaced:a,...i}=t,l=s6(B7,r),o=DB(B7,r),[c,d]=j.useState(null),[u,h]=j.useState(null),m=Vo(n,h),f=SLe(r),g=j.useRef(!1),x=j.useRef(!0),{viewport:v,selectedItem:y,selectedItemText:b,focusSelectedItem:w}=o,S=j.useCallback(()=>{if(l.trigger&&l.valueNode&&c&&u&&v&&y&&b){const P=l.trigger.getBoundingClientRect(),R=u.getBoundingClientRect(),D=l.valueNode.getBoundingClientRect(),O=b.getBoundingClientRect();if(l.dir!=="rtl"){const Ne=O.left-R.left,Be=D.left-Ne,Se=P.left-Be,Ae=P.width+Se,Ce=Math.max(Ae,R.width),qe=window.innerWidth-lS,ze=gG(Be,[lS,Math.max(lS,qe-Ce)]);c.style.minWidth=Ae+"px",c.style.left=ze+"px"}else{const Ne=R.right-O.right,Be=window.innerWidth-D.right-Ne,Se=window.innerWidth-P.right-Be,Ae=P.width+Se,Ce=Math.max(Ae,R.width),qe=window.innerWidth-lS,ze=gG(Be,[lS,Math.max(lS,qe-Ce)]);c.style.minWidth=Ae+"px",c.style.right=ze+"px"}const U=f(),W=window.innerHeight-lS*2,V=v.scrollHeight,G=window.getComputedStyle(u),Z=parseInt(G.borderTopWidth,10),X=parseInt(G.paddingTop,10),ae=parseInt(G.borderBottomWidth,10),le=parseInt(G.paddingBottom,10),re=Z+X+V+le+ae,te=Math.min(y.offsetHeight*5,re),J=window.getComputedStyle(v),ce=parseInt(J.paddingTop,10),ve=parseInt(J.paddingBottom,10),fe=P.top+P.height/2-lS,ue=W-fe,be=y.offsetHeight/2,Ee=y.offsetTop+be,ke=Z+X+Ee,Ie=re-ke;if(ke<=fe){const Ne=U.length>0&&y===U[U.length-1].ref.current;c.style.bottom="0px";const Be=u.clientHeight-v.offsetTop-v.offsetHeight,Se=Math.max(ue,be+(Ne?ve:0)+Be+ae),Ae=ke+Se;c.style.height=Ae+"px"}else{const Ne=U.length>0&&y===U[0].ref.current;c.style.top="0px";const Se=Math.max(fe,Z+v.offsetTop+(Ne?ce:0)+be)+Ie;c.style.height=Se+"px",v.scrollTop=ke-fe+v.offsetTop}c.style.margin=`${lS}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,v,y,b,l.dir,a]);Af(()=>S(),[S]);const[A,E]=j.useState();Af(()=>{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(wMs,{scope:r,contentWrapper:c,shouldExpandOnScrollRef:g,onScrollButtonChange:I,children:e.jsx("div",{ref:d,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:A},children:e.jsx(Ei.div,{...i,ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})},"SelectItemAlignedPosition")),hyt=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,align:a="start",collisionPadding:i=lS,...l}=t,o=dtt(r);return e.jsx(wae,{...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")),[wMs,utt]=RB(B7,{}),myt="SelectViewport",jMs=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,nonce:a,...i}=t,l=DB(myt,r),o=utt(myt,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(kLe.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-lS*2,v=parseFloat(m.style.minHeight),y=parseFloat(m.style.height),b=Math.max(v,y);if(b0?A:0,m.style.justifyContent="flex-end")}}}d.current=h.scrollTop})})})]})},"SelectViewport")),NMs="SelectGroup",[kMs,SMs]=RB(NMs),CMs=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,...a}=t,i=cy();return e.jsx(kMs,{scope:r,id:i,children:e.jsx(Ei.div,{role:"group","aria-labelledby":i,...a,ref:n})})},"SelectGroup")),AMs="SelectLabel",rzt=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,...a}=t,i=SMs(AMs,r);return e.jsx(Ei.div,{id:i.id,...a,ref:n})},"SelectLabel")),zHe="SelectItem",[EMs,azt]=RB(zHe),izt=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,value:a,disabled:i=!1,textValue:l,...o}=t,c=s6(zHe,r),d=DB(zHe,r),u=c.value===a,[h,m]=j.useState(l??""),[f,g]=j.useState(!1),x=Kp(S=>{var A;return(A=d.itemRefCallback)==null?void 0:A.call(d,S,a,i)}),v=Vo(n,x),y=cy(),b=j.useRef("touch"),w=Ru(()=>{i||(c.onValueChange(a),c.onOpenChange(!1))},"handleSelect");return e.jsx(EMs,{scope:r,value:a,disabled:i,textId:y,isSelected:u,onItemTextChange:j.useCallback(S=>{m(A=>A||((S==null?void 0:S.textContent)??"").trim())},[]),children:e.jsx(kLe.ItemSlot,{scope:r,value:a,disabled:i,textValue:h,children:e.jsx(Ei.div,{role:"option","aria-labelledby":y,"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:v,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 A;b.current=S.pointerType,i?(A=d.onItemLeave)==null||A.call(d):b.current==="mouse"&&S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ra(o.onPointerLeave,S=>{var A;S.currentTarget===document.activeElement&&((A=d.onItemLeave)==null||A.call(d))}),onKeyDown:Ra(o.onKeyDown,S=>{var E;i||S.target!==S.currentTarget||((E=d.searchRef)==null?void 0:E.current)!==""&&S.key===" "||(rMs.includes(S.key)&&w(),S.key===" "&&S.preventDefault())})})})})},"SelectItem")),Tce="SelectItemText",TMs=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,className:a,style:i,...l}=t,o=s6(Tce,r),c=DB(Tce,r),d=azt(Tce,r),u=lMs(Tce,r),[h,m]=j.useState(null),f=Kp(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,v=j.useMemo(()=>e.jsx("option",{value:d.value,disabled:d.disabled,children:x},d.value),[d.disabled,d.value,x]),{onNativeOptionAdd:y,onNativeOptionRemove:b}=u;return Af(()=>(y(v),()=>b(v)),[y,b,v]),e.jsxs(e.Fragment,{children:[e.jsx(Ei.span,{id:d.textId,...l,ref:g}),d.isSelected&&o.valueNode&&!o.valueNodeHasChildren&&!Rae(o.value)?yv.createPortal(l.children,o.valueNode):null]})},"SelectItemText")),MMs="SelectItemIndicator",PMs=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,...a}=t;return azt(MMs,r).isSelected?e.jsx(Ei.span,{"aria-hidden":!0,...a,ref:n}):null},"SelectItemIndicator")),fyt="SelectScrollUpButton",ozt=j.forwardRef(Ru(function(t,n){const r=DB(fyt,t.__scopeSelect),a=utt(fyt,t.__scopeSelect),[i,l]=j.useState(!1),o=Vo(n,a.onScrollButtonChange);return Af(()=>{if(r.viewport&&r.isPositioned){let c=function(){const u=d.scrollTop>0;l(u)};Ru(c,"handleScroll");const d=r.viewport;return c(),d.addEventListener("scroll",c),()=>d.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),i?e.jsx(czt,{...t,ref:o,onAutoScroll:()=>{const{viewport:c,selectedItem:d}=r;c&&d&&(c.scrollTop=c.scrollTop-d.offsetHeight)}}):null},"SelectScrollUpButton")),pyt="SelectScrollDownButton",lzt=j.forwardRef(Ru(function(t,n){const r=DB(pyt,t.__scopeSelect),a=utt(pyt,t.__scopeSelect),[i,l]=j.useState(!1),o=Vo(n,a.onScrollButtonChange);return Af(()=>{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(czt,{...t,ref:o,onAutoScroll:()=>{const{viewport:c,selectedItem:d}=r;c&&d&&(c.scrollTop=c.scrollTop+d.offsetHeight)}}):null},"SelectScrollDownButton")),czt=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,onAutoScroll:a,...i}=t,l=DB("SelectScrollButton",r),o=j.useRef(null),c=SLe(r),d=j.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return j.useEffect(()=>()=>d(),[d]),Af(()=>{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")),dzt=j.forwardRef(Ru(function(t,n){const{__scopeSelect:r,...a}=t;return e.jsx(Ei.div,{"aria-hidden":!0,...a,ref:n})},"SelectSeparator")),IMs="SelectBubbleInput",LMs=j.forwardRef(Ru(function({__scopeSelect:t,...n},r){const a=s6(IMs,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),v=i??"",y=ctt(v),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(y!==v&&E){const I=new Event("change",{bubbles:!0});E.call(w,v),w.dispatchEvent(I)}},[y,v]),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:{...oRt,...n.style},ref:x,defaultValue:v,children:[Rae(i)&&!b?e.jsx("option",{value:""}):null,Array.from(m)]},f)},"SelectBubbleInput"));function uzt(s){return typeof s=="function"}Ru(uzt,"isFunction");function Rae(s){return s===""||s===void 0}Ru(Rae,"shouldShowPlaceholder");function htt(s){const t=Kp(s),n=j.useRef(""),r=j.useRef(0),a=j.useCallback(l=>{const o=n.current+l;t(o),Ru(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]}Ru(htt,"useTypeaheadSearch");function mtt(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=hzt(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}Ru(mtt,"findNextItem");function hzt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}Ru(hzt,"wrapArray");const ms=cMs,RMs=CMs,fs=hMs,us=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(tzt,{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(mMs,{asChild:!0,children:e.jsx(wl,{className:"h-4 w-4 opacity-50"})})]}));us.displayName=tzt.displayName;const mzt=j.forwardRef(({className:s,...t},n)=>e.jsx(ozt,{ref:n,className:Pt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(xb,{className:"h-4 w-4"})}));mzt.displayName=ozt.displayName;const fzt=j.forwardRef(({className:s,...t},n)=>e.jsx(lzt,{ref:n,className:Pt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(wl,{className:"h-4 w-4"})}));fzt.displayName=lzt.displayName;const hs=j.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx(xMs,{children:e.jsxs(szt,{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(mzt,{}),e.jsx(jMs,{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(fzt,{})]})}));hs.displayName=szt.displayName;const pzt=j.forwardRef(({className:s,...t},n)=>e.jsx(rzt,{ref:n,className:Pt("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));pzt.displayName=rzt.displayName;const Ge=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(izt,{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(PMs,{children:e.jsx(ma,{className:"h-4 w-4"})})}),e.jsx(TMs,{children:t})]}));Ge.displayName=izt.displayName;const DMs=j.forwardRef(({className:s,...t},n)=>e.jsx(dzt,{ref:n,className:Pt("-mx-1 my-1 h-px bg-muted",s),...t}));DMs.displayName=dzt.displayName;const FMs=F2({category:ltt(["general","technology","crm","marketing"]),subject:yl().min(5,"Subject must be at least 5 characters").max(200),description:yl().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),OMs={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function BHe({trigger:s}){const[t,n]=j.useState(!1),[r,a]=j.useState(!1),{user:i}=_s(),l=yLe({resolver:vLe(FMs),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){ne.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:OMs[c.category],subject:c.subject}})}catch(u){console.log("Notification send attempted:",u)}ne.success("Support ticket submitted successfully!"),l.reset(),n(!1)}catch(d){console.error("Error submitting ticket:",d),ne.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(Os,{open:t,onOpenChange:n,children:[e.jsx(jl,{asChild:!0,children:s||e.jsxs($,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(LJ,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(Fs,{className:"sm:max-w-[500px]",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Need Help?"}),e.jsx(Er,{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(jLe,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(_g,{control:l.control,name:"category",render:({field:c})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Category"}),e.jsxs(ms,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(Up,{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(m_,{})]})}),e.jsx(_g,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Subject"}),e.jsx(Up,{children:e.jsx(pe,{placeholder:"Brief description of your issue",...c})}),e.jsx(m_,{})]})}),e.jsx(_g,{control:l.control,name:"description",render:({field:c})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Description"}),e.jsx(Up,{children:e.jsx(Rs,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(m_,{})]})}),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 Em(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function Am(s,t){const n=So(s);return isNaN(t)?Em(s,NaN):(t&&n.setDate(n.getDate()+t),n)}function Av(s,t){const n=So(s);if(isNaN(t))return Em(s,NaN);if(!t)return n;const r=n.getDate(),a=Em(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 gzt(s,t){const n=+So(s);return Em(s,n+t)}const ftt=6048e5,zMs=864e5,CLe=6e4,ALe=36e5,BMs=1e3,Mce=43200,gyt=1440;function xyt(s,t){return gzt(s,t*ALe)}let $Ms={};function n6(){return $Ms}function w1(s,t){var o,c,d,u;const n=n6(),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 Eg(s){const t=So(s);return t.setHours(0,0,0,0),t}function NL(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 db(s,t){const n=Eg(s),r=Eg(t),a=+n-NL(n),i=+r-NL(r);return Math.round((a-i)/zMs)}function UMs(s){const t=xzt(s),n=Em(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),dT(n)}function yyt(s,t){return gzt(s,t*CLe)}function s8(s,t){const n=t*7;return Am(s,n)}function qMs(s,t){return Av(s,t*12)}function VMs(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 G4e(s,t){const n=So(s),r=So(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function ELe(s){return Em(s,Date.now())}function sf(s,t){const n=Eg(s),r=Eg(t);return+n==+r}function ptt(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function $He(s){if(!ptt(s)&&typeof s!="number")return!1;const t=So(s);return!isNaN(Number(t))}function wG(s,t){const n=So(s),r=So(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function GMs(s,t,n){const r=w1(s,n),a=w1(t,n),i=+r-NL(r),l=+a-NL(a);return Math.round((i-l)/ftt)}function ck(s,t){const n=So(s),r=So(t),a=vyt(n,r),i=Math.abs(db(n,r));n.setDate(n.getDate()-a*i);const l=+(vyt(n,r)===-a),o=a*(i-l);return o===0?0:o}function vyt(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 WMs(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function KMs(s,t){return+So(s)-+So(t)}function YMs(s){const t=So(s);return t.setHours(23,59,59,999),t}function uw(s){const t=So(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function ZMs(s){const t=So(s);return+YMs(t)==+uw(t)}function XMs(s,t){const n=So(s),r=So(t),a=G4e(n,r),i=Math.abs(wG(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=G4e(n,r)===-a;ZMs(So(s))&&i===1&&G4e(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function QMs(s,t,n){const r=KMs(s,t)/1e3;return WMs(n==null?void 0:n.roundingMethod)(r)}function JMs(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 ePs(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 Zm(s){const t=So(s);return t.setDate(1),t.setHours(0,0,0,0),t}function gtt(s){const t=So(s),n=Em(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function TLe(s,t){var o,c,d,u;const n=n6(),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=tPs[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 Xze(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const nPs={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},rPs={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},aPs={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},iPs={date:Xze({formats:nPs,defaultWidth:"full"}),time:Xze({formats:rPs,defaultWidth:"full"}),dateTime:Xze({formats:aPs,defaultWidth:"full"})},oPs={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},lPs=(s,t,n,r)=>oPs[s];function bZ(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 cPs={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},dPs={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},uPs={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"]},hPs={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"]},mPs={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"}},fPs={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"}},pPs=(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"},gPs={ordinalNumber:pPs,era:bZ({values:cPs,defaultWidth:"wide"}),quarter:bZ({values:dPs,defaultWidth:"wide",argumentCallback:s=>s-1}),month:bZ({values:uPs,defaultWidth:"wide"}),day:bZ({values:hPs,defaultWidth:"wide"}),dayPeriod:bZ({values:mPs,defaultWidth:"wide",formattingValues:fPs,defaultFormattingWidth:"wide"})};function _Z(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)?yPs(o,h=>h.test(l)):xPs(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 xPs(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function yPs(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 bPs=/^(\d+)(th|st|nd|rd)?/i,_Ps=/\d+/i,wPs={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},jPs={any:[/^b/i,/^(a|c)/i]},NPs={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},kPs={any:[/1/i,/2/i,/3/i,/4/i]},SPs={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},CPs={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]},APs={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},EPs={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]},TPs={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},MPs={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}},PPs={ordinalNumber:vPs({matchPattern:bPs,parsePattern:_Ps,valueCallback:s=>parseInt(s,10)}),era:_Z({matchPatterns:wPs,defaultMatchWidth:"wide",parsePatterns:jPs,defaultParseWidth:"any"}),quarter:_Z({matchPatterns:NPs,defaultMatchWidth:"wide",parsePatterns:kPs,defaultParseWidth:"any",valueCallback:s=>s+1}),month:_Z({matchPatterns:SPs,defaultMatchWidth:"wide",parsePatterns:CPs,defaultParseWidth:"any"}),day:_Z({matchPatterns:APs,defaultMatchWidth:"wide",parsePatterns:EPs,defaultParseWidth:"any"}),dayPeriod:_Z({matchPatterns:TPs,defaultMatchWidth:"any",parsePatterns:MPs,defaultParseWidth:"any"})},MLe={code:"en-US",formatDistance:sPs,formatLong:iPs,formatRelative:lPs,localize:gPs,match:PPs,options:{weekStartsOn:0,firstWeekContainsDate:1}};function IPs(s){const t=So(s);return db(t,gtt(t))+1}function xtt(s){const t=So(s),n=+dT(t)-+UMs(t);return Math.round(n/ftt)+1}function ytt(s,t){var u,h,m,f;const n=So(s),r=n.getFullYear(),a=n6(),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=Em(s,0);l.setFullYear(r+1,0,i),l.setHours(0,0,0,0);const o=w1(l,t),c=Em(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=w1(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function LPs(s,t){var o,c,d,u;const n=n6(),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=ytt(s,t),i=Em(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),w1(i,t)}function vtt(s,t){const n=So(s),r=+w1(n,t)-+LPs(n,t);return Math.round(r/ftt)+1}function Sm(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const xM={y(s,t){const n=s.getFullYear(),r=n>0?n:1-n;return Sm(t==="yy"?r%100:r,t.length)},M(s,t){const n=s.getMonth();return t==="M"?String(n+1):Sm(n+1,2)},d(s,t){return Sm(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 Sm(s.getHours()%12||12,t.length)},H(s,t){return Sm(s.getHours(),t.length)},m(s,t){return Sm(s.getMinutes(),t.length)},s(s,t){return Sm(s.getSeconds(),t.length)},S(s,t){const n=t.length,r=s.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return Sm(a,t.length)}},p$={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},byt={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 xM.y(s,t)},Y:function(s,t,n,r){const a=ytt(s,r),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return Sm(l,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):Sm(i,t.length)},R:function(s,t){const n=xzt(s);return Sm(n,t.length)},u:function(s,t){const n=s.getFullYear();return Sm(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 Sm(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 Sm(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 xM.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 Sm(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=vtt(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):Sm(a,t.length)},I:function(s,t,n){const r=xtt(s);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Sm(r,t.length)},d:function(s,t,n){return t==="do"?n.ordinalNumber(s.getDate(),{unit:"date"}):xM.d(s,t)},D:function(s,t,n){const r=IPs(s);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Sm(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 Sm(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 Sm(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 Sm(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=p$.noon:r===0?a=p$.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=p$.evening:r>=12?a=p$.afternoon:r>=4?a=p$.morning:a=p$.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 xM.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):xM.H(s,t)},K:function(s,t,n){const r=s.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Sm(r,t.length)},k:function(s,t,n){let r=s.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Sm(r,t.length)},m:function(s,t,n){return t==="mo"?n.ordinalNumber(s.getMinutes(),{unit:"minute"}):xM.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):xM.s(s,t)},S:function(s,t){return xM.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return wyt(r);case"XXXX":case"XX":return EO(r);case"XXXXX":case"XXX":default:return EO(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return wyt(r);case"xxxx":case"xx":return EO(r);case"xxxxx":case"xxx":default:return EO(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+_yt(r,":");case"OOOO":default:return"GMT"+EO(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+_yt(r,":");case"zzzz":default:return"GMT"+EO(r,":")}},t:function(s,t,n){const r=Math.trunc(s.getTime()/1e3);return Sm(r,t.length)},T:function(s,t,n){const r=s.getTime();return Sm(r,t.length)}};function _yt(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+Sm(i,2)}function wyt(s,t){return s%60===0?(s>0?"-":"+")+Sm(Math.abs(s)/60,2):EO(s,t)}function EO(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=Sm(Math.trunc(r/60),2),i=Sm(r%60,2);return n+a+t+i}const jyt=(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"})}},vzt=(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"})}},RPs=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return jyt(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}}",jyt(r,t)).replace("{{time}}",vzt(a,t))},UHe={p:vzt,P:RPs},DPs=/^D+$/,FPs=/^Y+$/,OPs=["D","DD","YY","YYYY"];function bzt(s){return DPs.test(s)}function _zt(s){return FPs.test(s)}function qHe(s,t,n){const r=zPs(s,t,n);if(console.warn(r),OPs.includes(s))throw new RangeError(r)}function zPs(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 BPs=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,$Ps=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,UPs=/^'([^]*?)'?$/,qPs=/''/g,VPs=/[a-zA-Z]/;function Js(s,t,n){var u,h,m,f,g,x,v,y;const r=n6(),a=(n==null?void 0:n.locale)??r.locale??MLe,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??((y=(v=r.locale)==null?void 0:v.options)==null?void 0:y.weekStartsOn)??0,o=So(s);if(!$He(o))throw new RangeError("Invalid time value");let c=t.match($Ps).map(b=>{const w=b[0];if(w==="p"||w==="P"){const S=UHe[w];return S(b,a.formatLong)}return b}).join("").match(BPs).map(b=>{if(b==="''")return{isToken:!1,value:"'"};const w=b[0];if(w==="'")return{isToken:!1,value:HPs(b)};if(byt[w])return{isToken:!0,value:b};if(w.match(VPs))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)&&_zt(w)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&bzt(w))&&qHe(w,t,String(s));const S=byt[w[0]];return S(o,w,a.localize,d)}).join("")}function HPs(s){const t=s.match(UPs);return t?t[1].replace(qPs,"'"):s}function GPs(s,t,n){const r=n6(),a=(n==null?void 0:n.locale)??r.locale??MLe,i=2520,l=G4e(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=QMs(d,c),h=(NL(d)-NL(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 nC(s,t){const n=So(s),r=So(t);return+n<+r}function JPs(s){return+So(s)>Date.now()}function eIs(s,t){const n=t instanceof Date?Em(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 tIs=10;class wzt{constructor(){_r(this,"subPriority",0)}validate(t,n){return!0}}class sIs extends wzt{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 nIs extends wzt{constructor(){super(...arguments);_r(this,"priority",tIs);_r(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:Em(n,eIs(n,Date))}}class om{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 rIs extends om{constructor(){super(...arguments);_r(this,"priority",140);_r(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 iy={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}/},o4={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 oy(s,t){return s&&{value:t(s.value),rest:s.rest}}function Sg(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function l4(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*ALe+i*CLe+l*BMs),rest:t.slice(n[0].length)}}function jzt(s){return Sg(iy.anyDigitsSigned,s)}function Cx(s,t){switch(s){case 1:return Sg(iy.singleDigit,t);case 2:return Sg(iy.twoDigits,t);case 3:return Sg(iy.threeDigits,t);case 4:return Sg(iy.fourDigits,t);default:return Sg(new RegExp("^\\d{1,"+s+"}"),t)}}function kEe(s,t){switch(s){case 1:return Sg(iy.singleDigitSigned,t);case 2:return Sg(iy.twoDigitsSigned,t);case 3:return Sg(iy.threeDigitsSigned,t);case 4:return Sg(iy.fourDigitsSigned,t);default:return Sg(new RegExp("^-?\\d{1,"+s+"}"),t)}}function btt(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 Nzt(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 kzt(s){return s%400===0||s%4===0&&s%100!==0}class aIs extends om{constructor(){super(...arguments);_r(this,"priority",130);_r(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 oy(Cx(4,n),i);case"yo":return oy(a.ordinalNumber(n,{unit:"year"}),i);default:return oy(Cx(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=Nzt(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 iIs extends om{constructor(){super(...arguments);_r(this,"priority",130);_r(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 oy(Cx(4,n),i);case"Yo":return oy(a.ordinalNumber(n,{unit:"year"}),i);default:return oy(Cx(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=ytt(n,i);if(a.isTwoDigitYear){const c=Nzt(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),w1(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),w1(n,i)}}class oIs extends om{constructor(){super(...arguments);_r(this,"priority",130);_r(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(n,r){return kEe(r==="R"?4:r.length,n)}set(n,r,a){const i=Em(n,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),dT(i)}}class lIs extends om{constructor(){super(...arguments);_r(this,"priority",130);_r(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(n,r){return kEe(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class cIs extends om{constructor(){super(...arguments);_r(this,"priority",120);_r(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 Cx(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 dIs extends om{constructor(){super(...arguments);_r(this,"priority",120);_r(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 Cx(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 uIs extends om{constructor(){super(...arguments);_r(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);_r(this,"priority",110)}parse(n,r,a){const i=l=>l-1;switch(r){case"M":return oy(Sg(iy.month,n),i);case"MM":return oy(Cx(2,n),i);case"Mo":return oy(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 hIs extends om{constructor(){super(...arguments);_r(this,"priority",110);_r(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 oy(Sg(iy.month,n),i);case"LL":return oy(Cx(2,n),i);case"Lo":return oy(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 mIs(s,t,n){const r=So(s),a=vtt(r,n)-t;return r.setDate(r.getDate()-a*7),r}class fIs extends om{constructor(){super(...arguments);_r(this,"priority",100);_r(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(n,r,a){switch(r){case"w":return Sg(iy.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return Cx(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return w1(mIs(n,a,i),i)}}function pIs(s,t){const n=So(s),r=xtt(n)-t;return n.setDate(n.getDate()-r*7),n}class gIs extends om{constructor(){super(...arguments);_r(this,"priority",100);_r(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 Sg(iy.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return Cx(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return dT(pIs(n,a))}}const xIs=[31,28,31,30,31,30,31,31,30,31,30,31],yIs=[31,29,31,30,31,30,31,31,30,31,30,31];class vIs extends om{constructor(){super(...arguments);_r(this,"priority",90);_r(this,"subPriority",1);_r(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"d":return Sg(iy.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return Cx(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=kzt(a),l=n.getMonth();return i?r>=1&&r<=yIs[l]:r>=1&&r<=xIs[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class bIs extends om{constructor(){super(...arguments);_r(this,"priority",90);_r(this,"subpriority",1);_r(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 Sg(iy.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return Cx(r.length,n)}}validate(n,r){const a=n.getFullYear();return kzt(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 _tt(s,t,n){var h,m,f,g;const r=n6(),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 Am(i,u)}class _Is extends om{constructor(){super(...arguments);_r(this,"priority",90);_r(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=_tt(n,a,i),n.setHours(0,0,0,0),n}}class wIs extends om{constructor(){super(...arguments);_r(this,"priority",90);_r(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 oy(Cx(r.length,n),l);case"eo":return oy(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=_tt(n,a,i),n.setHours(0,0,0,0),n}}class jIs extends om{constructor(){super(...arguments);_r(this,"priority",90);_r(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 oy(Cx(r.length,n),l);case"co":return oy(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=_tt(n,a,i),n.setHours(0,0,0,0),n}}function NIs(s,t){const n=So(s),r=YPs(n),a=t-r;return Am(n,a)}class kIs extends om{constructor(){super(...arguments);_r(this,"priority",90);_r(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 Cx(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return oy(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 oy(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return oy(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return oy(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=NIs(n,a),n.setHours(0,0,0,0),n}}class SIs extends om{constructor(){super(...arguments);_r(this,"priority",80);_r(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(btt(a),0,0,0),n}}class CIs extends om{constructor(){super(...arguments);_r(this,"priority",80);_r(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(btt(a),0,0,0),n}}class AIs extends om{constructor(){super(...arguments);_r(this,"priority",80);_r(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(btt(a),0,0,0),n}}class EIs extends om{constructor(){super(...arguments);_r(this,"priority",70);_r(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return Sg(iy.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return Cx(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 TIs extends om{constructor(){super(...arguments);_r(this,"priority",70);_r(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(n,r,a){switch(r){case"H":return Sg(iy.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return Cx(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class MIs extends om{constructor(){super(...arguments);_r(this,"priority",70);_r(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return Sg(iy.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return Cx(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 PIs extends om{constructor(){super(...arguments);_r(this,"priority",70);_r(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(n,r,a){switch(r){case"k":return Sg(iy.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return Cx(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 IIs extends om{constructor(){super(...arguments);_r(this,"priority",60);_r(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return Sg(iy.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return Cx(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class LIs extends om{constructor(){super(...arguments);_r(this,"priority",50);_r(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return Sg(iy.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return Cx(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class RIs extends om{constructor(){super(...arguments);_r(this,"priority",30);_r(this,"incompatibleTokens",["t","T"])}parse(n,r){const a=i=>Math.trunc(i*Math.pow(10,-r.length+3));return oy(Cx(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class DIs extends om{constructor(){super(...arguments);_r(this,"priority",10);_r(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return l4(o4.basicOptionalMinutes,n);case"XX":return l4(o4.basic,n);case"XXXX":return l4(o4.basicOptionalSeconds,n);case"XXXXX":return l4(o4.extendedOptionalSeconds,n);case"XXX":default:return l4(o4.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Em(n,n.getTime()-NL(n)-a)}}class FIs extends om{constructor(){super(...arguments);_r(this,"priority",10);_r(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return l4(o4.basicOptionalMinutes,n);case"xx":return l4(o4.basic,n);case"xxxx":return l4(o4.basicOptionalSeconds,n);case"xxxxx":return l4(o4.extendedOptionalSeconds,n);case"xxx":default:return l4(o4.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Em(n,n.getTime()-NL(n)-a)}}class OIs extends om{constructor(){super(...arguments);_r(this,"priority",40);_r(this,"incompatibleTokens","*")}parse(n){return jzt(n)}set(n,r,a){return[Em(n,a*1e3),{timestampIsSet:!0}]}}class zIs extends om{constructor(){super(...arguments);_r(this,"priority",20);_r(this,"incompatibleTokens","*")}parse(n){return jzt(n)}set(n,r,a){return[Em(n,a),{timestampIsSet:!0}]}}const BIs={G:new rIs,y:new aIs,Y:new iIs,R:new oIs,u:new lIs,Q:new cIs,q:new dIs,M:new uIs,L:new hIs,w:new fIs,I:new gIs,d:new vIs,D:new bIs,E:new _Is,e:new wIs,c:new jIs,i:new kIs,a:new SIs,b:new CIs,B:new AIs,h:new EIs,H:new TIs,K:new MIs,k:new PIs,m:new IIs,s:new LIs,S:new RIs,X:new DIs,x:new FIs,t:new OIs,T:new zIs},$Is=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,UIs=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,qIs=/^'([^]*?)'?$/,VIs=/''/g,HIs=/\S/,GIs=/[a-zA-Z]/;function wtt(s,t,n,r){var x,v,y,b;const a=KPs(),i=a.locale??MLe,l=a.firstWeekContainsDate??((v=(x=a.locale)==null?void 0:x.options)==null?void 0:v.firstWeekContainsDate)??1,o=a.weekStartsOn??((b=(y=a.locale)==null?void 0:y.options)==null?void 0:b.weekStartsOn)??0;if(t==="")return s===""?So(n):Em(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new nIs],u=t.match(UIs).map(w=>{const S=w[0];if(S in UHe){const A=UHe[S];return A(w,i.formatLong)}return w}).join("").match($Is),h=[];for(let w of u){_zt(w)&&qHe(w,t,s),bzt(w)&&qHe(w,t,s);const S=w[0],A=BIs[S];if(A){const{incompatibleTokens:E}=A;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(A.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=A.run(s,w,i.match,c);if(!I)return Em(n,NaN);d.push(I.setter),s=I.rest}else{if(S.match(GIs))throw new RangeError("Format string contains an unescaped latin alphabet character `"+S+"`");if(w==="''"?w="'":S==="'"&&(w=WIs(w)),s.indexOf(w)===0)s=s.slice(w.length);else return Em(n,NaN)}}if(s.length>0&&HIs.test(s))return Em(n,NaN);const m=d.map(w=>w.priority).sort((w,S)=>S-w).filter((w,S,A)=>A.indexOf(w)===S).map(w=>d.filter(S=>S.priority===w).sort((S,A)=>A.subPriority-S.subPriority)).map(w=>w[0]);let f=So(n);if(isNaN(f.getTime()))return Em(n,NaN);const g={};for(const w of m){if(!w.validate(f,c))return Em(n,NaN);const S=w.set(f,g,c);Array.isArray(S)?(f=S[0],Object.assign(g,S[1])):f=S}return Em(n,f)}function WIs(s){return s.match(qIs)[1].replace(VIs,"'")}function R4(s){return+So(s)i-l);return n>=r&&n<=a}function W4e(s,t){return Am(s,-t)}function pv(s,t){const r=tLs(s);let a;if(r.date){const c=sLs(r.date,2);a=nLs(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=rLs(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=aLs(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 Pce={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},QIs=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,JIs=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,eLs=/^([+-])(\d{2})(?::?(\d{2}))?$/;function tLs(s){const t={},n=s.split(Pce.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],Pce.timeZoneDelimiter.test(t.date)&&(t.date=s.split(Pce.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=Pce.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 nLs(s,t){if(t===null)return new Date(NaN);const n=s.match(QIs);if(!n)return new Date(NaN);const r=!!n[4],a=wZ(n[1]),i=wZ(n[2])-1,l=wZ(n[3]),o=wZ(n[4]),c=wZ(n[5])-1;if(r)return dLs(t,o,c)?iLs(t,o,c):new Date(NaN);{const d=new Date(0);return!lLs(t,i,l)||!cLs(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function wZ(s){return s?parseInt(s):1}function rLs(s){const t=s.match(JIs);if(!t)return NaN;const n=Qze(t[1]),r=Qze(t[2]),a=Qze(t[3]);return uLs(n,r,a)?n*ALe+r*CLe+a*1e3:NaN}function Qze(s){return s&&parseFloat(s.replace(",","."))||0}function aLs(s){if(s==="Z")return 0;const t=s.match(eLs);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return hLs(r,a)?n*(r*ALe+a*CLe):NaN}function iLs(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 oLs=[31,null,31,30,31,30,31,31,30,31,30,31];function Szt(s){return s%400===0||s%4===0&&s%100!==0}function lLs(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(oLs[t]||(Szt(s)?29:28))}function cLs(s,t){return t>=1&&t<=(Szt(s)?366:365)}function dLs(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function uLs(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function hLs(s,t){return t>=0&&t<=59}function Jze(s,t){const n=So(s),r=n.getFullYear(),a=n.getDate(),i=Em(s,0);i.setFullYear(r,t,15),i.setHours(0,0,0,0);const l=WPs(i);return n.setMonth(t,Math.min(a,l)),n}function Czt(s,t){const n=So(s);return n.setHours(t),n}function Azt(s,t){const n=So(s);return n.setMinutes(t),n}function kyt(s,t){const n=So(s);return isNaN(+n)?Em(s,NaN):(n.setFullYear(t),n)}function n8(s,t){return Av(s,-t)}const mLs=()=>{const{user:s}=_s(),t=Zn(),[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}`,v=localStorage.getItem(x);v&&!u.current&&(u.current=v,d(v));const y=`nb_cache_${s.id}`,b=60*1e3,w=async()=>{try{const P=sessionStorage.getItem(y);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 A=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(y,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(A)}},[s]);const h=x=>{const v=x.toLowerCase();return v.includes("community")||v.includes("post")?no:v.includes("academy")||v.includes("video")?fa:v.includes("template")?yd:v.includes("event")?Ea:v.includes("newsletter")?XN:v.includes("brokerage")?wx:v.includes("swag")||v.includes("social")?dl:v.includes("toolbox")||v.includes("tool")?I4:v.includes("brief")?wn:no},m=x=>{o(!1),x.url&&x.url!=="/"&&t(x.url)},f=()=>{if(!s)return;const x=new Date().toISOString(),v=`notification_last_read_${s.id}`;localStorage.setItem(v,x),d(x),i(0)},g=x=>{o(x),x&&a>0&&f()};return e.jsxs(Bu,{open:l,onOpenChange:g,children:[e.jsx($u,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(zy,{className:"h-5 w-5"}),a>0&&e.jsx($e,{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(Cu,{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(go,{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 v=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(v,{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:hu(new Date(x.created_at),{addSuffix:!0})})]})]},x.id)})})]})]})};function fLs(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function tg(){const{user:s}=_s(),{data:t,isLoading:n}=st({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 fLs(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 PLe(s=!0){const{user:t}=_s(),{data:n,isLoading:r}=st({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 pLs="coaching_access";function Ezt(){const{user:s,loading:t,isAdmin:n,isCoach:r}=_s(),{data:a,isLoading:i}=st({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",pLs).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 Du=q,SEe=[{value:"contract",label:"Under contract"},{value:"inspection",label:"Inspection / due diligence"},{value:"closing",label:"Closing"},{value:"closed",label:"Closed"}];function VHe(s){return s.total_items===0?"not_started":s.rejected_items>0?"changes_requested":s.approved_items>=s.total_items?"compliant":"in_review"}const Tzt={not_started:"Not started",in_review:"In review",changes_requested:"Changes requested",compliant:"Compliant"};function jtt(){return st({queryKey:["transaction-admin-seats"],queryFn:async()=>{const{data:s}=await q.auth.getUser();if(!s.user)return[];const{data:t,error:n}=await Du.from("brokerage_transaction_admins").select("brokerage_id").eq("user_id",s.user.id);if(n)throw n;return t||[]}})}function gLs(s){return st({queryKey:["transaction-admins",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Du.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 Du.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 xLs(){const s=Zt();return mt({mutationFn:async({brokerageId:t,userId:n})=>{const{error:r}=await Du.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 yLs(){const s=Zt();return mt({mutationFn:async({id:t})=>{const{error:n}=await Du.from("brokerage_transaction_admins").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["transaction-admins",n.brokerageId]})})}function vLs(s){return st({queryKey:["compliance-settings",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Du.from("brokerage_compliance_settings").select("*").eq("brokerage_id",s).maybeSingle();if(n)throw n;return t}})}function bLs(){const s=Zt();return mt({mutationFn:async t=>{const{error:n}=await Du.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 Mzt(s){return st({queryKey:["compliance-templates",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Du.from("brokerage_checklist_templates").select("*").eq("brokerage_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function _Ls(s){return st({queryKey:["compliance-template-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Du.from("brokerage_checklist_template_items").select("*").eq("template_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function wLs(){const s=Zt();return mt({mutationFn:async t=>{if(t.id){const{error:a}=await Du.from("brokerage_checklist_templates").update(t).eq("id",t.id);if(a)throw a;return t.id}const{data:n,error:r}=await Du.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 jLs(){const s=Zt();return mt({mutationFn:async({id:t})=>{const{error:n}=await Du.from("brokerage_checklist_templates").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-templates",n.brokerageId]})})}function NLs(){const s=Zt();return mt({mutationFn:async t=>{if(t.id){const{error:r}=await Du.from("brokerage_checklist_template_items").update(t).eq("id",t.id);if(r)throw r;return}const{error:n}=await Du.from("brokerage_checklist_template_items").insert(t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-template-items",n.template_id]})})}function kLs(){const s=Zt();return mt({mutationFn:async({id:t})=>{const{error:n}=await Du.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 Ntt(s){return st({queryKey:["compliance-deals",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Du.rpc("get_brokerage_compliance_deals",{_brokerage_id:s});if(n)throw n;return t||[]}})}function Pzt(s){return st({queryKey:["deal-compliance-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Du.from("deal_compliance_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function SLs(s){return st({queryKey:["deal-compliance-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Du.from("deal_compliance_events").select("*").eq("deal_id",s).order("created_at",{ascending:!1}).limit(200);if(n)throw n;return t||[]}})}async function ILe(s){var n;const{data:t}=await q.auth.getUser();await Du.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 CLs(){const s=Zt();return mt({mutationFn:async({item:t,status:n,note:r})=>{var l;const{data:a}=await q.auth.getUser(),{error:i}=await Du.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 ILe({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 ALs(){const s=Zt();return mt({mutationFn:async({dealId:t,brokerageId:n,templateId:r,deal:a})=>{const{data:i,error:l}=await Du.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 Du.from("deal_compliance_items").insert(c);if(d)throw d;await ILe({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 ELs(s){return st({queryKey:["deal-compliance-files",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Du.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 TLs(){const s=Zt();return mt({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 Du.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 Du.from("deal_files").update({is_current:!1}).eq("compliance_item_id",t.id);const{error:u}=await Du.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 Du.from("deal_compliance_items").update({status:"submitted",review_note:null,reviewed_at:null,reviewed_by:null}).eq("id",t.id),await ILe({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 Syt(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 MLs(s){return st({queryKey:["deal-compliance-messages",s],enabled:!!s,refetchInterval:3e4,queryFn:async()=>{const{data:t,error:n}=await Du.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 Du.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 PLs(){const s=Zt();return mt({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 Du.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 ILs(){const s=Zt();return mt({mutationFn:async({dealId:t,senderRole:n})=>{const{error:r}=await Du.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 LLs(s){return st({queryKey:["brokerage-agent-roster",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Du.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",s).order("name",{ascending:!0});if(n)throw n;return t||[]}})}function RLs(s){return st({queryKey:["agent-pipeline-stages",s],enabled:!!s,queryFn:async()=>{const t=async()=>{const{data:r,error:a}=await Du.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 Du.rpc("initialize_deal_pipeline_stages",{p_user_id:s});r||(n=await t())}return n}})}function DLs(){const s=Zt();return mt({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 Du.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 Du.rpc("ensure_deal_compliance",{_deal_id:i})}catch(l){console.error("ensure_deal_compliance failed",l)}return await ILe({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 LLe=[{id:"home",label:"Home",icon:HI,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:Jo,description:"Contacts and follow-up",accent:"nav-crm"},{id:"deals",label:"Deals",icon:i2,description:"Pipeline, transactions and tasks",accent:"nav-deals"},{id:"listings",label:"Listings",icon:wi,description:"Win and market listings",accent:"nav-listings"},{id:"marketing",label:"Marketing",icon:gm,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:cl,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:af,description:"Training, programs and coaching",accent:"nav-academy"},{id:"events",label:"Events",icon:Qz,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:Dj,route:"/apps",accent:"nav-apps"},{id:"team",label:"Team",icon:Yn,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:Dq,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:s=>!s.isAdmin&&(!!s.brokerageId||s.isBrokerageManager||s.isOnTeam)},{id:"more",label:"More",icon:o_,description:"Community, marketplace and help",accent:"nav-more"}],W1=s=>t=>t.hasPermission(s),FLs=[{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:A4,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:W1("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:wn,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:Yn,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:W1("contacts"),searchKeywords:["contacts","database","sphere","people"],displayOrder:30},{id:"relationship-report",label:"Relationship Report",route:"/mission-control/relationship-scorecard",icon:rf,description:"See who needs attention next",primaryCategory:"crm",section:"Contacts",visible:W1("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:Xq,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:W1("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:Zr,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:W1("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:nu,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:W1("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"property-intelligence",label:"Property Intelligence",route:"/mission-control/property-intelligence",icon:wi,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:Wc,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:W1("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:Qp,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:pn,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:Hq,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:dl,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:W1("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:i2,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:W1("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:GN,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:W1("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"forms",label:"Forms Library",route:"/mission-control/forms",icon:l_,description:"Your PDF form templates, filled from any deal",primaryCategory:"deals",section:"Pipeline",visible:W1("pipeline"),searchKeywords:["forms","pdf","templates","contracts","documents"],displayOrder:145},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:qj,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:W1("pipeline"),searchKeywords:["tasks","to do"],displayOrder:150},{id:"scorecard",label:"Scorecard",route:"/mission-control/scorecard",icon:Gl,description:"Your production numbers at a glance",primaryCategory:"deals",section:"Pipeline",visible:W1("scorecard"),searchKeywords:["scorecard","production","goals"],displayOrder:160},{id:"my-calendar",label:"My Calendar",route:"/mission-control/calendar",icon:Wc,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:Wc,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:wi,description:"Publish and browse member listings",primaryCategory:"listings",section:"Manage Listings",visible:W1("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:vb,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:sh,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:r2,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:GN,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:Hc,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:yd,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:Jq,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:ei,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:Hc,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:g1,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:g1,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:nf,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:XN,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:pn,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:"Direct Mail",route:"/mission-control/direct-mail",icon:Zr,description:"Send postcards to your farm",primaryCategory:"marketing",section:"Email & Mail",visible:s=>s.isAdmin,toolId:"direct-mail",searchKeywords:["postcard","direct mail","farming"],displayOrder:70},{id:"card-studio",label:"Card Studio",route:"/mission-control/card-studio",icon:dl,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:fa,description:"All of your recorded videos",primaryCategory:"marketing",section:"Video",visible:W1("videos"),searchKeywords:["videos","library"],displayOrder:90},{id:"quickvid",label:"QuickVid",route:"/mission-control/video/record",icon:fa,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:nf,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:By,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:yb,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:nu,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:Xf,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:cl,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:cl,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:Ta,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:pi,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:wi,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:Yn,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:Gl,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:rf,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:g1,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:wn,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:af,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:_x,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:I4,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:Qz,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:By,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:af,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:no,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:QS,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:Ir,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:eV,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:dl,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:Fq,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:wn,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:QN,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:QN,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:wn,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:jc,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:Qp,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:wi,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:t4,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:_x,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:Yn,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:Yn,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:Nd,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:Yn,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:gm,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:Fg,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:HI,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:Aw,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:Fg,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:yb,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:Qr,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:wx,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:wn,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:Fg,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 Izt(s,t){return typeof s.route=="function"?s.route(t):s.route}function Lzt(){const{user:s,isAdmin:t,isBrokerageManager:n,isCoach:r,brokerageId:a}=_s(),{hasPermission:i}=Sae(),{isInnerCircleEnabled:l,isMarketplaceEnabled:o,isFeatureEnabled:c}=Aae(),{hasAccess:d}=pLe(),{data:u,teams:h}=Ow(),{leadSite:m,hasLeadSite:f,siteUrl:g}=tg(),{hasOffer:x}=PLe(!f),v=bC(),{hasAccess:y}=Ezt(),{data:b}=jtt(),w=Zt(),{data:S}=st({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:A}=st({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(A||[]),[A]),I=mt({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(le=>le.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:v.isMember,hasCoachingOnboarding:v.isMember&&!!((X=v.pkg)!=null&&X.includes_coaching),hasCoachingAccess:!!y||v.isMember&&!!((ae=v.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,v.isMember,v.pkg,y]),R=j.useMemo(()=>FLs.filter(X=>X.visible?X.visible(P):!0).map(X=>{if(!v.isRestricted)return X;const ae=pCs(X);return!ae||v.hasFeature(ae)?X:{...X,locked:!0,route:`/upgrade/${ae}`}}).sort((X,ae)=>X.displayOrder-ae.displayOrder),[P,v.isRestricted,v.features]),D=j.useMemo(()=>LLe.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),le=[],re=new Map;for(const te of ae)re.has(te.section)||(re.set(te.section,[]),le.push(te.section)),re.get(te.section).push(te);return{id:X.id,label:X.label,sections:le.map(te=>({title:te,items:re.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(re=>{const te=re.label.toLowerCase(),J=(re.description||"").toLowerCase(),ce=(re.searchKeywords||[]).join(" ").toLowerCase();let ve=0;return te===ae?ve=100:te.startsWith(ae)?ve=80:te.includes(ae)?ve=60:ce.includes(ae)?ve=40:J.includes(ae)?ve=20:re.section.toLowerCase().includes(ae)&&(ve=10),ve&&V(re)&&(ve+=5),{d:re,score:ve}}).filter(re=>re.score>0).sort((re,te)=>te.score-re.score).map(re=>re.d):[]},routeFor:X=>Izt(X,P)}}var Cyt=1,OLs=.9,zLs=.8,BLs=.17,e7e=.1,t7e=.999,$Ls=.9999,ULs=.99,qLs=/[\\\/_+.#"@\[\(\{&]/,VLs=/[\\\/_+.#"@\[\(\{&]/g,HLs=/[\s-]/,Rzt=/[\s-]/g;function HHe(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?Cyt:ULs;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=HHe(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=Cyt:qLs.test(s.charAt(d-1))?(h*=zLs,f=s.slice(a,d-1).match(VLs),f&&a>0&&(h*=Math.pow(t7e,f.length))):HLs.test(s.charAt(d-1))?(h*=OLs,g=s.slice(a,d-1).match(Rzt),g&&a>0&&(h*=Math.pow(t7e,g.length))):(h*=BLs,a>0&&(h*=Math.pow(t7e,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=$Ls)),(hh&&(h=m*e7e)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function Ayt(s){return s.toLowerCase().replace(Rzt," ")}function GLs(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,HHe(s,t,Ayt(s),Ayt(t),0,0,{})}var jZ='[cmdk-group=""]',s7e='[cmdk-group-items=""]',WLs='[cmdk-group-heading=""]',Dzt='[cmdk-item=""]',Eyt=`${Dzt}:not([aria-disabled="true"])`,GHe="cmdk-item-select",dU="data-value",KLs=(s,t,n)=>GLs(s,t,n),Fzt=j.createContext(void 0),Fae=()=>j.useContext(Fzt),Ozt=j.createContext(void 0),ktt=()=>j.useContext(Ozt),zzt=j.createContext(void 0),Bzt=j.forwardRef((s,t)=>{let n=uU(()=>{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=uU(()=>new Set),a=uU(()=>new Map),i=uU(()=>new Map),l=uU(()=>new Set),o=$zt(s),{label:c,children:d,value:u,onValueChange:h,filter:m,shouldFilter:f,loop:g,disablePointerSelection:x=!1,vimBindings:v=!0,...y}=s,b=cy(),w=cy(),S=cy(),A=j.useRef(null),E=a6s();$7(()=>{if(u!==void 0){let J=u.trim();n.current.value=J,I.emit()}},[u]),$7(()=>{E(6,W)},[]);let I=j.useMemo(()=>({subscribe:J=>(l.current.add(J),()=>l.current.delete(J)),snapshot:()=>n.current,setState:(J,ce,ve)=>{var fe,ue,be,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 ke=document.getElementById(S);ke?ke.focus():(fe=document.getElementById(b))==null||fe.focus()}if(E(7,()=>{var ke;n.current.selectedItemId=(ke=V())==null?void 0:ke.id,I.emit()}),ve||E(5,W),((ue=o.current)==null?void 0:ue.value)!==void 0){let ke=ce??"";(Ee=(be=o.current).onValueChange)==null||Ee.call(be,ke);return}}I.emit()}},emit:()=>{l.current.forEach(J=>J())}}),[]),P=j.useMemo(()=>({value:(J,ce,ve)=>{var fe;ce!==((fe=i.current.get(J))==null?void 0:fe.value)&&(i.current.set(J,{value:ce,keywords:ve}),n.current.filtered.items.set(J,R(ce,ve)),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 ve=V();E(4,()=>{U(),(ve==null?void 0:ve.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:A}),[]);function R(J,ce){var ve,fe;let ue=(fe=(ve=o.current)==null?void 0:ve.filter)!=null?fe:KLs;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(fe=>{let ue=a.current.get(fe),be=0;ue.forEach(Ee=>{let ke=J.get(Ee);be=Math.max(ke,be)}),ce.push([fe,be])});let ve=A.current;G().sort((fe,ue)=>{var be,Ee;let ke=fe.getAttribute("id"),Ie=ue.getAttribute("id");return((be=J.get(Ie))!=null?be:0)-((Ee=J.get(ke))!=null?Ee:0)}).forEach(fe=>{let ue=fe.closest(s7e);ue?ue.appendChild(fe.parentElement===ue?fe:fe.closest(`${s7e} > *`)):ve.appendChild(fe.parentElement===ve?fe:fe.closest(`${s7e} > *`))}),ce.sort((fe,ue)=>ue[1]-fe[1]).forEach(fe=>{var ue;let be=(ue=A.current)==null?void 0:ue.querySelector(`${jZ}[${dU}="${encodeURIComponent(fe[0])}"]`);be==null||be.parentElement.appendChild(be)})}function O(){let J=G().find(ve=>ve.getAttribute("aria-disabled")!=="true"),ce=J==null?void 0:J.getAttribute(dU);I.setState("value",ce||void 0)}function U(){var J,ce,ve,fe;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 be of r.current){let Ee=(ce=(J=i.current.get(be))==null?void 0:J.value)!=null?ce:"",ke=(fe=(ve=i.current.get(be))==null?void 0:ve.keywords)!=null?fe:[],Ie=R(Ee,ke);n.current.filtered.items.set(be,Ie),Ie>0&&ue++}for(let[be,Ee]of a.current)for(let ke of Ee)if(n.current.filtered.items.get(ke)>0){n.current.filtered.groups.add(be);break}n.current.filtered.count=ue}function W(){var J,ce,ve;let fe=V();fe&&(((J=fe.parentElement)==null?void 0:J.firstChild)===fe&&((ve=(ce=fe.closest(jZ))==null?void 0:ce.querySelector(WLs))==null||ve.scrollIntoView({block:"nearest"})),fe.scrollIntoView({block:"nearest"}))}function V(){var J;return(J=A.current)==null?void 0:J.querySelector(`${Dzt}[aria-selected="true"]`)}function G(){var J;return Array.from(((J=A.current)==null?void 0:J.querySelectorAll(Eyt))||[])}function Z(J){let ce=G()[J];ce&&I.setState("value",ce.getAttribute(dU))}function X(J){var ce;let ve=V(),fe=G(),ue=fe.findIndex(Ee=>Ee===ve),be=fe[ue+J];(ce=o.current)!=null&&ce.loop&&(be=ue+J<0?fe[fe.length-1]:ue+J===fe.length?fe[0]:fe[ue+J]),be&&I.setState("value",be.getAttribute(dU))}function ae(J){let ce=V(),ve=ce==null?void 0:ce.closest(jZ),fe;for(;ve&&!fe;)ve=J>0?n6s(ve,jZ):r6s(ve,jZ),fe=ve==null?void 0:ve.querySelector(Eyt);fe?I.setState("value",fe.getAttribute(dU)):X(J)}let le=()=>Z(G().length-1),re=J=>{J.preventDefault(),J.metaKey?le():J.altKey?ae(1):X(1)},te=J=>{J.preventDefault(),J.metaKey?Z(0):J.altKey?ae(-1):X(-1)};return j.createElement(Ei.div,{ref:t,tabIndex:-1,...y,"cmdk-root":"",onKeyDown:J=>{var ce;(ce=y.onKeyDown)==null||ce.call(y,J);let ve=J.nativeEvent.isComposing||J.keyCode===229;if(!(J.defaultPrevented||ve))switch(J.key){case"n":case"j":{v&&J.ctrlKey&&re(J);break}case"ArrowDown":{re(J);break}case"p":case"k":{v&&J.ctrlKey&&te(J);break}case"ArrowUp":{te(J);break}case"Home":{J.preventDefault(),Z(0);break}case"End":{J.preventDefault(),le();break}case"Enter":{J.preventDefault();let fe=V();if(fe){let ue=new Event(GHe);fe.dispatchEvent(ue)}}}}},j.createElement("label",{"cmdk-label":"",htmlFor:P.inputId,id:P.labelId,style:o6s},c),RLe(s,J=>j.createElement(Ozt.Provider,{value:I},j.createElement(Fzt.Provider,{value:P},J))))}),YLs=j.forwardRef((s,t)=>{var n,r;let a=cy(),i=j.useRef(null),l=j.useContext(zzt),o=Fae(),c=$zt(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;$7(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=Uzt(a,i,[s.value,s.children,i],s.keywords),h=ktt(),m=kL(E=>E.value&&E.value===u.current),f=kL(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(GHe,g),()=>E.removeEventListener(GHe,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:v,value:y,onSelect:b,forceMount:w,keywords:S,...A}=s;return j.createElement(Ei.div,{ref:I7(i,t),...A,id:a,"cmdk-item":"",role:"option","aria-disabled":!!v,"aria-selected":!!m,"data-disabled":!!v,"data-selected":!!m,onPointerMove:v||o.getDisablePointerSelection()?void 0:x,onClick:v?void 0:g},s.children)}),ZLs=j.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=cy(),o=j.useRef(null),c=j.useRef(null),d=cy(),u=Fae(),h=kL(f=>a||u.filter()===!1?!0:f.search?f.filtered.groups.has(l):!0);$7(()=>u.group(l),[]),Uzt(l,o,[s.value,s.heading,c]);let m=j.useMemo(()=>({id:l,forceMount:a}),[a]);return j.createElement(Ei.div,{ref:I7(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),RLe(s,f=>j.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},j.createElement(zzt.Provider,{value:m},f))))}),XLs=j.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=j.useRef(null),i=kL(l=>!l.search);return!n&&!i?null:j.createElement(Ei.div,{ref:I7(a,t),...r,"cmdk-separator":"",role:"separator"})}),QLs=j.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=ktt(),l=kL(d=>d.search),o=kL(d=>d.selectedItemId),c=Fae();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)}})}),JLs=j.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=j.useRef(null),l=j.useRef(null),o=kL(d=>d.selectedItemId),c=Fae();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:I7(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},RLe(s,d=>j.createElement("div",{ref:I7(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),e6s=j.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return j.createElement(qIe,{open:n,onOpenChange:r},j.createElement(VIe,{container:l},j.createElement($W,{"cmdk-overlay":"",className:a}),j.createElement(UW,{"aria-label":s.label,"cmdk-dialog":"",className:i},j.createElement(Bzt,{ref:t,...o}))))}),t6s=j.forwardRef((s,t)=>kL(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},RLe(s,l=>j.createElement("div",{"aria-hidden":!0},l)))}),Bw=Object.assign(Bzt,{List:JLs,Item:YLs,Input:QLs,Group:ZLs,Separator:XLs,Dialog:e6s,Empty:t6s,Loading:s6s});function n6s(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function r6s(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function $zt(s){let t=j.useRef(s);return $7(()=>{t.current=s}),t}var $7=typeof window>"u"?j.useEffect:j.useLayoutEffect;function uU(s){let t=j.useRef();return t.current===void 0&&(t.current=s()),t}function kL(s){let t=ktt(),n=()=>s(t.snapshot());return j.useSyncExternalStore(t.subscribe,n,n)}function Uzt(s,t,n,r=[]){let a=j.useRef(),i=Fae();return $7(()=>{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(dU,o),a.current=o}),a}var a6s=()=>{let[s,t]=j.useState(),n=uU(()=>new Map);return $7(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function i6s(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function RLe({asChild:s,children:t},n){return s&&j.isValidElement(t)?j.cloneElement(i6s(t),{ref:t.ref},n(t.props.children)):n(t)}var o6s={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const N2=j.forwardRef(({className:s,...t},n)=>e.jsx(Bw,{ref:n,className:Pt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));N2.displayName=Bw.displayName;const l6s=({children:s,...t})=>e.jsx(Os,{...t,children:e.jsx(Fs,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(N2,{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})})}),k2=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(Bw.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})]}));k2.displayName=Bw.Input.displayName;const S2=j.forwardRef(({className:s,...t},n)=>e.jsx(Bw.List,{ref:n,className:Pt("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));S2.displayName=Bw.List.displayName;const C2=j.forwardRef((s,t)=>e.jsx(Bw.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));C2.displayName=Bw.Empty.displayName;const Rw=j.forwardRef(({className:s,...t},n)=>e.jsx(Bw.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}));Rw.displayName=Bw.Group.displayName;const c6s=j.forwardRef(({className:s,...t},n)=>e.jsx(Bw.Separator,{ref:n,className:Pt("-mx-1 h-px bg-border",s),...t}));c6s.displayName=Bw.Separator.displayName;const h1=j.forwardRef(({className:s,...t},n)=>e.jsx(Bw.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}));h1.displayName=Bw.Item.displayName;const d6s={event:{label:"Events",icon:Wc,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:yd,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:af,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:I4,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:wn,color:"bg-fuchsia-500/10 text-fuchsia-600"}},Tyt=()=>{const[s,t]=j.useState(!1),[n,r]=j.useState(""),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=Zn(),{searchDestinations:d,isFavorite:u,routeFor:h}=Lzt(),m=n.trim()?d(n).slice(0,6):[];j.useEffect(()=>{const v=y=>{y.key==="k"&&(y.metaKey||y.ctrlKey)&&(y.preventDefault(),t(b=>!b))};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[]);const f=j.useCallback(async v=>{if(!v.trim()){i([]);return}o(!0);const y=`%${v}%`;try{const[b,w,S,A,E]=await Promise.all([q.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${y},description.ilike.${y}`).limit(5),q.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${y},description.ilike.${y}`).limit(5),q.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${y},description.ilike.${y}`).limit(5),q.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${y},description.ilike.${y}`).limit(5),q.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${y},description.ilike.${y}`).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}`})}),A.data&&A.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 v=setTimeout(()=>{f(n)},300);return()=>clearTimeout(v)},[n,f]);const g=v=>{t(!1),r(""),c(v)},x=a.reduce((v,y)=>(v[y.type]||(v[y.type]=[]),v[y.type].push(y),v),{});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(l6s,{open:s,onOpenChange:t,children:[e.jsx(k2,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(S2,{children:[m.length>0&&e.jsx(Rw,{heading:"Go to",children:m.map(v=>{const y=v.icon;return e.jsxs(h1,{value:`nav-${v.id}-${v.label}`,onSelect:()=>{const b=h(v);v.external||v.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(y,{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:[v.label,u(v)&&e.jsx(A0,{className:"h-3 w-3 fill-current text-primary"})]}),v.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:v.description})]}),e.jsx($e,{variant:"secondary",className:"text-xs shrink-0",children:v.section})]},`nav-${v.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(C2,{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(([v,y])=>{const b=d6s[v],w=b.icon;return e.jsx(Rw,{heading:b.label,children:y.map(S=>e.jsxs(h1,{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($e,{variant:"secondary",className:"text-xs",children:b.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:hu(new Date(S.date),{addSuffix:!0})})]})]},`${S.type}-${S.id}`))},v)})]})]})]})},u6s=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=j.useState(null),i=Zn();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)),v=Math.floor(f%(1e3*60*60)/(1e3*60));a({days:g,hours:x,minutes:v})};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(Al,{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(wn,{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(ca,{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(wn,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},h6s=()=>{const s=Zn();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(je,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(St,{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(Al,{className:"h-8 w-8 text-destructive"})}),e.jsx(Et,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(Vn,{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(Le,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(je,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Le,{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(Yn,{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(wn,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(je,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Le,{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(wi,{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(wi,{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(pn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},m6s=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(ry,{children:[e.jsx(ay,{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(gm,{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(vx,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var f6s=Object.defineProperty,uT=(s,t)=>f6s(s,"name",{value:t,configurable:!0}),Stt="Checkbox",[p6s,pkr]=ep(Stt),[g6s,Ctt]=p6s(Stt);function qzt(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]=dy({prop:n,defaultProp:a??!1,onChange:c,caller:Stt}),[g,x]=j.useState(null),[v,y]=j.useState(null),b=j.useRef(!1),[w,S]=j.useReducer(I=>I+1,0),A=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:BE(a)?!1:a,isFormControl:A,bubbleInput:v,setBubbleInput:y};return e.jsx(g6s,{scope:t,...E,children:Hzt(h)?h(E):r})}uT(qzt,"CheckboxProvider");var x6s="CheckboxTrigger",y6s=j.forwardRef(uT(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:v}=Ctt(x6s,t),y=Vo(i,h),b=j.useRef(d);return j.useEffect(()=>{const w=l==null?void 0:l.form;if(w){const S=uT(()=>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":BE(d)?"mixed":d,"aria-required":u,"data-state":Att(d),"data-disabled":c?"":void 0,disabled:c,value:o,...a,ref:y,onKeyDown:Ra(n,w=>{w.key==="Enter"&&w.preventDefault()}),onClick:Ra(r,w=>{g(),m(S=>BE(S)?!0:!S),v&&x&&(f.current=w.isPropagationStopped(),f.current||w.stopPropagation())})})},"CheckboxTrigger")),Vzt=j.forwardRef(uT(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(qzt,{__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(y6s,{...m,ref:n,__scopeCheckbox:r}),f&&e.jsx(w6s,{__scopeCheckbox:r})]})})},"Checkbox")),v6s="CheckboxIndicator",b6s=j.forwardRef(uT(function(t,n){const{__scopeCheckbox:r,forceMount:a,...i}=t,l=Ctt(v6s,r);return e.jsx(my,{present:a||BE(l.checked)||l.checked===!0,children:e.jsx(Ei.span,{"data-state":Att(l.checked),"data-disabled":l.disabled?"":void 0,...i,ref:n,style:{pointerEvents:"none",...t.style}})})},"CheckboxIndicator")),_6s="CheckboxBubbleInput",w6s=j.forwardRef(uT(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:v}=Ctt(_6s,t),y=Vo(a,v),b=HW(i),w=j.useRef(!1),S=j.useRef(c),A=j.useRef(o);j.useEffect(()=>{const I=x;if(!I)return;const P=window.HTMLInputElement.prototype,D=Object.getOwnPropertyDescriptor(P,"checked").set,O=o!==A.current;A.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=BE(c),D.call(I,BE(c)?!1:c),I.dispatchEvent(V),w.current=!1}},[x,c,l,o]);const E=j.useRef(BE(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:y,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 Hzt(s){return typeof s=="function"}uT(Hzt,"isFunction");function BE(s){return s==="indeterminate"}uT(BE,"isIndeterminate");function Att(s){return BE(s)?"indeterminate":s?"checked":"unchecked"}uT(Att,"getState");const ai=j.forwardRef(({className:s,...t},n)=>e.jsx(Vzt,{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(b6s,{className:Pt("flex items-center justify-center text-current"),children:e.jsx(ma,{className:"h-4 w-4"})})}));ai.displayName=Vzt.displayName;var j6s=Object.defineProperty,x1=(s,t)=>j6s(s,"name",{value:t,configurable:!0}),Gzt="Radio",[N6s,Wzt]=ep(Gzt),[k6s,DLe]=N6s(Gzt);function Kzt(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),[v,y]=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:v,onUserInteraction:y,isFormControl:b,bubbleInput:f,setBubbleInput:g,onCheck:x1(()=>o==null?void 0:o(),"onCheck")};return e.jsx(k6s,{scope:t,...w,children:Yzt(u)?u(w):r})}x1(Kzt,"RadioProvider");var S6s="RadioTrigger",C6s=j.forwardRef(x1(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}=DLe(S6s,t),g=Vo(a,c);return e.jsx(Ei.button,{type:"button",role:"radio","aria-checked":i,"data-state":Ett(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")),A6s="RadioIndicator",E6s=j.forwardRef(x1(function(t,n){const{__scopeRadio:r,forceMount:a,...i}=t,l=DLe(A6s,r);return e.jsx(my,{present:a||l.checked,children:e.jsx(Ei.span,{"data-state":Ett(l.checked),"data-disabled":l.disabled?"":void 0,...i,ref:n})})},"RadioIndicator")),T6s="RadioBubbleInput",M6s=j.forwardRef(x1(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}=DLe(T6s,t),v=Vo(a,f),y=HW(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 A=j.useRef(l);return e.jsx(Ei.input,{type:"radio","aria-hidden":!0,defaultChecked:A.current,required:o,disabled:c,name:d,value:u,form:h,...r,tabIndex:-1,ref:v,onClick:Ra(n,E=>{b.current&&E.stopPropagation()}),style:{...r.style,...y,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"RadioBubbleInput"));function Yzt(s){return typeof s=="function"}x1(Yzt,"isFunction");function Ett(s){return s?"checked":"unchecked"}x1(Ett,"getState");var P6s=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Ttt="RadioGroup",[I6s,gkr]=ep(Ttt,[JL,Wzt]),Zzt=JL(),FLe=Wzt(),[L6s,R6s]=I6s(Ttt),Xzt=j.forwardRef(x1(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=Zzt(r),v=a3(h),[y,b]=dy({prop:o,defaultProp:l??null,onChange:f,caller:Ttt}),[w,S]=j.useState(null),A=Vo(n,S),E=j.useRef(y);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=x1(()=>b(E.current),"reset");return I.addEventListener("reset",P),()=>I.removeEventListener("reset",P)}},[w,i,b]),e.jsx(L6s,{scope:r,name:a,form:i,required:c,disabled:d,value:y,onValueChange:b,children:e.jsx(uLe,{asChild:!0,...x,orientation:u,dir:v,loop:m,children:e.jsx(Ei.div,{role:"radiogroup","aria-required":c,"aria-orientation":u,"data-disabled":d?"":void 0,dir:v,...g,ref:A})})})},"RadioGroup")),D6s="RadioGroupItemProvider",F6s="RadioGroupItemTrigger";function Qzt(s){const{__scopeRadioGroup:t,value:n,disabled:r,children:a,internal_do_not_use_render:i}=s,l=R6s(D6s,t),o=FLe(t),c=l.disabled||r;return e.jsx(Kzt,{...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})}x1(Qzt,"RadioGroupItemProvider");var O6s=j.forwardRef(x1(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=Zzt(r),l=FLe(r),{checked:o,disabled:c}=DLe(F6s,l.__scopeRadio),d=j.useRef(null),u=Vo(n,d),h=j.useRef(!1);return j.useEffect(()=>{const m=x1(g=>{P6s.includes(g.key)&&(h.current=!0)},"handleKeyDown"),f=x1(()=>h.current=!1,"handleKeyUp");return document.addEventListener("keydown",m),document.addEventListener("keyup",f),()=>{document.removeEventListener("keydown",m),document.removeEventListener("keyup",f)}},[]),e.jsx(hLe,{asChild:!0,...i,focusable:!c,active:o,children:e.jsx(C6s,{...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")),Jzt=j.forwardRef(x1(function(t,n){const{__scopeRadioGroup:r,value:a,disabled:i,...l}=t;return e.jsx(Qzt,{__scopeRadioGroup:r,value:a,disabled:i,internal_do_not_use_render:({isFormControl:o})=>e.jsxs(e.Fragment,{children:[e.jsx(O6s,{...l,ref:n,__scopeRadioGroup:r}),o&&e.jsx(z6s,{__scopeRadioGroup:r})]})})},"RadioGroupItem")),z6s=j.forwardRef(x1(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=FLe(r);return e.jsx(M6s,{...i,...a,ref:n})},"RadioGroupItemBubbleInput")),B6s=j.forwardRef(x1(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=FLe(r);return e.jsx(E6s,{...i,...a,ref:n})},"RadioGroupIndicator"));const yw=j.forwardRef(({className:s,...t},n)=>e.jsx(Xzt,{className:Pt("grid gap-2",s),...t,ref:n}));yw.displayName=Xzt.displayName;const Km=j.forwardRef(({className:s,...t},n)=>e.jsx(Jzt,{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(B6s,{className:"flex items-center justify-center",children:e.jsx(Dg,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Km.displayName=Jzt.displayName;const $6s=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=_s(),[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 v=s.polls.map(b=>b.id),{data:y}=await q.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",v);if(y){const b={};y.forEach(w=>{b[w.poll_id]||(b[w.poll_id]=[]),b[w.poll_id].push(w.option_id)}),c(b)}},m=(v,y)=>{l(b=>({...b,[v]:y}))},f=(v,y,b)=>{l(w=>{const S=w[v]||[];return b?{...w,[v]:[...S,y]}:{...w,[v]:S.filter(A=>A!==y)}})},g=async v=>{if(!a)return;const y=i[v];if(!y||Array.isArray(y)&&y.length===0){ne.error("Please select an option");return}u(b=>[...b,v]);try{await q.from("levelup_brief_poll_responses").delete().eq("poll_id",v).eq("user_id",a.id);const b=Array.isArray(y)?y:[y],w=b.map(A=>({poll_id:v,option_id:A,user_id:a.id})),{error:S}=await q.from("levelup_brief_poll_responses").insert(w);if(S)throw S;c(A=>({...A,[v]:b})),ne.success("Response submitted!")}catch(b){console.error("Error submitting poll response:",b),ne.error("Failed to submit response")}finally{u(b=>b.filter(w=>w!==v))}},x=v=>(v.includes("mediadelivery.net")||v.includes("bunny"),v);return e.jsx(Os,{open:t,onOpenChange:v=>!v&&n(),children:e.jsxs(Fs,{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(mr,{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(gm,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx($e,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx($s,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(go,{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(v=>e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(v.url,"_blank"),className:"gap-2",children:[e.jsx(Ir,{className:"h-4 w-4"}),v.title]},v.id))})]}),s.polls.map(v=>{var w,S;const y=((w=o[v.id])==null?void 0:w.length)>0,b=d.includes(v.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:v.question}),y&&e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),"Responded"]})]}),v.poll_type==="single"?e.jsx(yw,{value:i[v.id]||((S=o[v.id])==null?void 0:S[0])||"",onValueChange:A=>m(v.id,A),className:"space-y-2",children:v.options.map(A=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Km,{value:A.id,id:A.id}),e.jsx(ee,{htmlFor:A.id,className:"cursor-pointer",children:A.option_text})]},A.id))}):e.jsx("div",{className:"space-y-2",children:v.options.map(A=>{const I=(i[v.id]||o[v.id]||[]).includes(A.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ai,{id:A.id,checked:I,onCheckedChange:P=>f(v.id,A.id,P)}),e.jsx(ee,{htmlFor:A.id,className:"cursor-pointer",children:A.option_text})]},A.id)})}),e.jsx($,{size:"sm",onClick:()=>g(v.id),disabled:b,children:b?"Submitting...":y?"Update Response":"Submit"})]},v.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"})]})]})})},U6s=()=>{const{user:s}=_s(),[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:v}=await q.from("levelup_brief_views").select("*").eq("brief_id",g.id).eq("user_id",s.id).maybeSingle(),[y,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:y.data||[],polls:w};n(S);const A=!!v,E=(v==null?void 0:v.dismissed_at)!=null,I=localStorage.getItem(`brief-dismissed-${g.id}`)==="true";if(E||I)c(!1),a(!1);else if(!A)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(v.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:v}=await q.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",g.id).eq("user_id",s.id);v&&console.error("Error updating brief dismiss:",v)}else{const{error:v}=await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});v&&console.error("Error inserting brief dismiss:",v)}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 q6s(){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(ji,{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(KJ,{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(mr,{className:"h-4 w-4"})})]})]})}):null}const V6s=({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=Zt(),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 A=b.touches[0].clientY-d.current;if(A>0){const I=Math.min(A*.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]),v=Math.min(a/h,1),y=v*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:v},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${y}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(co,{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})]})},e7t=()=>{const{user:s}=_s(),[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 v=sessionStorage.getItem("review-prompt-dismissed");n(x>=4&&!v)}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}},H6s="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",G6s=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=e7t(),[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,v]=j.useState(!1),[y,b]=j.useState(!1);if(t||!s&&!y)return null;const w=async()=>{if(d===0){_a({title:"Please select a rating",variant:"destructive"});return}v(!0);const E=await r(d,f);v(!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(H6s,"_blank")),l(!1),n()},A=()=>{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(ei,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(Os,{open:i,onOpenChange:A,children:e.jsx(Fs,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx($s,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(Er,{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(ei,{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:A,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($s,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(Er,{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 W6s(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 v=localStorage.getItem(x);if(!v){const{data:w,error:S}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(S)throw S;if(v=(w==null?void 0:w.vapidPublicKey)??null,!v)throw new Error("Missing VAPID public key");localStorage.setItem(x,v)}u(v);const y=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(y),n(Notification.permission);const b=await y.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 ne.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"?ne.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):ne.error("Notification permission was dismissed. Please try again."),!1}const x=W6s(d);let v;try{v=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")?ne.error("Push permission denied. Check your browser notification settings."):S.includes("key")||S.includes("VAPID")?ne.error("Push configuration error. Please contact support."):S.includes("AbortError")?ne.error("Push subscription was cancelled. Please try again."):ne.error(`Failed to subscribe: ${S}`),!1}const y=v.toJSON(),{error:b}=await q.from("push_subscriptions").upsert({user_id:s.id,endpoint:y.endpoint,p256dh_key:y.keys.p256dh,auth_key:y.keys.auth},{onConflict:"user_id,endpoint"});if(b)throw console.error("Error saving subscription:",b),ne.error("Failed to save notification preferences. Please try again."),b;return a(!0),ne.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";ne.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),ne.success("Push notifications disabled"),!0}catch(g){console.error("Error unsubscribing:",g);const x=g instanceof Error?g.message:"Unknown error";return ne.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 n7e="push_notification_prompt_dismissed",K6s=["/dashboard","/admin"],Y6s=()=>{const{user:s}=_s(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=t7t(),i=qu(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),u=K6s.some(f=>i.pathname===f||i.pathname.startsWith(`${f}/`));j.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${n7e}_${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(`${n7e}_${s.id}`,"true"),o(!1))},m=()=>{s&&localStorage.setItem(`${n7e}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(Os,{open:l,onOpenChange:f=>!f&&m(),children:e.jsxs(Fs,{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(zy,{className:"h-6 w-6 text-primary"})}),e.jsx($s,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(Er,{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."})]})})},Myt=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},Z6s=s=>s?Myt(s):Myt,X6s=s=>s;function Q6s(s,t=X6s){const n=Kt.useSyncExternalStore(s.subscribe,Kt.useCallback(()=>t(s.getState()),[s,t]),Kt.useCallback(()=>t(s.getInitialState()),[s,t]));return Kt.useDebugValue(n),n}const Pyt=s=>{const t=Z6s(s),n=r=>Q6s(t,r);return Object.assign(n,t),n},J6s=s=>s?Pyt(s):Pyt;function eRs(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 WHe=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return WHe(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return WHe(r)(n)}}}},tRs=(s,t)=>(n,r,a)=>{let i={storage:eRs(()=>window.localStorage),partialize:v=>v,version:0,merge:(v,y)=>({...y,...v}),...t},l=!1,o=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return s((...v)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...v)},r,a);const h=()=>{const v=i.partialize({...r()});return u.setItem(i.name,{state:v,version:i.version})},m=a.setState;a.setState=(v,y)=>(m(v,y),h());const f=s((...v)=>(n(...v),h()),r,a);a.getInitialState=()=>f;let g;const x=()=>{var v,y;if(!u)return;const b=++o;l=!1,c.forEach(S=>{var A;return S((A=r())!=null?A:f)});const w=((y=i.onRehydrateStorage)==null?void 0:y.call(i,(v=r())!=null?v:f))||void 0;return WHe(u.getItem.bind(u))(i.name).then(S=>{if(S)if(typeof S.version=="number"&&S.version!==i.version){if(i.migrate){const A=i.migrate(S.state,S.version);return A instanceof Promise?A.then(E=>[!0,E]):[!0,A]}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 A;if(b!==o)return;const[E,I]=S;if(g=i.merge(I,(A=r())!=null?A: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:v=>{i={...i,...v},v.storage&&(u=v.storage)},clearStorage:()=>{++o,u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>l,onHydrate:v=>(c.add(v),()=>{c.delete(v)}),onFinishHydration:v=>(d.add(v),()=>{d.delete(v)})},i.skipHydration||x(),g||f},sRs=tRs,OLe=J6s()(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 nRs({activeCategory:s,currentCategory:t,onSelect:n,onHover:r,badgeCounts:a,categories:i=LLe}){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 rRs({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 v;if(!u.current)return;const x=g.target;!u.current.contains(x)&&!((v=x==null?void 0:x.closest)!=null&&v.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(jc,{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(A0,{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(A0,{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 aRs({categories:s,railCategories:t=LLe,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(wl,{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(v=>{const y=v.icon,b=v.badgeKey?(l==null?void 0:l[v.badgeKey])??0:0,w=(o==null?void 0:o(v))??!1;return e.jsxs("div",{className:Pt("flex w-full items-center gap-2 rounded-md pr-1 hover:bg-sidebar-accent",i(v)&&"bg-sidebar-accent"),children:[e.jsxs("button",{type:"button",onClick:()=>r(v),className:"flex flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-sidebar-foreground",children:[e.jsx(y,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:v.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 ${v.label} from favorites`:`Add ${v.label} to favorites`,onClick:()=>c(v),className:Pt("rounded p-2",w?"text-primary":"text-muted-foreground/60"),children:e.jsx(A0,{className:Pt("h-4 w-4",w&&"fill-current")})})]},v.id)})]},x.title))})]},h.id)})})}function s7t(){const s=Zn(),t=qu(),n=Lzt(),r=j.useCallback(o=>Izt(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 iRs({communityUnreadCount:s=0,wishlistOpenCount:t=0,flyoutTop:n=64,flyoutLeft:r=80}){const{nav:a,navigate:i,currentCategory:l,isCurrent:o,go:c}=s7t(),[d,u]=j.useState(null),h=j.useRef(null),m=x=>{const v=LLe.find(y=>y.id===x);if(v!=null&&v.route){u(null),i(v.route);return}u(y=>y===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(nRs,{activeCategory:d,currentCategory:l,onSelect:m,categories:a.railCategories,badgeCounts:g}),f&&e.jsx(rRs,{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 oRs({communityUnreadCount:s=0,wishlistOpenCount:t=0,onNavigated:n}){const{nav:r,navigate:a,currentCategory:i,isCurrent:l,go:o}=s7t();return e.jsx(aRs,{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 lRs=({bannerHeight:s,communityUnreadCount:t,wishlistOpenCount:n,isTrial:r,isExpired:a})=>{const i=Zn();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:WCs,alt:"LevelUp",className:"h-8 w-auto"})})}),e.jsxs(go,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[e.jsx(iRs,{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(wn,{className:"h-4 w-4"}),"Upgrade"]})})]})]})},cRs=({isTrial:s,isExpired:t,expiresAt:n,communityUnreadCount:r,wishlistOpenCount:a,pathname:i,onSignOut:l,onNavigated:o})=>{const c=Zn();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:GCs,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsxs(go,{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(wn,{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(oRs,{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(Bz,{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}=_s(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=Sae();pLe();const{isImpersonating:h}=cLe(),f=(c&&!!d?40:0)+(h?40:0),{avatarUrl:g}=COt(n==null?void 0:n.id),{isTrial:x,isExpired:v,expiresAt:y}=_Cs(n==null?void 0:n.id),{isMarketplaceEnabled:b}=Aae(),{currentBrief:w,shouldShowPopup:S,hasUnseenBrief:A,openBrief:E,closeBrief:I,dismissBrief:P}=U6s(),{unreadCount:R}=wCs(),{openCount:D}=jCs();Ow();const U=OLe(ce=>ce.cartItems).reduce((ce,ve)=>ce+ve.quantity,0),{hasLeadSite:W}=tg();PLe(!W);const V=Zn(),G=qu(),[Z,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=Z||((J=n==null?void 0:n.user_metadata)==null?void 0:J.name)||(n==null?void 0:n.email)||"User",[le,re]=j.useState(!1),te=ce=>ce.split(" ").map(ve=>ve[0]).join("").toUpperCase().slice(0,2);return e.jsx(vk,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[x&&v&&G.pathname!=="/subscription"&&e.jsx(h6s,{}),typeof document<"u"&&yv.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(lRs,{bannerHeight:f,communityUnreadCount:R,wishlistOpenCount:D,isTrial:x,isExpired:v})}),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(Vy,{open:le,onOpenChange:re,children:[e.jsx(Tae,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(TE,{className:"h-5 w-5"})})}),e.jsx(uy,{side:"left",className:"w-72 p-0 bg-card",children:e.jsx(cRs,{isTrial:x,isExpired:v,expiresAt:y,communityUnreadCount:R,wishlistOpenCount:D,pathname:G.pathname,onSignOut:r,onNavigated:()=>re(!1)})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:KCs,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(Tyt,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[x&&!v&&y&&e.jsx(u6s,{expiresAt:y,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(Tyt,{})}),w&&e.jsx(m6s,{hasUnseenBrief:A,onClick:E}),b&&e.jsxs($,{variant:"ghost",size:"icon",className:"relative",onClick:()=>V("/marketplace/cart"),children:[e.jsx(eC,{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(Wc,{className:"h-5 w-5"})}),e.jsx(mLs,{}),e.jsx(BHe,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",ae.split(" ")[0],"!"]}),e.jsxs(Bu,{children:[e.jsx($u,{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(Ii,{src:g||void 0}),e.jsx(za,{className:"bg-primary text-primary-foreground font-medium text-sm",children:te(ae)})]})})}),e.jsxs(Cu,{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(QN,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(ja,{onClick:()=>V("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(QN,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(P0,{}),e.jsxs(ja,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(Bz,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(V6s,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),w&&e.jsx($6s,{brief:w,open:S,onClose:I,onDismiss:P}),e.jsx(q6s,{}),e.jsx(G6s,{}),e.jsx(Y6s,{})]})]})})},vn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=_s(),c=qu(),d=bC();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(eu,{to:"/auth",replace:!0})}if(t&&!l)return e.jsx(eu,{to:"/dashboard",replace:!0});if(n&&!o&&!l)return e.jsx(eu,{to:"/dashboard",replace:!0});if(d.isRestricted&&!d.isLoading){const u=kOt(c.pathname);if(u&&!d.hasFeature(u))return e.jsx(Vs,{title:"Upgrade required",children:e.jsx(bCs,{featureKey:u})})}return e.jsx(e.Fragment,{children:s})};function r7e({children:s}){const{isAdmin:t,loading:n,rolesLoading:r}=_s(),{isFeatureEnabled:a,isLoading:i}=Aae();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(eu,{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 Mtt={};(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 re=new OffscreenCanvas(1,1),te=re.getContext("2d");te.fillRect(0,0,1,1);var J=re.transferToImageBitmap();te.createPattern(J,"no-repeat")}catch{return!1}return!0}();function c(){}function d(re){var te=n.exports.Promise,J=te!==void 0?te:t.Promise;return typeof J=="function"?new J(re):(re(c,c),null)}var u=function(re,te){return{transform:function(J){if(re)return J;if(te.has(J))return te.get(J);var ce=new OffscreenCanvas(J.width,J.height),ve=ce.getContext("2d");return ve.drawImage(J,0,0),te.set(J,ce),ce},clear:function(){te.clear()}}}(o,new Map),h=function(){var re=Math.floor(16.666666666666668),te,J,ce={},ve=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(te=function(fe){var ue=Math.random();return ce[ue]=requestAnimationFrame(function be(Ee){ve===Ee||ve+re-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 uRs(){const s=Zt();return mt({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 hRs(){const s=Zt(),{user:t}=_s();return mt({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 mRs={points_earned:Kl,listing_created:va,deal_closed:su,custom:ei},Lyt={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"},Ryt=()=>{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 fRs(){const{user:s}=_s(),t=Zt(),{data:n}=dRs(),r=uRs(),[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=(y,b)=>Math.random()*(b-y)+y,v=setInterval(()=>{const y=f-Date.now();if(y<=0){clearInterval(v);return}const b=50*(y/3e3);Iyt({...g,particleCount:b,origin:{x:x(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),Iyt({...g,particleCount:b,origin:{x:x(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);j.useEffect(()=>{Ryt()||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(Ryt()||!a)return null;const u=mRs[a.celebration_type]||ei,h=Lyt[a.celebration_type]||Lyt.custom;return e.jsx(Os,{open:l,onOpenChange:m=>!m&&d(),children:e.jsxs(Fs,{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(wn,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(wn,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(wn,{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 xn({className:s,...t}){return e.jsx("div",{className:Pt("animate-pulse rounded-md bg-muted",s),...t})}var pRs=Object.defineProperty,JW=(s,t)=>pRs(s,"name",{value:t,configurable:!0}),Ptt="Tabs",[gRs,xkr]=ep(Ptt,[JL]),n7t=JL(),[xRs,Itt]=gRs(Ptt),yRs=j.forwardRef(JW(function(t,n){const{__scopeTabs:r,value:a,onValueChange:i,defaultValue:l,orientation:o="horizontal",dir:c,activationMode:d="automatic",...u}=t,h=a3(c),[m,f]=dy({prop:a,onChange:i,defaultProp:l??"",caller:Ptt});return e.jsx(xRs,{scope:r,baseId:cy(),value:m,onValueChange:f,orientation:o,dir:h,activationMode:d,children:e.jsx(Ei.div,{dir:h,"data-orientation":o,...u,ref:n})})},"Tabs")),vRs="TabsList",bRs=j.forwardRef(JW(function(t,n){const{__scopeTabs:r,loop:a=!0,...i}=t,l=Itt(vRs,r),o=n7t(r);return e.jsx(uLe,{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")),_Rs="TabsTrigger",wRs=j.forwardRef(JW(function(t,n){const{__scopeTabs:r,value:a,disabled:i=!1,...l}=t,o=Itt(_Rs,r),c=n7t(r),d=Ltt(o.baseId,a),u=Rtt(o.baseId,a),h=a===o.value;return e.jsx(hLe,{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")),jRs="TabsContent",NRs=j.forwardRef(JW(function(t,n){const{__scopeTabs:r,value:a,forceMount:i,children:l,...o}=t,c=Itt(jRs,r),d=Ltt(c.baseId,a),u=Rtt(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(my,{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 Ltt(s,t){return`${s}-trigger-${t}`}JW(Ltt,"makeTriggerId");function Rtt(s,t){return`${s}-content-${t}`}JW(Rtt,"makeContentId");var kRs=yRs,r7t=bRs,a7t=wRs,i7t=NRs;const pa=kRs,ga=j.forwardRef(({className:s,...t},n)=>e.jsx(r7t,{ref:n,className:Pt("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));ga.displayName=r7t.displayName;const Xt=j.forwardRef(({className:s,...t},n)=>e.jsx(a7t,{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}));Xt.displayName=a7t.displayName;const Qt=j.forwardRef(({className:s,...t},n)=>e.jsx(i7t,{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}));Qt.displayName=i7t.displayName;const Zte="#0d0d0d",CEe="#1a1a1a",ob="#c9a84c",Oae="#f0d78c",H4={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function zLe(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(H4.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function Dtt(){try{return!!localStorage.getItem(H4.captured)}catch{return!1}}function SRs(){try{const s=localStorage.getItem(H4.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function Ftt({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?yv.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, ${CEe} 0%, ${Zte} 100%)`,border:`1px solid ${ob}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${ob}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(mr,{className:"h-4 w-4"})}),n]})}),document.body):null}function Ott(){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 ztt({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(pn,{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(ui,{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 Btt({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, ${Oae} 0%, ${ob} 100%)`,color:Zte,boxShadow:`0 8px 24px ${ob}55`},children:s})}function Dyt({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=Ott(),[d,u]=j.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await zLe({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(H4.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{ne.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(Ftt,{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(zy,{className:"h-4 w-4",style:{color:ob}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:Oae},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:`${ob}22`,border:`1px solid ${ob}55`},children:e.jsx(wn,{className:"h-5 w-5",style:{color:ob}})}),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(ztt,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(Btt,{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 CRs(){const[s,t]=j.useState(!0),[n,r]=j.useState(!1);j.useEffect(()=>{try{const i=!!localStorage.getItem(H4.stickyDismissed)||Dtt();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(H4.stickyDismissed,"1")}catch{}};return s?e.jsx(Dyt,{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, ${CEe} 0%, ${Zte} 100%)`,borderTop:`1px solid ${ob}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:`${ob}22`,border:`1px solid ${ob}55`},children:e.jsx(zy,{className:"h-4 w-4",style:{color:ob}})}),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, ${Oae} 0%, ${ob} 100%)`,color:Zte},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx(mr,{className:"h-4 w-4"})})]})}),e.jsx(Dyt,{open:n,onClose:()=>r(!1)})]})}function ARs(){const[s,t]=j.useState(!1),n=j.useRef(!1);j.useEffect(()=>{try{if(sessionStorage.getItem(H4.exitShown)||Dtt())return}catch{}const m=setTimeout(()=>{n.current=!0},8e3),f=g=>{if(n.current&&!(g.clientY>0)){t(!0);try{sessionStorage.setItem(H4.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}=Ott(),[d,u]=j.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await zLe({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{ne.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(Ftt,{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, ${Zte} 0%, ${CEe} 60%, ${ob} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:Oae},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:CEe,border:`1px solid ${ob}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(wn,{className:"h-6 w-6",style:{color:ob}})}),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(ztt,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(Btt,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function ERs(){const[s,t]=j.useState([]);j.useEffect(()=>{try{const o=localStorage.getItem(H4.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(H4.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 TRs({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=ERs(),l=r(s),[o,c]=j.useState(!1),d=()=>{if(l){i(s);return}if(Dtt()){a(s),ne.success("Saved to your favorites"),zLe({lead_type:"saved_listing",email:SRs()||"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(MRs,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function MRs({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=Ott(),h=async m=>{if(m.preventDefault(),!!i.email){c(!0);try{await zLe({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(),ne.success("Saved to your favorites"),t()}catch{ne.error("Something went wrong. Please try again.")}finally{c(!1)}}};return e.jsx(Ftt,{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:ob}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:Oae},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(ztt,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(Btt,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}var PRs=Object.defineProperty,Bh=(s,t)=>PRs(s,"name",{value:t,configurable:!0}),o7t=["PageUp","PageDown"],l7t=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],c7t={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},zae="Slider",[KHe,IRs,LRs]=SB(zae),[$tt,ykr]=ep(zae,[LRs]),[RRs,Bae]=$tt(zae),d7t=j.forwardRef(Bh(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=Bh(()=>{},"onValueChange"),onValueCommit:f=Bh(()=>{},"onValueCommit"),inverted:g=!1,form:x,...v}=t,y=j.useRef(new Set),b=j.useRef(0),w=j.useRef(!1),A=o==="horizontal"?DRs:FRs,[E,I]=j.useState(null),P=Vo(n,I),[R=[],D]=dy({prop:h,defaultProp:u,onChange:Bh(X=>{var le;(le=[...y.current][b.current])==null||le.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=Bh(()=>D(U.current),"reset");return X.addEventListener("reset",ae),()=>X.removeEventListener("reset",ae)}},[E,x,D]);function W(X){const ae=y7t(R,X);Z(X,ae)}Bh(W,"handleSlideStart");function V(X){Z(X,b.current)}Bh(V,"handleSlideMove");function G(){String(R)!==String(O.current)&&f(R)}Bh(G,"handleSlideEnd");function Z(X,ae,{commit:le}={commit:!1}){const re=qtt(l),te=mee(Math.round((X-a)/l)*l+a,re),J=gG(te,[a,i]);D((ce=[])=>{const ve=g7t(ce,J,ae);if(_7t(ve,d*l)){b.current=ve.indexOf(J);const fe=String(ve)!==String(ce);return fe&&le&&f(ve),fe?ve:ce}else return ce})}return Bh(Z,"updateValues"),e.jsx(RRs,{scope:t.__scopeSlider,name:r,disabled:c,min:a,max:i,valueIndexToChangeRef:b,thumbs:y.current,values:R,orientation:o,form:x,children:e.jsx(KHe.Provider,{scope:t.__scopeSlider,children:e.jsx(KHe.Slot,{scope:t.__scopeSlider,children:e.jsx(A,{"aria-disabled":c,"data-disabled":c?"":void 0,...v,ref:P,onPointerDown:Ra(v.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,Z(a,0,{commit:!0}))},onEndKeyDown:()=>{c||(w.current=!0,Z(i,R.length-1,{commit:!0}))},onStepKeyDown:({event:X,direction:ae})=>{if(!c){w.current=!0;const te=o7t.includes(X.key)||X.shiftKey&&l7t.includes(X.key)?10:1,J=b.current,ce=R[J],ve=w7t(ce,{min:a,step:l,direction:ae,multiplier:te});Z(ve,J,{commit:!0})}}})})})})},"Slider")),[u7t,h7t]=$tt(zae,{startEdge:"left",endEdge:"right",size:"width",direction:1}),DRs=j.forwardRef(Bh(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),v=a3(i),y=v==="ltr",b=y&&!l||!y&&l;function w(S){const A=x.current||m.getBoundingClientRect(),E=[0,A.width],P=BLe(E,b?[r,a]:[a,r]);return x.current=A,P(S-A.left)}return Bh(w,"getValueFromPointer"),e.jsx(u7t,{scope:t.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:e.jsx(m7t,{dir:v,"data-orientation":"horizontal",...h,ref:g,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:S=>{const A=w(S.clientX);o==null||o(A)},onSlideMove:S=>{const A=w(S.clientX);c==null||c(A)},onSlideEnd:()=>{x.current=void 0,d==null||d()},onStepKeyDown:S=>{const E=c7t[b?"from-left":"from-right"].includes(S.key);u==null||u({event:S,direction:E?-1:1})}})})},"SliderHorizontal")),FRs=j.forwardRef(Bh(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(v){const y=f.current||h.current.getBoundingClientRect(),b=[0,y.height],S=BLe(b,g?[a,r]:[r,a]);return f.current=y,S(v-y.top)}return Bh(x,"getValueFromPointer"),e.jsx(u7t,{scope:t.__scopeSlider,startEdge:g?"bottom":"top",endEdge:g?"top":"bottom",size:"height",direction:g?1:-1,children:e.jsx(m7t,{"data-orientation":"vertical",...u,ref:m,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:v=>{const y=x(v.clientY);l==null||l(y)},onSlideMove:v=>{const y=x(v.clientY);o==null||o(y)},onSlideEnd:()=>{f.current=void 0,c==null||c()},onStepKeyDown:v=>{const b=c7t[g?"from-bottom":"from-top"].includes(v.key);d==null||d({event:v,direction:b?-1:1})}})})},"SliderVertical")),m7t=j.forwardRef(Bh(function(t,n){const{__scopeSlider:r,onSlideStart:a,onSlideMove:i,onSlideEnd:l,onHomeKeyDown:o,onEndKeyDown:c,onStepKeyDown:d,...u}=t,h=Bae(zae,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()):o7t.concat(l7t).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")),ORs="SliderTrack",zRs=j.forwardRef(Bh(function(t,n){const{__scopeSlider:r,...a}=t,i=Bae(ORs,r);return e.jsx(Ei.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...a,ref:n})},"SliderTrack")),Fyt="SliderRange",BRs=j.forwardRef(Bh(function(t,n){const{__scopeSlider:r,...a}=t,i=Bae(Fyt,r),l=h7t(Fyt,r),o=j.useRef(null),c=Vo(n,o),d=i.values.length,u=i.values.map(f=>Utt(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")),$Rs="SliderThumb",[URs,f7t]=$tt($Rs),qRs="SliderThumbProvider";function p7t(s){const{__scopeSlider:t,name:n,children:r,internal_do_not_use_render:a}=s,i=Bae(qRs,t),l=IRs(t),[o,c]=j.useState(null),d=j.useMemo(()=>o?l().findIndex(v=>v.ref.current===o):-1,[l,o]),u=HW(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:Utt(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(URs,{scope:t,...x,children:j7t(a)?a(x):r})}Bh(p7t,"SliderThumbProvider");var a7e="SliderThumbTrigger",VRs=j.forwardRef(Bh(function(t,n){const{__scopeSlider:r,...a}=t,i=Bae(a7e,r),l=h7t(a7e,r),{index:o,value:c,percent:d,size:u,onThumbChange:h}=f7t(a7e,r),m=Vo(n,h),f=x7t(o,i.values.length),g=u==null?void 0:u[l.size],x=g?v7t(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(KHe.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")),HRs=j.forwardRef(Bh(function(t,n){const{__scopeSlider:r,name:a,...i}=t;return e.jsx(p7t,{__scopeSlider:r,name:a,internal_do_not_use_render:({index:l,isFormControl:o})=>e.jsxs(e.Fragment,{children:[e.jsx(VRs,{...i,ref:n,__scopeSlider:r}),o?e.jsx(WRs,{__scopeSlider:r},l):null]})})},"SliderThumb")),GRs="SliderBubbleInput",WRs=j.forwardRef(Bh(function({__scopeSlider:t,...n},r){const{value:a,name:i,form:l}=f7t(GRs,t),o=j.useRef(null),c=Vo(o,r),d=ctt(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 g7t(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}Bh(g7t,"getNextSortedValues");function Utt(s,t,n){const i=100/(n-t)*(s-t);return gG(i,[0,100])}Bh(Utt,"convertValueToPercentage");function x7t(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}Bh(x7t,"getLabel");function y7t(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)}Bh(y7t,"getClosestValueIndex");function v7t(s,t,n){const r=s/2,i=BLe([0,50],[0,r]);return(r-i(t)*n)*n}Bh(v7t,"getThumbInBoundsOffset");function b7t(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}Bh(b7t,"getStepsBetweenValues");function _7t(s,t){if(t>0){const n=b7t(s);return Math.min(...n)>=t}return!0}Bh(_7t,"hasMinStepsBetweenValues");function BLe(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])}}Bh(BLe,"linearScale");function qtt(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}Bh(qtt,"getDecimalCount");function mee(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}Bh(mee,"roundValue");function w7t(s,{min:t,step:n,direction:r,multiplier:a}){const i=qtt(n),l=(s-t)/n,o=Math.round(l),c=mee(o*n+t,i)===mee(s,i);let d;return c?d=o+a*r:r>0?d=Math.ceil(l):d=Math.floor(l),mee(d*n+t,i)}Bh(w7t,"getNextStepValue");function j7t(s){return typeof s=="function"}Bh(j7t,"isFunction");const bx=j.forwardRef(({className:s,...t},n)=>e.jsxs(d7t,{ref:n,className:Pt("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(zRs,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(BRs,{className:"absolute h-full bg-primary"})}),e.jsx(HRs,{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"})]}));bx.displayName=d7t.displayName;const KRs=s=>st({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}}),YRs=()=>st({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)}}}),ZRs=s=>st({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}),XRs=()=>mt({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:v}=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(v)throw v;const{error:y}=await q.functions.invoke("process-listing-lead",{body:{leadId:x.id}});return y&&console.error("Error processing lead:",y),x}}),QRs=()=>mt({mutationFn:async s=>{const{error:t}=await q.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),SL={sale:"For Sale",lease:"For Lease",sale_or_lease:"For Sale or Lease",investment:"Investment Offering"},r6={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"},JRs=["NNN","Modified Gross","Full Service","Gross","Absolute Net","Ground Lease"],eDs={sf_year:"/SF/YR",sf_month:"/SF/MO",month:"/MO"},YHe={om:"Offering Memorandum",flyer:"Flyer",rent_roll:"Rent Roll",financials:"Financials",survey:"Survey",site_plan:"Site Plan",lease:"Lease Documents",other:"Other"},Oyt={public:"Open download",email:"Email required",nda:"NDA required"},ZHe={principal:"Principal / Investor",broker:"Broker",tenant:"Tenant / User",lender:"Lender",other:"Other"},i7e=[{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"}],K4e=[{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"}],N7t=[{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 PN(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 zyt(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`:PN(t)}function xE(s){return s==null?null:`${new Intl.NumberFormat("en-US").format(Number(s))} SF`}function AEe(s,t=2){return s==null?null:`${Number(s).toFixed(t).replace(/\.?0+$/,"")}%`}function XHe(s){if(!(s!=null&&s.lease_rate))return null;const t=eDs[s.lease_rate_unit||"sf_year"]??"";return`${s.lease_rate_unit==="month"?PN(s.lease_rate):`$${Number(s.lease_rate).toFixed(2).replace(/\.00$/,"")}`}${t}${s.lease_type?` ${s.lease_type}`:""}`}function jG(s,t){if(!s)return PN(t)??"Price on request";if(s.deal_type==="lease")return XHe(s)??"Rate on request";const n=s.asking_price??t;if(s.deal_type==="sale_or_lease"){const r=[PN(n),XHe(s)].filter(Boolean);return r.length?r.join(" · "):"Price on request"}return PN(n)??"Price on request"}function sL(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?r6[t.commercial_type]:"Commercial"} Opportunity`:s.property_address||`${s.city??""}, ${s.state??""}`}function $ae(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 tDs(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 K4e)(a[l.key]||n[l.key])&&r.push(l.key);return{done:r,total:K4e.length,score:Math.round(r.length/K4e.length*100)}}const Byt={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 $yt(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 sDs="https://commercial.relevelup.com",G4=q;function k7t(s){return st({queryKey:["commercial-details",s],queryFn:async()=>{const{data:t,error:n}=await G4.from("commercial_listing_details").select("*").eq("listing_id",s).maybeSingle();if(n)throw n;return t??null},enabled:!!s})}function S7t(){const s=Zt(),{user:t}=_s();return mt({mutationFn:async({listingId:n,values:r})=>{const{data:a,error:i}=await G4.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 nDs(s){return st({queryKey:["commercial-pitch",s],queryFn:async()=>{const{data:t,error:n}=await G4.from("commercial_pitch_details").select("*").eq("listing_id",s).maybeSingle();if(n)throw n;return t??null},enabled:!!s})}function C7t(){const s=Zt(),{user:t}=_s();return mt({mutationFn:async({listingId:n,values:r})=>{const{data:a,error:i}=await G4.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 A7t(){const s=Zt();return mt({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 G4.from("listings").update(l).eq("id",t);if(o)throw o;return(a||i)&&await G4.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 rDs(){const s=Zt();return mt({mutationFn:async({listingId:t,values:n})=>{const{error:r}=await G4.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 Vtt(s,t=90){return st({queryKey:["commercial-engagement",s,t],queryFn:async()=>{const n=new Date(Date.now()-t*864e5).toISOString(),{data:r,error:a}=await G4.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 Htt(s){return st({queryKey:["commercial-leads",s],queryFn:async()=>{const{data:t,error:n}=await G4.from("listing_leads").select("*").eq("listing_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]},enabled:!!s})}const Uyt="lu_commercial_session";function E7t(){try{let s=localStorage.getItem(Uyt);return s||(s=crypto.randomUUID(),localStorage.setItem(Uyt,s)),s}catch{return"anonymous"}}async function g$(s,t,n={}){try{await G4.from("commercial_engagement_events").insert({listing_id:s,event_type:t,session_id:E7t(),source:typeof document<"u"&&document.referrer||null,metadata:n})}catch{}}const aDs={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 iDs({open:s,onOpenChange:t,listingId:n,kind:r,documentId:a,requiresNda:i,brokerName:l}){const o=aDs[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),v=async()=>{if(!c.firstName.trim()||!c.email.trim()){ne.error("Name and email are required");return}if(i&&r==="om_request"&&!u){ne.error("Please acknowledge the confidentiality terms");return}f(!0);try{const{data:y,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:E7t()}});if(b)throw b;if(y!=null&&y.error)throw new Error(y.error);x({signedUrl:(y==null?void 0:y.signedUrl)??null,fileName:(y==null?void 0:y.fileName)??null}),y!=null&&y.signedUrl&&window.open(y.signedUrl,"_blank")}catch(y){ne.error(y.message||"Something went wrong. Please try again.")}finally{f(!1)}};return e.jsx(Os,{open:s,onOpenChange:y=>{t(y),y||x(null)},children:e.jsxs(Fs,{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(Vr,{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(cR,{label:"First name *",children:e.jsx(pe,{value:c.firstName,onChange:y=>d({...c,firstName:y.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsx(cR,{label:"Last name",children:e.jsx(pe,{value:c.lastName,onChange:y=>d({...c,lastName:y.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),e.jsx(cR,{label:"Email *",children:e.jsx(pe,{type:"email",value:c.email,onChange:y=>d({...c,email:y.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(cR,{label:"Company",children:e.jsx(pe,{value:c.company,onChange:y=>d({...c,company:y.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsx(cR,{label:"Phone",children:e.jsx(pe,{value:c.phone,onChange:y=>d({...c,phone:y.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),e.jsx(cR,{label:"I am a *",children:e.jsxs(ms,{value:c.role,onValueChange:y=>d({...c,role:y}),children:[e.jsx(us,{className:"border-white/15 bg-white/5 text-white",children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(ZHe).map(([y,b])=>e.jsx(Ge,{value:y,children:b},y))})]})}),r!=="om_request"&&e.jsx(cR,{label:"Message",children:e.jsx(Rs,{rows:3,value:c.message,onChange:y=>d({...c,message:y.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:y=>h(!!y),className:"mt-0.5 border-white/30"}),e.jsxs("span",{className:"text-xs leading-relaxed text-white/65",children:[e.jsx(Rm,{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:v,disabled:m,children:[m?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(jc,{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 cR({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 Gtt(s){if(!s)return[];const t=[],n=(r,a)=>{a&&t.push({label:r,value:a})};return n("Cap Rate",AEe(s.cap_rate)),n("NOI",zyt(s.noi)),n("Occupancy",s.occupancy_pct!=null?`${Math.round(Number(s.occupancy_pct))}%`:null),n("Building SF",xE(s.building_sf)),n("Available SF",xE(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?PN(s.price_per_sf,2):null),n("Price / Unit",zyt(s.price_per_unit)),n("Lease Rate",s.deal_type!=="sale"?XHe(s):null),n("Year Built",null),n("Zoning",s.zoning??null),t}function T7t({details:s,className:t="",tone:n="light"}){const r=Gtt(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 oDs(s){return st({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}=oDs(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(()=>Gtt(d).slice(0,8),[d]);if(j.useEffect(()=>{c!=null&&c.id&&g$(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=sL(c,d),v=$ae(c,d),y=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)??[],A=(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=>(A==null?void 0:A[W])&&Object.values(A[W]).some(Boolean)),D=(W,V)=>{o({kind:W,documentId:V}),g$(c.id,W==="om_request"?"om_request":W,{})};return e.jsxs("div",{className:"min-h-screen bg-[#0b0f14] text-white antialiased",children:[e.jsxs(Dl,{children:[e.jsx("title",{children:`${x} | ${v}`}),e.jsx("meta",{name:"description",content:(c.description??"").slice(0,155)||`${SL[(d==null?void 0:d.deal_type)??"sale"]} — ${v}`}),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:SL[(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:r6[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(jc,{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(ui,{className:"h-4 w-4"})," ",v]}),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:jG(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:AEe(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(Qa,{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(yM,{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(yM,{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(yM,{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),g$(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(yM,{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:PN(d==null?void 0:d.noi)},{l:"Gross income",v:PN(d==null?void 0:d.gross_income)},{l:"Operating expenses",v:PN(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?PN(d.price_per_sf,2):null},{l:"Price per unit",v:PN(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(yM,{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?xE(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(yM,{eyebrow:"Location",title:d!=null&&d.submarket?`${d.submarket} submarket`:v,children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-[1.2fr_1fr]",children:[y?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(y)}&z=${c.latitude&&c.longitude?15:12}&output=embed`,onLoad:()=>g$(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.":v}),e.jsxs("div",{className:"space-y-5",children:[(d==null?void 0:d.zoning)&&e.jsx(x$,{label:"Zoning",value:d.zoning}),(d==null?void 0:d.lot_acres)!=null&&e.jsx(x$,{label:"Site size",value:`${d.lot_acres} acres`}),(d==null?void 0:d.parking_spaces)!=null&&e.jsx(x$,{label:"Parking",value:`${d.parking_spaces} spaces`}),(d==null?void 0:d.opportunity_zone)&&e.jsx(x$,{label:"Opportunity Zone",value:"Qualified"}),E.filter(W=>W.road||W.count).map((W,V)=>e.jsx(x$,{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(x$,{label:"Submarket",value:(d==null?void 0:d.submarket)||v})]})]})}),R&&e.jsx(yM,{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=A==null?void 0:A[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(([,Z])=>Z).map(([Z,X])=>e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("dt",{className:"text-white/50",children:Z}),e.jsx("dd",{className:"font-medium tabular-nums",children:X})]},Z))})]},W)})})}),u.length>0&&e.jsx(yM,{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(ji,{className:"h-5 w-5"}):W.gate_level==="nda"?e.jsx(Rm,{className:"h-5 w-5"}):e.jsx(jc,{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||YHe[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:()=>{g$(c.id,"contact_click",{}),window.location.href=`mailto:${m.email}`},children:[e.jsx(pn,{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:()=>{g$(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:[jG(d,c.price)," · ",v]})]}),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(Os,{open:a!==null,onOpenChange:W=>!W&&i(null),children:e.jsx(Fs,{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(mr,{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(kd,{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(iDs,{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 yM({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 x$({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 qyt="/assets/levelup-logo-color-BeKd2k_g.png",cDs={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"},dDs={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"},Vyt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},Ice=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),NZ=s=>new Intl.NumberFormat("en-US").format(s);function Wtt({slugOverride:s}={}){var as,bs,Ut,Ft,is;const t=Wi(),n=s||t.slugOrId,[r]=Nc(),{data:a,isLoading:i}=ZRs(n||""),l=XRs(),o=QRs(),c=r.get("ref"),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,v]=j.useState(""),[y,b]=j.useState(""),[w,S]=j.useState(""),[A,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,Z]=j.useState(null),[X,ae]=j.useState(!1),[le,re]=j.useState(!1),[te,J]=j.useState(!1),[ce,ve]=j.useState(20),[fe,ue]=j.useState(6.5),[be,Ee]=j.useState(30),ke=j.useRef(null),[Ie,Fe]=j.useState(!1);j.useEffect(()=>{const jt=()=>Fe(window.scrollY>300);return window.addEventListener("scroll",jt,{passive:!0}),()=>window.removeEventListener("scroll",jt)},[]),j.useEffect(()=>{c&&o.mutate(c)},[c]),j.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const Ne=(a==null?void 0:a.photos)||[],Be=Ne.find(jt=>jt.is_primary)||Ne[0],Se=j.useMemo(()=>{if(!(a!=null&&a.price))return 0;const jt=a.price*(1-ce/100),zs=fe/100/12,yt=be*12;return zs===0?jt/yt:jt*zs/(1-Math.pow(1+zs,-yt))},[a==null?void 0:a.price,ce,fe,be]),Ae=async()=>{const jt=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:jt})}catch{}else await navigator.clipboard.writeText(jt),ne.success("Link copied to clipboard")},Ce=async jt=>{if(jt.preventDefault(),!d.trim()||!f.trim()||!a)return;const zs=R==="showing";if(zs&&!w){ne.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:zs?"showing_request":"info_request",preferredDate:zs?w:null,preferredTime:zs&&A||null,showingMode:zs?I:null,message:y.trim()||null}),V(!0),ne.success(zs?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(yt){console.error("Lead submission error:",yt),ne.error(`Failed to submit: ${yt.message||"Please try again"}`)}finally{U(!1)}},qe=()=>{G!==null&&Z(G===0?Ne.length-1:G-1)},ze=()=>{G!==null&&Z(G===Ne.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(xn,{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(br,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:qyt,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(br,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const Ve=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,ht=((bs=(as=a.agent)==null?void 0:as.brokerage)==null?void 0:bs.name)||((Ut=a.agent)==null?void 0:Ut.brokerage_name),Qe=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,at=a.description||"",rt=at.length>420,Ke=te||!rt?at:at.slice(0,420).trimEnd()+"…",Je=a.page_config||{},ft=jt=>{var zs;return(((zs=Je.sections)==null?void 0:zs[jt])??!0)!==!1},gt=Array.isArray(Je.addons)?Je.addons:[],es=Je.custom_note||"",Ht=Je.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(Dl,{children:[e.jsxs("title",{children:[Ve," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${Ice(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${Vyt[a.property_type]} in ${a.city}, ${a.state}. ${at.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:Ve}),e.jsx("meta",{property:"og:description",content:`${Ice(a.price)} · ${a.city}, ${a.state}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${a.slug||a.id}`}),Be&&e.jsx("meta",{property:"og:image",content:Be.photo_url}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:Ve}),e.jsx("meta",{name:"twitter:description",content:`${Ice(a.price)} · ${a.city}, ${a.state}`}),Be&&e.jsx("meta",{name:"twitter:image",content:Be.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:at,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:Ne.map(jt=>jt.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 ${Ie?"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(br,{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(Va,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),Ie&&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(([jt,zs])=>e.jsx("a",{href:`#${jt}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:zs},jt))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(TRs,{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(Hd,{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:ke,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[Be?e.jsx("img",{src:Be.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($e,{className:`${cDs[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:dDs[a.status]}),Ne.length>0&&e.jsxs("button",{onClick:()=>Z(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(jx,{className:"h-3.5 w-3.5"}),Ne.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:Ice(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:NZ(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}),ht&&e.jsx("p",{className:"text-xs text-white/60",children:ht})]}),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"]})]})})]}),ft("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:n2,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:C0,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:w_,label:"Interior",value:`${NZ(a.square_footage)} sqft`},a.lot_size&&{icon:M4,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:Ea,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:r2,label:"Price / sqft",value:`$${NZ(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((jt,zs)=>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(jt.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:jt.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:jt.value})]})]},zs))})}),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:[ft("story")&&at&&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:Ke})}),rt&&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($e,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[e.jsx(wi,{className:"h-3 w-3 mr-1.5"}),Vyt[a.property_type]]}),a.has_hoa&&e.jsx($e,{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(Ir,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(es||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(wn,{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:['"',es||a.agent_notes,'"']})]})]}),ft("gallery")&&Ne.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:()=>Z(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",Ne.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:Ne.slice(0,7).map((jt,zs)=>{const yt=["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"],gs=zs===6&&Ne.length>7;return e.jsxs("button",{onClick:()=>Z(zs),className:`${yt[zs]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:jt.photo_url,alt:`Photo ${zs+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),gs&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(jx,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",Ne.length-7," more"]})]})]},jt.id)})})]}),ft("video")&&((Ft=a.video)==null?void 0:Ft.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"})})]}),ft("map")&&Qe&&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:Qe,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(ui,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),ft("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:["$",NZ(Math.round(Se))]}),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(bx,{value:[ce],onValueChange:jt=>ve(jt[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",NZ(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:[fe.toFixed(2),"%"]})]}),e.jsx(bx,{value:[fe],onValueChange:jt=>ue(jt[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:[be," yr"]})]}),e.jsx(bx,{value:[be],onValueChange:jt=>Ee(jt[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."})]})]}),gt.map(jt=>{const zs=jt.type,yt=jt.data||{};if(zs==="extra_video"&&yt.url){const gs=String(yt.url).includes("youtu")?`https://www.youtube.com/embed/${String(yt.url).split(/[/=]/).pop()}`:yt.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:yt.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:yt.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:gs,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:yt.title||"Video"})})]},jt.id)}return zs==="3d_tour"&&yt.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:yt.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:yt.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},jt.id):zs==="floor_plan"&&yt.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:yt.title||"Layout"}),e.jsx("img",{src:yt.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},jt.id):zs==="testimonial"&&yt.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:['"',yt.quote,'"']}),yt.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",yt.author]})]},jt.id):zs==="custom_cta"&&yt.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:Ht?`${Ht}22`:"rgba(255,255,255,0.05)",border:`1px solid ${Ht||"rgba(255,255,255,0.1)"}`},children:[yt.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:yt.title}),e.jsx($,{asChild:!0,size:"lg",style:Ht?{background:Ht}:void 0,children:e.jsx("a",{href:yt.url||"#agent",children:yt.label})})]},jt.id):null})]}),e.jsxs("aside",{id:"agent",className:"lg:sticky lg:top-24 lg:self-start space-y-6",children:[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}),ht&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:ht})]})]}),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(pn,{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(pn,{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(Hyt,{submitted:W,activeTab:R,setActiveTab:D,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:f,setEmail:g,phone:x,setPhone:v,message:y,setMessage:b,preferredDate:w,setPreferredDate:S,preferredTime:A,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(Su,{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:qyt,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(Os,{open:G!==null,onOpenChange:()=>Z(null),children:e.jsxs(Fs,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(Us,{className:"sr-only",children:e.jsx($s,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>Z(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(mr,{className:"h-5 w-5"})}),G!==null&&Ne[G]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Ne[G].photo_url,alt:`Photo ${G+1}`,className:"w-full max-h-[85vh] object-contain"}),Ne.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(kd,{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," / ",Ne.length]})]})]})]})}),e.jsx(Os,{open:X,onOpenChange:ae,children:e.jsxs(Fs,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(Us,{className:"sr-only",children:e.jsx($s,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(Hyt,{submitted:W,activeTab:R,setActiveTab:D,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:f,setEmail:g,phone:x,setPhone:v,message:y,setMessage:b,preferredDate:w,setPreferredDate:S,preferredTime:A,setPreferredTime:E,showingMode:I,setShowingMode:P,isSubmitting:O,onSubmit:Ce})})]})})]})]})}function Hyt(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:v,setPreferredTime:y,showingMode:b,setShowingMode:w,isSubmitting:S,onSubmit:A}=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(ma,{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(pa,{value:n,onValueChange:E=>r(E),children:[e.jsxs(ga,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Xt,{value:"info",className:"gap-1.5",children:[e.jsx(no,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(Xt,{value:"showing",className:"gap-1.5",children:[e.jsx(Su,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:A,className:"space-y-3",children:[e.jsxs(Qt,{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:v,onValueChange:y,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 NG="/assets/levelup-logo-white-C2RAgAoG.png",uDs="/assets/listings-hero-noir-BHCJrhvU.jpg";var M7t={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(kp,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],C=p[1],M=p[2],F=p[3],z=_*F-M*C;return z?(N[0]=F*(z=1/z),N[1]=-C*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 C=p[0],M=p[1],F=p[2],z=p[3],H=p[4],Y=p[5],se=p[6],me=p[7],xe=p[8],_e=_[0],Te=_[1],De=_[2],Ue=_[3],Ye=_[4],nt=_[5],it=_[6],ut=_[7],ot=_[8];return N[0]=_e*C+Te*z+De*se,N[1]=_e*M+Te*H+De*me,N[2]=_e*F+Te*Y+De*xe,N[3]=Ue*C+Ye*z+nt*se,N[4]=Ue*M+Ye*H+nt*me,N[5]=Ue*F+Ye*Y+nt*xe,N[6]=it*C+ut*z+ot*se,N[7]=it*M+ut*H+ot*me,N[8]=it*F+ut*Y+ot*xe,N}function x(N,p){var _=Math.sin(p),C=Math.cos(p);return N[0]=C,N[1]=_,N[2]=0,N[3]=-_,N[4]=C,N[5]=0,N[6]=0,N[7]=0,N[8]=1,N}function v(){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 y(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],C=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]=C,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 A(N,p){var _=p[0],C=p[1],M=p[2],F=p[3],z=p[4],H=p[5],Y=p[6],se=p[7],me=p[8],xe=p[9],_e=p[10],Te=p[11],De=p[12],Ue=p[13],Ye=p[14],nt=p[15],it=_*H-C*z,ut=_*Y-M*z,ot=_*se-F*z,vt=C*Y-M*H,kt=C*se-F*H,ls=M*se-F*Y,At=me*Ue-xe*De,qt=me*Ye-_e*De,ts=me*nt-Te*De,ns=xe*Ye-_e*Ue,Ps=xe*nt-Te*Ue,Ws=_e*nt-Te*Ye,mn=it*Ws-ut*Ps+ot*ns+vt*ts-kt*qt+ls*At;return mn?(N[0]=(H*Ws-Y*Ps+se*ns)*(mn=1/mn),N[1]=(M*Ps-C*Ws-F*ns)*mn,N[2]=(Ue*ls-Ye*kt+nt*vt)*mn,N[3]=(_e*kt-xe*ls-Te*vt)*mn,N[4]=(Y*ts-z*Ws-se*qt)*mn,N[5]=(_*Ws-M*ts+F*qt)*mn,N[6]=(Ye*ot-De*ls-nt*ut)*mn,N[7]=(me*ls-_e*ot+Te*ut)*mn,N[8]=(z*Ps-H*ts+se*At)*mn,N[9]=(C*ts-_*Ps-F*At)*mn,N[10]=(De*kt-Ue*ot+nt*it)*mn,N[11]=(xe*ot-me*kt-Te*it)*mn,N[12]=(H*qt-z*ns-Y*At)*mn,N[13]=(_*ns-C*qt+M*At)*mn,N[14]=(Ue*ut-De*vt-Ye*it)*mn,N[15]=(me*vt-xe*ut+_e*it)*mn,N):null}function E(N,p,_){var C=p[0],M=p[1],F=p[2],z=p[3],H=p[4],Y=p[5],se=p[6],me=p[7],xe=p[8],_e=p[9],Te=p[10],De=p[11],Ue=p[12],Ye=p[13],nt=p[14],it=p[15],ut=_[0],ot=_[1],vt=_[2],kt=_[3];return N[0]=ut*C+ot*H+vt*xe+kt*Ue,N[1]=ut*M+ot*Y+vt*_e+kt*Ye,N[2]=ut*F+ot*se+vt*Te+kt*nt,N[3]=ut*z+ot*me+vt*De+kt*it,N[4]=(ut=_[4])*C+(ot=_[5])*H+(vt=_[6])*xe+(kt=_[7])*Ue,N[5]=ut*M+ot*Y+vt*_e+kt*Ye,N[6]=ut*F+ot*se+vt*Te+kt*nt,N[7]=ut*z+ot*me+vt*De+kt*it,N[8]=(ut=_[8])*C+(ot=_[9])*H+(vt=_[10])*xe+(kt=_[11])*Ue,N[9]=ut*M+ot*Y+vt*_e+kt*Ye,N[10]=ut*F+ot*se+vt*Te+kt*nt,N[11]=ut*z+ot*me+vt*De+kt*it,N[12]=(ut=_[12])*C+(ot=_[13])*H+(vt=_[14])*xe+(kt=_[15])*Ue,N[13]=ut*M+ot*Y+vt*_e+kt*Ye,N[14]=ut*F+ot*se+vt*Te+kt*nt,N[15]=ut*z+ot*me+vt*De+kt*it,N}function I(N,p,_){var C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue=_[0],Ye=_[1],nt=_[2];return p===N?(N[12]=p[0]*Ue+p[4]*Ye+p[8]*nt+p[12],N[13]=p[1]*Ue+p[5]*Ye+p[9]*nt+p[13],N[14]=p[2]*Ue+p[6]*Ye+p[10]*nt+p[14],N[15]=p[3]*Ue+p[7]*Ye+p[11]*nt+p[15]):(M=p[1],F=p[2],z=p[3],H=p[4],Y=p[5],se=p[6],me=p[7],xe=p[8],_e=p[9],Te=p[10],De=p[11],N[0]=C=p[0],N[1]=M,N[2]=F,N[3]=z,N[4]=H,N[5]=Y,N[6]=se,N[7]=me,N[8]=xe,N[9]=_e,N[10]=Te,N[11]=De,N[12]=C*Ue+H*Ye+xe*nt+p[12],N[13]=M*Ue+Y*Ye+_e*nt+p[13],N[14]=F*Ue+se*Ye+Te*nt+p[14],N[15]=z*Ue+me*Ye+De*nt+p[15]),N}function P(N,p,_){var C=_[0],M=_[1],F=_[2];return N[0]=p[0]*C,N[1]=p[1]*C,N[2]=p[2]*C,N[3]=p[3]*C,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 C=Math.sin(_),M=Math.cos(_),F=p[4],z=p[5],H=p[6],Y=p[7],se=p[8],me=p[9],xe=p[10],_e=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*C,N[5]=z*M+me*C,N[6]=H*M+xe*C,N[7]=Y*M+_e*C,N[8]=se*M-F*C,N[9]=me*M-z*C,N[10]=xe*M-H*C,N[11]=_e*M-Y*C,N}function D(N,p,_){var C=Math.sin(_),M=Math.cos(_),F=p[0],z=p[1],H=p[2],Y=p[3],se=p[8],me=p[9],xe=p[10],_e=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*C,N[1]=z*M-me*C,N[2]=H*M-xe*C,N[3]=Y*M-_e*C,N[8]=F*C+se*M,N[9]=z*C+me*M,N[10]=H*C+xe*M,N[11]=Y*C+_e*M,N}function O(N,p,_){var C=Math.sin(_),M=Math.cos(_),F=p[0],z=p[1],H=p[2],Y=p[3],se=p[4],me=p[5],xe=p[6],_e=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*C,N[1]=z*M+me*C,N[2]=H*M+xe*C,N[3]=Y*M+_e*C,N[4]=se*M-F*C,N[5]=me*M-z*C,N[6]=xe*M-H*C,N[7]=_e*M-Y*C,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 C,M,F,z=_[0],H=_[1],Y=_[2],se=Math.sqrt(z*z+H*H+Y*Y);return se0?(Ye=2*Math.sqrt(Ue+1),N[3]=.25*Ye,N[0]=(xe-Te)/Ye,N[1]=(_e-Y)/Ye,N[2]=(H-se)/Ye):z>me&&z>De?(Ye=2*Math.sqrt(1+z-me-De),N[3]=(xe-Te)/Ye,N[0]=.25*Ye,N[1]=(H+se)/Ye,N[2]=(_e+Y)/Ye):me>De?(Ye=2*Math.sqrt(1+me-z-De),N[3]=(_e-Y)/Ye,N[0]=(H+se)/Ye,N[1]=.25*Ye,N[2]=(xe+Te)/Ye):(Ye=2*Math.sqrt(1+De-z-me),N[3]=(H-se)/Ye,N[0]=(_e+Y)/Ye,N[1]=(xe+Te)/Ye,N[2]=.25*Ye),N}function X(N,p){var _=p[0],C=p[1],M=p[2],F=p[3],z=_+_,H=C+C,Y=M+M,se=_*z,me=C*z,xe=C*H,_e=M*z,Te=M*H,De=M*Y,Ue=F*z,Ye=F*H,nt=F*Y;return N[0]=1-xe-De,N[1]=me+nt,N[2]=_e-Ye,N[3]=0,N[4]=me-nt,N[5]=1-se-De,N[6]=Te+Ue,N[7]=0,N[8]=_e+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,_,C,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/(C-M);N[10]=(M+C)*z,N[14]=2*M*C*z}else N[10]=-1,N[14]=-2*C;return N},le=function(N,p,_,C,M,F,z){var H=1/(p-_),Y=1/(C-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*Y,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+C)*Y,N[14]=(z+F)*se,N[15]=1,N},re=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],C=N[2];return Math.sqrt(p*p+_*_+C*C)}function ve(N,p,_){var C=new h(3);return C[0]=N,C[1]=p,C[2]=_,C}function fe(N,p,_,C){return N[0]=p,N[1]=_,N[2]=C,N}function ue(N,p,_){return N[0]=p[0]+_[0],N[1]=p[1]+_[1],N[2]=p[2]+_[2],N}function be(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 ke(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 Ie(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 Ne(N,p,_,C){return N[0]=p[0]+_[0]*C,N[1]=p[1]+_[1]*C,N[2]=p[2]+_[2]*C,N}function Be(N,p){var _=p[0]-N[0],C=p[1]-N[1],M=p[2]-N[2];return Math.sqrt(_*_+C*C+M*M)}function Se(N,p){var _=p[0]-N[0],C=p[1]-N[1],M=p[2]-N[2];return _*_+C*C+M*M}function Ae(N){var p=N[0],_=N[1],C=N[2];return p*p+_*_+C*C}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],C=p[1],M=p[2],F=_*_+C*C+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 Ve(N,p,_){var C=p[0],M=p[1],F=p[2],z=_[0],H=_[1],Y=_[2];return N[0]=M*Y-F*H,N[1]=F*z-C*Y,N[2]=C*H-M*z,N}function ht(N,p,_,C){var M=p[0],F=p[1],z=p[2];return N[0]=M+C*(_[0]-M),N[1]=F+C*(_[1]-F),N[2]=z+C*(_[2]-z),N}function Qe(N,p,_){var C=p[0],M=p[1],F=p[2],z=_[3]*C+_[7]*M+_[11]*F+_[15];return N[0]=(_[0]*C+_[4]*M+_[8]*F+_[12])/(z=z||1),N[1]=(_[1]*C+_[5]*M+_[9]*F+_[13])/z,N[2]=(_[2]*C+_[6]*M+_[10]*F+_[14])/z,N}function at(N,p,_){var C=p[0],M=p[1],F=p[2];return N[0]=C*_[0]+M*_[3]+F*_[6],N[1]=C*_[1]+M*_[4]+F*_[7],N[2]=C*_[2]+M*_[5]+F*_[8],N}function rt(N,p,_){var C=_[0],M=_[1],F=_[2],z=_[3],H=p[0],Y=p[1],se=p[2],me=M*se-F*Y,xe=F*H-C*se,_e=C*Y-M*H;return N[0]=H+z*(me+=me)+M*(_e+=_e)-F*(xe+=xe),N[1]=Y+z*xe+F*me-C*_e,N[2]=se+z*_e+C*xe-M*me,N}function Ke(N){return N[0]=0,N[1]=0,N[2]=0,N}function Je(N,p){return N[0]===p[0]&&N[1]===p[1]&&N[2]===p[2]}var ft=be,gt=Ee,es=ce;function Ht(){var N=new h(4);return h!=Float32Array&&(N[0]=0,N[1]=0,N[2]=0,N[3]=0),N}function as(N,p,_,C){var M=new h(4);return M[0]=N,M[1]=p,M[2]=_,M[3]=C,M}function bs(N,p,_){return N[0]=p[0]*_,N[1]=p[1]*_,N[2]=p[2]*_,N[3]=p[3]*_,N}function Ut(N,p){var _=p[0],C=p[1],M=p[2],F=p[3],z=_*_+C*C+M*M+F*F;return z>0&&(z=1/Math.sqrt(z)),N[0]=_*z,N[1]=C*z,N[2]=M*z,N[3]=F*z,N}function Ft(N,p,_){var C=p[0],M=p[1],F=p[2],z=p[3];return N[0]=_[0]*C+_[4]*M+_[8]*F+_[12]*z,N[1]=_[1]*C+_[5]*M+_[9]*F+_[13]*z,N[2]=_[2]*C+_[6]*M+_[10]*F+_[14]*z,N[3]=_[3]*C+_[7]*M+_[11]*F+_[15]*z,N}function is(){var N=new h(4);return h!=Float32Array&&(N[0]=0,N[1]=0,N[2]=0),N[3]=1,N}function jt(N){return N[0]=0,N[1]=0,N[2]=0,N[3]=1,N}function zs(N,p){var _=2*Math.acos(p[3]),C=Math.sin(_/2);return C>u?(N[0]=p[0]/C,N[1]=p[1]/C,N[2]=p[2]/C):(N[0]=1,N[1]=0,N[2]=0),_}function yt(N,p,_){_*=.5;var C=p[0],M=p[1],F=p[2],z=p[3],H=Math.sin(_),Y=Math.cos(_);return N[0]=C*Y+z*H,N[1]=M*Y+F*H,N[2]=F*Y-M*H,N[3]=z*Y-C*H,N}function gs(N,p,_){_*=.5;var C=p[0],M=p[1],F=p[2],z=p[3],H=Math.sin(_),Y=Math.cos(_);return N[0]=C*Y-F*H,N[1]=M*Y+z*H,N[2]=F*Y+C*H,N[3]=z*Y-M*H,N}function Ss(N,p,_){_*=.5;var C=p[0],M=p[1],F=p[2],z=p[3],H=Math.sin(_),Y=Math.cos(_);return N[0]=C*Y+M*H,N[1]=M*Y-C*H,N[2]=F*Y+z*H,N[3]=z*Y-F*H,N}te(),Ht();var Ds,Bt,zt,vs=Ut,dn=(Ds=te(),Bt=ve(1,0,0),zt=ve(0,1,0),function(N,p,_){var C=ze(p,_);return C<-.999999?(Ve(Ds,Bt,p),es(Ds)<1e-6&&Ve(Ds,zt,p),qe(Ds,Ds),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,Ds,Math.PI),N):C>.999999?(N[0]=0,N[1]=0,N[2]=0,N[3]=1,N):(Ve(Ds,p,_),N[0]=Ds[0],N[1]=Ds[1],N[2]=Ds[2],N[3]=1+C,vs(N,N))});function Ks(){var N=new h(2);return h!=Float32Array&&(N[0]=0,N[1]=0),N}function Cn(N,p){var _=new h(2);return _[0]=N,_[1]=p,_}function Rr(N,p,_){return N[0]=p,N[1]=_,N}function ia(N,p,_){return N[0]=p[0]+_[0],N[1]=p[1]+_[1],N}function Hs(N,p,_){return N[0]=p[0]-_[0],N[1]=p[1]-_[1],N}function Br(N,p,_){return N[0]=p[0]*_,N[1]=p[1]*_,N}function Ur(N){var p=N[0],_=N[1];return Math.sqrt(p*p+_*_)}function Wn(N,p){var _=p[0],C=p[1],M=_*_+C*C;return M>0&&(M=1/Math.sqrt(M)),N[0]=p[0]*M,N[1]=p[1]*M,N}function Sn(N,p){return N[0]*p[0]+N[1]*p[1]}is(),is(),f();var Fn=Hs;function bn(N,p,_,C){const M=3*N,F=3*(_-N)-M,z=1-M-F,H=3*p,Y=3*(C-p)-H,se=1-H-Y;return function(me,xe=1e-6){if(me<=0)return 0;if(me>=1)return 1;let _e=me;for(let Ue=0;Ue<8;Ue++){const Ye=((z*_e+F)*_e+M)*_e-me;if(Math.abs(Ye)Ye?Te=_e:De=_e,_e=.5*(Te+De)}return((se*_e+Y)*_e+H)*_e}}function xs(N,p){this.x=N,this.y=p}function Tr(N,p){if(Array.isArray(N)){if(!Array.isArray(p)||N.length!==p.length)return!1;for(let _=0;__;){if(C-_>600){const Y=C-_+1,se=p-_+1,me=Math.log(Y),xe=.5*Math.exp(2*me/3),_e=.5*Math.sqrt(me*xe*(Y-xe)/Y)*(se-Y/2<0?-1:1);Lr(N,p,Math.max(_,Math.floor(p-se*xe/Y+_e)),Math.min(C,Math.floor(p+(Y-se)*xe/Y+_e)),M)}const F=N[p];let z=_,H=C;for(la(N,_,p),M(N[C],F)>0&&la(N,_,C);z0;)H--}M(N[_],F)===0?la(N,_,H):(H++,la(N,H,C)),H<=p&&(_=H+1),p<=H&&(C=H-1)}}function la(N,p,_){const C=N[p];N[p]=N[_],N[_]=C}function Xn(N,p){return Np?1:0}function wr(N){let p=0;for(let _,C,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 Ln(N,p,_){const C=N[0]-p[0],M=N[1]-p[1],F=N[0]-_[0],z=N[1]-_[1];return C*z-F*M===0&&C*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 Ka(N,p,_=!1){let C=!1;for(let M=0,F=p.length;M0&&H<0||z<0&&H>0}function Tc(N,p,_,C){return(M=[C[0]-_[0],C[1]-_[1]])[0]*(F=[p[0]-N[0],p[1]-N[1]])[1]-M[1]*F[0]!==0&&!(!uo(N,p,_,C)||!uo(_,C,N,p));var M,F}function Fd(N){const p=new xs(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),_=new xs(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const C of N[0])p.x>C.x&&(p.x=C.x),p.y>C.y&&(p.y=C.y),_.x=1)return 1;const p=N*N,_=p*N;return 4*(N<.5?_:3*(N-p)+_-.75)}const ro=bn(.25,.1,.25,1);function ea(N,p,_){return Math.min(_,Math.max(p,N))}function pc(N,p,_){return(_=ea((_-N)/(p-N),0,1))*_*(3-2*_)}function ml(N,p,_){const C=_-p,M=((N-p)%C+C)%C+p;return M===p?_:M}function Co(N,p,_){if(!N.length)return _(null,[]);let C=N.length;const M=new Array(N.length);let F=null;N.forEach((z,H)=>{p(z,(Y,se)=>{Y&&(F=Y),M[H]=se,--C===0&&_(F,M)})})}function mu(N,p){const _={};for(let C=0;C>p/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,N)}()}function Dr(N){return N<=1?1:Math.pow(2,Math.ceil(Math.log2(N)))}function Hi(N){return!!N&&ti.test(N)}function zc(N,p){N.forEach(_=>{p[_]&&(p[_]=p[_].bind(p))})}function Bc(N,p,_){const C={};for(const M in N)C[M]=p.call(this,N[M],M,N);return C}function gc(N,p,_){const C={};for(const M in N)p.call(this,N[M],M,N)&&(C[M]=N[M]);return C}function $l(N){return Array.isArray(N)?N.map($l):typeof N=="object"&&N?Bc(N,$l):N}function sg(N,p){for(let _=0;_(p.y-N.y)*(_.x-N.x)}function Mh([N,p,_]){const C=Yr(p+90),M=Yr(_);return{x:N*Math.cos(C)*Math.sin(M),y:N*Math.sin(C)*Math.sin(M),z:N*Math.cos(M),azimuthal:p,polar:_}}function lm(N,p,_){const C=Math.sqrt(N*N+p*p+_*_),M=C>0?Math.acos(_/C)*Ho:0;let F=N!==0||p!==0?Math.atan2(-p,-N)*Ho+90:0;return F<0&&(F+=360),[C,F,M]}function Yc(N){return(typeof self<"u"||N!==void 0)&&typeof WorkerGlobalScope<"u"&&(N!==void 0?N:self)instanceof WorkerGlobalScope}function ws(N){const p={};if(N.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(_,C,M,F)=>{const z=M||F;return p[C]=!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 ao(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 cm(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 Gg(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 Fl,Ol,fy,Kd,Vh,cf;function Wy(){return Fl??(Fl=self.OffscreenCanvas&&!!new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),Fl}const ah={requestIdleCallback:N=>{if(typeof requestIdleCallback<"u")return requestIdleCallback(N);setTimeout(()=>N({didTimeout:!1,timeRemaining:()=>50}),0)},now:()=>Kd!==void 0?Kd:performance.now(),setNow(N){Kd=N},restoreNow(){Kd=void 0},frame(N){const p=requestAnimationFrame(N);return{cancel:()=>cancelAnimationFrame(p)}},getImageData(N,p=0){const{width:_,height:C}=N;Vh||(Vh=document.createElement("canvas"));const M=Vh.getContext("2d",{willReadFrequently:!0});if(!M)throw new Error("failed to create canvas 2d context");return(_>Vh.width||C>Vh.height)&&(Vh.width=_,Vh.height=C),M.clearRect(-p,-p,_+2*p,C+2*p),M.drawImage(N,0,0,_,C),M.getImageData(-p,-p,_+2*p,C+2*p)},resolveURL:N=>(Ol||(Ol=document.createElement("a")),Ol.href=N,Ol.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(fy??(fy=window.matchMedia("(prefers-reduced-motion: reduce)")),fy.matches)},hasCanvasFingerprintNoise(){if(cf!==void 0)return cf;if(!Wy())return cf=!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 js=500,Ts=50;const Ns=["language","worldview","jobid"];let Ms;function hn(){try{return caches}catch{}}function fn(){const N=hn();N&&Ms==null&&(Ms=N.open(Wt))}let gn=1/0;function Mn(N){return xt.API_URL_REGEX.test(N)}function ar(N){return N.indexOf("mapbox:")===0}function Jn(N){return xt.API_CDN_URL_REGEX.test(N)}function er(N){return xt.API_SPRITE_REGEX.test(N)}function xr(N){return xt.API_STYLE_REGEX.test(N)&&!er(N)}const gr={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(gr);class qa extends Error{constructor(p,_,C){super(),this.url=C,this.statusText=p,this.status=_}get message(){return this.status===401&&Mn(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 et(N){return typeof N=="object"&&N!==null&&"status"in N&&N.status===404}const Gt=Yc()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Es=/^\w+:/,on=/[\r\n]+/;async function en(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 tr(N,p){return p&&p.throwIfAborted(),(_=N.url).startsWith("file:")||Gt().startsWith("file:")&&!Es.test(_)?async function(C,M){return new Promise((F,z)=>{const H=new XMLHttpRequest,Y=()=>{M.removeEventListener("abort",Y),H.abort(),z(M.reason)};M&&M.addEventListener("abort",Y),H.open(C.method||"GET",C.url,!0),C.type==="arrayBuffer"&&(H.responseType="arraybuffer");for(const se in C.headers)H.setRequestHeader(se,C.headers[se]);C.type==="json"&&(H.responseType="text",H.setRequestHeader("Accept","application/json")),H.withCredentials=C.credentials==="include",H.onerror=()=>{M&&M.removeEventListener("abort",Y),z(new Error(H.statusText))},H.onload=()=>{if(M&&M.removeEventListener("abort",Y),(H.status>=200&&H.status<300||H.status===0)&&H.response!==null){let se=H.response;if(C.type==="json")try{se=JSON.parse(H.response)}catch(xe){return void z(xe)}const me=new Headers;H.getAllResponseHeaders().trim().split(on).forEach(xe=>{const _e=xe.split(": "),Te=_e.shift(),De=_e.join(": ");Te&&me.set(Te,De)}),F({data:se,headers:me})}else z(new qa(H.statusText,H.status,C.url))},H.send(C.body)})}(N,p):async function(C,M){const F=new Request(C.url,{method:C.method||"GET",body:C.body,credentials:C.credentials,headers:C.headers,referrer:Gt(),referrerPolicy:C.referrerPolicy,signal:M}),z=(H=F.url).indexOf("sku=")>0&&Mn(H);var H;if(C.type==="json"&&F.headers.set("Accept","application/json"),z){let _e=null;try{_e=await async function(Te){if(fn(),Ms==null)return null;const De=await Ms;let Ue=$t(Te.url,{persistentParams:Ns});const Ye=Te.headers.get("Range");Ye&&(Ue=Rt(Ue,{range:Ye}));const nt=await De.match(Ue);if(!nt)return null;const it=function(ut){if(!ut)return!1;const ot=new Date(ut.headers.get("expires")||0),vt=ws(ut.headers.get("cache-control")||"");return Number(ot)>Date.now()&&!vt["no-cache"]}(nt);return De.delete(Ue).catch(ut=>Yo(ut.message)),it&&De.put(Ue,nt.clone()).catch(ut=>Yo(ut.message)),{response:nt,fresh:it}}(F)}catch(Te){Te.message!=="SecurityError"&&Yo(Te.toString())}if(_e&&_e.fresh)return M&&M.throwIfAborted(),en(C,_e.response)}const Y=Date.now();let se;try{se=await fetch(F)}catch(_e){throw _e.name==="AbortError"?_e:new Error(`${_e.message} ${C.url}`,{cause:_e})}if(M&&M.throwIfAborted(),!se.ok)throw new qa(se.statusText,se.status,C.url);const me=z?se.clone():null,xe=await en(C,se);return me&&async function(_e,Te,De){if(fn(),Ms==null)return;const Ue=ws(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 nt=Ye.headers.get("expires");if(!nt||new Date(nt).getTime()-De<42e4)return;let it=$t(_e.url,{persistentParams:Ns});if(Te.status===206){const vt=_e.headers.get("Range");if(!vt)return;Ye.status=200,it=Rt(it,{range:vt})}const ut=new Response((ot=Te.status)!==200&&ot!==404&&[101,103,204,205,304].includes(ot)?null:Te.body,Ye);var ot;if(fn(),Ms!=null)try{await(await Ms).put(it,ut)}catch(vt){Yo(vt.message)}}(F,me,Y),xe}(N,p);var _}async function sr(N,p){return tr(Object.assign(N,{type:"json"}),p)}async function Xr(N,p){return tr(Object.assign(N,{type:"arrayBuffer"}),p)}function sa(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",eo={create:"create",load:"load",fullLoad:"fullLoad"},xo={mark(N){performance.mark(N)},measure(N,p,_){performance.measure(N,p,_)}};function io(N){const p=N.name.split("?")[0];return Jn(p)&&p.includes("mapbox-gl.js")?"javascript":Jn(p)&&p.includes("mapbox-gl.css")?"css":function(_){return xt.API_FONTS_REGEX.test(_)}(p)?"fontRange":er(p)?"sprite":xr(p)?"style":function(_){return xt.API_TILEJSON_REGEX.test(_)}(p)?"tilejson":"other"}const Lo=/(\.(png|jpg)\d*)(?=$)/,Ul=/^.+\/v4\//,fo=/\.[\w]+$/,nl=/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/,Pl=/^access_token=(.*)$/,Cd="NO_ACCESS_TOKEN",au=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function Vt(N){const p=N.match(au);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 Nn(N){const p=N.params.length?`?${N.params.join("&")}`:"";return`${N.protocol}://${N.authority}${N.path}${p}`}const nr="mapbox.eventData";function na(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 Wr(N){return!(!xt.EVENTS_URL||!N&&!xt.ACCESS_TOKEN)}let Ca;const gi=/^[\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 _=na(xt.ACCESS_TOKEN);let C="";return C=_&&_.u?btoa(encodeURIComponent(_.u).replace(/%([0-9A-F]{2})/g,(M,F)=>String.fromCharCode(+("0x"+F)))):xt.ACCESS_TOKEN||"",p?`${nr}.${p}:${C}`:`${nr}:${C}`}fetchEventData(){const p=No("localStorage"),_=this.getStorageKey(),C=this.getStorageKey("uuid"),M=this.getStorageKey("uuidTimestamp");if(p)try{const F=localStorage.getItem(_);F&&(this.eventData=JSON.parse(F));const z=localStorage.getItem(C);z&&(this.anonId=z);const H=localStorage.getItem(M);H&&(this.anonIdTimestamp=Number(H));const Y=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,_,C,M){if(!xt.EVENTS_URL)return;const F=Vt(xt.EVENTS_URL);F.params.push(`access_token=${M||xt.ACCESS_TOKEN||""}`);const z={event:this.type,created:new Date(p).toISOString()},H=_?Object.assign(z,_):z,Y={url:Nn(F),headers:{"Content-Type":"text/plain"},body:JSON.stringify([H])};this.pendingRequest=!0,async function(se){return tr(Object.assign(se,{method:"POST"}),void 0)}(Y).then(()=>{this.pendingRequest=!1,C(null),this.saveEventData(),this.processRequests()}).catch(se=>{this.pendingRequest=!1,C(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(!Wr(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:C}=this.queue.shift();this.postEvent(p,_,()=>{},C)}}const Pc=new class extends el{constructor(N){super("appUserTurnstile"),this._customAccessToken=N}postTurnstileEvent(N,p){Wr(p)&&Array.isArray(N)&&N.some(_=>ar(_)||Mn(_))&&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=na(xt.ACCESS_TOKEN),p=N?N.u:xt.ACCESS_TOKEN;let _=p!==this.eventData.tokenU;Hi(this.anonId)||(this.refreshUUID(),_=!0);const{timestamp:C,customAccessToken:M}=this.queue.shift();if(this.eventData.lastSuccess){const z=new Date(this.eventData.lastSuccess),H=new Date(C),Y=(C-this.eventData.lastSuccess)/864e5;_=_||Y>=1||Y<-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};Ca&&(F.sdkInfo=Ca),this.postEvent(C,F,z=>{z||(this.eventData.lastSuccess=C,this.eventData.tokenU=p)},M)}},Eu=Pc.postTurnstileEvent.bind(Pc),iu=new class extends el{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(N,p,_,C){this.skuToken=p,this.errorCb=C,xt.EVENTS_URL&&(_||xt.ACCESS_TOKEN?this.queueRequest({id:N,timestamp:Date.now()},_):this.errorCb(new Error(Cd)))}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 C={version:"2.2",sdkIdentifier:"mapbox-gl-js",sdkVersion:d,skuId:La,skuToken:this.skuToken,userId:this.anonId,bundleFormat:"umd",bundleDistribution:Ia};Ca&&(C.sdkInfo=Ca),this.postEvent(p,C,M=>{M?this.errorCb(M):N&&(this.success[N]=!0)},_)}remove(){this.errorCb=null}},dm=iu.postMapLoadEvent.bind(iu),Ad=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=nd(),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:C,importedStyles:M}=p;if(!Wr(N))return;const F=this.getMapInstanceId(_),z={mapInstanceId:F,eventId:this.getEventId(F),style:C};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,()=>{},_)}},fu=Ad.postStyleLoadEvent.bind(Ad),Zc=new zo({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),rd=Zc.postMetricsEvent.bind(Zc),ih=new zo({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),Pf=ih.postMetricsEvent.bind(ih),Od=new class extends el{constructor(){super("gljs.performance")}postPerformanceEvent(N,p){Wr(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(),C=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 nt=`${Ue}ResolveRangeMin`,it=`${Ue}ResolveRangeMax`,ut=`${Ue}RequestCount`,ot=`${Ue}RequestCachedCount`;De[nt]=Math.min(De[nt]||1/0,Ye.startTime),De[it]=Math.max(De[it]||-1/0,Ye.responseEnd);const vt=kt=>{De[kt]===void 0&&(De[kt]=0),++De[kt]};Ye.transferSize!==void 0&&Ye.transferSize===0&&vt(ot),vt(ut)}}return De}(function(Te,De){const Ue={};if(Te)for(const Ye of Te){const nt=De(Ye);Ue[nt]===void 0&&(Ue[nt]=[]),Ue[nt].push(Ye)}return Ue}(F,io)),Y=window.devicePixelRatio,se=navigator.connection||navigator.mozConnection||navigator.webkitConnection,me=se?se.effectiveType:void 0,xe={counters:[],metadata:[],attributes:[]},_e=(Te,De,Ue)=>{Ue!=null&&Te.push({name:De,value:Ue.toString()})};for(const Te in H)_e(xe.counters,Te,H[Te]);if(M.interactionRange[0]!==1/0&&M.interactionRange[1]!==-1/0&&(_e(xe.counters,"interactionRangeMin",M.interactionRange[0]),_e(xe.counters,"interactionRangeMax",M.interactionRange[1])),z)for(const Te of Object.values(eo)){const De=z.find(Ue=>Ue.name===Te);De&&_e(xe.counters,Te,De.startTime)}return _e(xe.counters,"visibilityHidden",M.visibilityHidden),_e(xe.attributes,"style",function(Te){if(Te)for(const De of Te){const Ue=De.name.split("?")[0];if(xr(Ue)){const Ye=Ue.split("/").slice(-2);if(Ye.length===2)return`mapbox://styles/${Ye[0]}/${Ye[1]}`}}}(F)),_e(xe.attributes,"terrainEnabled",M.terrainEnabled?"true":"false"),_e(xe.attributes,"fogEnabled",M.fogEnabled?"true":"false"),_e(xe.attributes,"projection",M.projection),_e(xe.attributes,"zoom",M.zoom),_e(xe.metadata,"devicePixelRatio",Y),_e(xe.metadata,"connectionEffectiveType",me),_e(xe.metadata,"navigatorUserAgent",navigator.userAgent),_e(xe.metadata,"screenWidth",window.screen.width),_e(xe.metadata,"screenHeight",window.screen.height),_e(xe.metadata,"windowWidth",window.innerWidth),_e(xe.metadata,"windowHeight",window.innerHeight),_e(xe.metadata,"mapWidth",M.width/Y),_e(xe.metadata,"mapHeight",M.height/Y),_e(xe.metadata,"webglRenderer",M.renderer),_e(xe.metadata,"webglVendor",M.vendor),_e(xe.metadata,"sdkVersion",d),_e(xe.metadata,"sdkIdentifier","mapbox-gl-js"),xe}(p);for(const M of C.metadata);for(const M of C.counters);for(const M of C.attributes);this.postEvent(N,C,()=>{},_)}},ad=Od.postPerformanceEvent.bind(Od),Ph=new class extends el{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(N,p,_,C){if(!xt.API_URL||!xt.SESSION_PATH)return;const M=Vt(xt.API_URL+xt.SESSION_PATH);M.params.push(`sku=${p||""}`),M.params.push(`access_token=${C||xt.ACCESS_TOKEN||""}`);const F={url:Nn(M),headers:{"Content-Type":"text/plain"}};this.pendingRequest=!0,async function(z){return tr(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,_,C){this.skuToken=p,this.errorCb=C,xt.EVENTS_URL&&xt.SESSION_PATH&&xt.API_URL&&(_||xt.ACCESS_TOKEN?this.queueRequest({id:N,timestamp:Date.now()},_):this.errorCb(new Error(Cd)))}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,C=>{C?this.errorCb(C):N&&(this.success[N]=!0)},_)}remove(){this.errorCb=null}},Hu=Ph.getSessionAPI.bind(Ph),zd=new Set;function dd(N,p=0){const M=N.length,F=M-(3&M);let z,H=0|p,Y=0;for(;Y>>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(Y+2))<<16),se>=2&&(z^=(255&N.charCodeAt(Y+1))<<8),z^=255&N.charCodeAt(Y),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 zl{constructor(p,..._){Object.assign(this,_[0]||{}),this.type=p}}class Xi extends zl{constructor(p,_={}){super("error",{error:p,..._}),this.error=p}}function Ed(N,p,_){_[N]&&_[N].includes(p)||(_[N]=_[N]||[],_[N].push(p))}function ou(N,p,_){if(_[N]){const C=_[N].indexOf(p);C!==-1&&_[N].splice(C,1)}}class Xc{constructor(){this._listeners={},this._oneTimeListeners={}}on(p,_){return Ed(p,_,this._listeners),this}off(p,_){return ou(p,_,this._listeners),ou(p,_,this._oneTimeListeners),this}once(p,_){return _?(Ed(p,_,this._oneTimeListeners),this):new Promise(C=>{this.once(p,C)})}fire(p,_){const C=typeof p=="string"?new zl(p,_):p,M=C.type;if(this.listens(M)){C.target=this;const F=this._listeners[M]?this._listeners[M].slice():[];for(const Y of F)Y.call(this,C);const z=this._oneTimeListeners[M]?this._oneTimeListeners[M].slice():[];for(const Y of z)ou(M,Y,this._oneTimeListeners),Y.call(this,C);const H=this._eventedParent;if(H){const Y=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(C,Y),H.fire(C)}}else C instanceof Xi&&console.error(C.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 vd{constructor(p){typeof p=="string"?this.name=p:(this.name=p.name,this.iconsetId=p.iconsetId)}static from(p){return new vd(p)}static toString(p){return p.iconsetId?`${p.name}${p.iconsetId}`:p.name}static parse(p){const[_,C]=p.split("");return new vd({name:_,iconsetId:C})}static isEqual(p,_){return p.name===_.name&&p.iconsetId===_.iconsetId}toString(){return vd.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var Ap,Dv={},Px=function(){if(Ap)return Dv;Ap=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 C(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{Dv.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 Y=H.indexOf("("),se=H.indexOf(")");if(Y!==-1&&se+1===H.length){var me=H.substr(0,Y),xe=H.substr(Y+1,se-(Y+1)).split(","),_e=1;switch(me){case"rgba":if(xe.length!==4)return null;_e=C(xe.pop());case"rgb":return xe.length!==3?null:[_(xe[0]),_(xe[1]),_(xe[2]),_e];case"hsla":if(xe.length!==4)return null;_e=C(xe.pop());case"hsl":if(xe.length!==3)return null;var Te=(parseFloat(xe[0])%360+360)%360/360,De=C(xe[1]),Ue=C(xe[2]),Ye=Ue<=.5?Ue*(De+1):Ue+De-Ue*De,nt=2*Ue-Ye;return[p(255*M(nt,Ye,Te+1/3)),p(255*M(nt,Ye,Te)),p(255*M(nt,Ye,Te-1/3)),_e];default:return null}}return null}}catch{}return Dv}();function ya(N,p,_){return N*(1-_)+p*_}const Ky=new Map;class Ci{constructor(p,_,C,M=1){this.r=p,this.g=_,this.b=C,this.a=M}static parse(p){if(!p)return;if(p instanceof Ci)return p;if(typeof p!="string")return;const _=Ky.get(p);if(_)return _;const C=Px.parseCSSColor(p);if(!C)return;const M=new Ci(C[0]/255,C[1]/255,C[2]/255,C[3]);return Ky.set(p,M),M}toString(){const{r:p,g:_,b:C,a:M}=this;return`rgba(${Math.round(255*p)},${Math.round(255*_)},${Math.round(255*C)},${M})`}toNonPremultipliedRenderColor(p){const{r:_,g:C,b:M,a:F}=this;return new Om(p,_,C,M,F)}toPremultipliedRenderColor(p){const{r:_,g:C,b:M,a:F}=this;return new Ix(p,_*F,C*F,M*F,F)}clone(){return new Ci(this.r,this.g,this.b,this.a)}}class Wg{constructor(p,_,C,M,F,z=!1){if(this.premultiplied=!1,this.premultiplied=z,p){const H=p.image.height,Y=H*H;this.premultiplied?(_=F===0?0:_/F*(H-1),C=F===0?0:C/F*(H-1),M=F===0?0:M/F*(H-1)):(_*=H-1,C*=H-1,M*=H-1),_=Math.max(0,Math.min(H-1,_)),C=Math.max(0,Math.min(H-1,C)),M=Math.max(0,Math.min(H-1,M));const se=Math.floor(_),me=Math.floor(C),xe=Math.floor(M),_e=Math.ceil(_),Te=Math.ceil(C),De=Math.ceil(M),Ue=_-se,Ye=C-me,nt=M-xe,it=p.image.data,ut=4*(se+me*Y+xe*H),ot=4*(se+me*Y+De*H),vt=4*(se+Te*Y+xe*H),kt=4*(se+Te*Y+De*H),ls=4*(_e+me*Y+xe*H),At=4*(_e+me*Y+De*H),qt=4*(_e+Te*Y+xe*H),ts=4*(_e+Te*Y+De*H);this.r=ya(ya(ya(it[ut],it[ot],nt),ya(it[vt],it[kt],nt),Ye),ya(ya(it[ls],it[At],nt),ya(it[qt],it[ts],nt),Ye),Ue)/255*(this.premultiplied?F:1),this.g=ya(ya(ya(it[ut+1],it[ot+1],nt),ya(it[vt+1],it[kt+1],nt),Ye),ya(ya(it[ls+1],it[At+1],nt),ya(it[qt+1],it[ts+1],nt),Ye),Ue)/255*(this.premultiplied?F:1),this.b=ya(ya(ya(it[ut+2],it[ot+2],nt),ya(it[vt+2],it[kt+2],nt),Ye),ya(ya(it[ls+2],it[At+2],nt),ya(it[qt+2],it[ts+2],nt),Ye),Ue)/255*(this.premultiplied?F:1),this.a=F}else this.r=_,this.g=C,this.b=M,this.a=F}toArray(){const{r:p,g:_,b:C,a:M}=this;return[255*p,255*_,255*C,M]}toHslaArray(){let{r:p,g:_,b:C,a:M}=this;if(this.premultiplied){if(M===0)return[0,0,0,0];const De=1/M;p*=De,_*=De,C*=De}const F=Math.min(Math.max(p,0),1),z=Math.min(Math.max(_,0),1),H=Math.min(Math.max(C,0),1),Y=Math.min(F,z,H),se=Math.max(F,z,H),me=se-Y,xe=.5*(Y+se);if(me===0)return[0,0,100*xe,M];const _e=xe>.5?me/(2-se-Y):me/(se+Y);let Te;switch(se){case F:Te=60*((z-H)/me+(zya(C,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 kc=Object.freeze({__proto__:null,array:Gu,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[C,M]of _)this.bindings[C]=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 pu={kind:"null"},da={kind:"number"},Ao={kind:"string"},fl={kind:"boolean"},Qc={kind:"color"},ng={kind:"object"},Wo={kind:"value"},B0={kind:"collator"},xh={kind:"formatted"},df={kind:"resolvedImage"};function Bd(N,p){return{kind:"array",itemType:N,N:p}}function gu(N){if(N.kind==="array"){const p=gu(N.itemType);return typeof N.N=="number"?`array<${p}, ${N.N}>`:N.itemType.kind==="value"?"array":`array<${p}>`}return N.kind}const R_=[pu,da,Ao,fl,Qc,xh,ng,Bd(Wo),df];function Fv(N,p){if(p.kind==="error")return null;if(N.kind==="array"){if(p.kind==="array"&&(p.N===0&&p.itemType.kind==="value"||!Fv(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 R_)if(!Fv(_,p))return null}}return`Expected ${gu(N)} but found ${gu(p)} instead.`}function Lx(N,p){return p.some(_=>_==="null"?N===null:_==="array"?Array.isArray(N):_==="object"?N&&!Array.isArray(N)&&typeof N=="object":_===typeof N)}function Mb(N,p){return N.kind==="array"&&p.kind==="array"?N.N===p.N&&Mb(N.itemType,p.itemType):N.kind===p.kind}class Ww{constructor(p,_,C){this.sensitivity=p?_?"variant":"case":_?"accent":"base",this.locale=C,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 zm{constructor(p,_,C,M,F){this.text=p.normalize?p.normalize():p,this.image=_,this.scale=C,this.fontStack=M,this.textColor=F}}class xu{constructor(p){this.sections=p}static fromString(p){return new xu([new zm(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 xu?p:xu.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 C={};_.fontStack&&(C["text-font"]=["literal",_.fontStack.split(",")]),_.scale&&(C["font-scale"]=_.scale),_.textColor&&(C["text-color"]=["rgba"].concat(_.textColor.toNonPremultipliedRenderColor(null).toArray())),p.push(C)}return p}}class Ih{constructor(p,_={}){this.id=vd.from(p),this.params=_.params,this.sx=_.sx||1,this.sy=_.sy||1}toString(){return JSON.stringify(this)}static parse(p){let _,C,M,F;try{({id:_,params:C,sx:M,sy:F}=JSON.parse(p)||{})}catch{return null}return _?new Ih(_,{params:C,sx:M,sy:F}):null}scaleSelf(p,_=p){return this.sx*=p,this.sy*=_,this}}class yh{constructor(p,_,C,M,F=!1){this.primaryId=vd.from(p),this.primaryOptions=_,C&&(this.secondaryId=vd.from(C)),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 Ih(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new Ih(this.secondaryId,this.secondaryOptions):null}static from(p){return typeof p!="string"?p:yh.build({name:p})}static build(p,_,C,M){return!p||typeof p=="object"&&!("name"in p)?null:new yh(p,C,_,M)}}function Ui(N,p,_,C){return typeof N=="number"&&N>=0&&N<=255&&typeof p=="number"&&p>=0&&p<=255&&typeof _=="number"&&_>=0&&_<=255?C===void 0||typeof C=="number"&&C>=0&&C<=1?null:`Invalid rgba value [${[N,p,_,C].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof C=="number"?[N,p,_,C]:[N,p,_]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function um(N){if(N===null||typeof N=="string"||typeof N=="boolean"||typeof N=="number"||N instanceof Ci||N instanceof Ww||N instanceof xu||N instanceof yh)return!0;if(Array.isArray(N)){for(const p of N)if(!um(p))return!1;return!0}if(typeof N=="object"){for(const p in N)if(!um(N[p]))return!1;return!0}return!1}function oh(N){if(N===null)return pu;if(typeof N=="string")return Ao;if(typeof N=="boolean")return fl;if(typeof N=="number")return da;if(N instanceof Ci)return Qc;if(N instanceof Ww)return B0;if(N instanceof xu)return xh;if(N instanceof yh)return df;if(Array.isArray(N)){const p=N.length;let _;for(const C of N){const M=oh(C);if(_){if(_===M)continue;_=Wo;break}_=M}return Bd(_||Wo,p)}return ng}function sp(N){return N===null?"":typeof N=="string"||typeof N=="number"||typeof N=="boolean"?String(N):N instanceof xu||N instanceof yh||N instanceof Ci?N.toString():JSON.stringify(N)}class Kg{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(!um(p[1]))return _.error("invalid value");const C=p[1];let M=oh(C);const F=_.expectedType;return M.kind!=="array"||M.N!==0||!F||F.kind!=="array"||typeof F.N=="number"&&F.N!==0||(M=F),new Kg(M,C)}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 xu?this.value.serialize():this.value}}class lh{constructor(p){this.name="ExpressionEvaluationError",this.message=p}toJSON(){return this.message}}const Ic={string:Ao,number:da,boolean:fl,object:ng};class Yg{constructor(p,_){this.type=p,this.args=_}static parse(p,_){if(p.length<2)return _.error("Expected at least one argument.");let C,M=1;const F=p[0];if(F==="array"){let H,Y;if(p.length>2){const se=p[1];if(typeof se!="string"||!(se in Ic)||se==="object")return _.error('The item type argument of "array" must be one of string, number, boolean',1);H=Ic[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);Y=p[2],M++}C=Bd(H,Y)}else C=Ic[F];const z=[];for(;Mp.outputDefined())}serialize(){const p=this.type,_=[p.kind];if(p.kind==="array"){const C=p.itemType;if(C.kind==="string"||C.kind==="number"||C.kind==="boolean"){_.push(C.kind);const M=p.N;(typeof M=="number"||this.args.length>1)&&_.push(M)}}return _.concat(this.args.map(C=>C.serialize()))}}class P1{constructor(p){this.type=xh,this.sections=p}static parse(p,_){if(p.length<2)return _.error("Expected at least one argument.");const C=p[1];if(!Array.isArray(C)&&typeof C=="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 Y=null;if(H["font-scale"]&&(Y=_.parseObjectValue(H["font-scale"],z,"font-scale",da),!Y))return null;let se=null;if(H["text-font"]&&(se=_.parseObjectValue(H["text-font"],z,"text-font",Bd(Ao)),!se))return null;let me=null;if(H["text-color"]&&(me=_.parseObjectValue(H["text-color"],z,"text-color",Qc),!me))return null;const xe=M.at(-1);xe.scale=Y,xe.font=se,xe.textColor=me}else{const Y=_.parse(p[z],z,Wo);if(!Y)return null;const se=Y.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:Y,scale:null,font:null,textColor:null})}}return new P1(M)}evaluate(p){return new xu(this.sections.map(_=>{const C=_.content.evaluate(p);return Mb(oh(C),df)?new zm("",C,null,null,null):new zm(sp(C),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 C={};_.scale&&(C["font-scale"]=_.scale.serialize()),_.font&&(C["text-font"]=_.font.serialize()),_.textColor&&(C["text-color"]=_.textColor.serialize()),p.push(C)}return p}}class I1{constructor(p,_,C,M){this._imageWarnHistory={},this.type=df,this.namePrimary=p,this.nameSecondary=_,C&&(this.paramsPrimary=C.params,this.iconsetIdPrimary=C.iconset?C.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 C=1;const M=[];function F(){if(Cvd.isEqual(z,F)),M.available){const z=M.getSecondary()?M.getSecondary().id:null;z&&(M.available=p.availableImages.some(H=>vd.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 C={};if(_&&(C.iconset={id:_}),p){C.params={};for(const M in p)p[M]&&(C.params[M]=p[M].serialize())}return Object.keys(C).length>0?C: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 L1(N){return Yw(N)?"string":D_(N)?"number":Mk(N)?"boolean":Array.isArray(N)?"array":N===null?"null":Kw(N)?"object":typeof N}function Kw(N){return N!=null&&!Array.isArray(N)&&typeof N!="function"&&!(N instanceof String||N instanceof Number||N instanceof Boolean)&&typeof N=="object"}function Yw(N){return typeof N=="string"||N instanceof String}function D_(N){return typeof N=="number"||N instanceof Number}function Mk(N){return typeof N=="boolean"||N instanceof Boolean}const Pb={"to-boolean":fl,"to-color":Qc,"to-number":da,"to-string":Ao};class Ov{constructor(p,_){this.type=p,this.args=_}static parse(p,_){if(p.length<2)return _.error("Expected at least one argument.");const C=p[0],M=[];let F=pu;if(C==="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=Bd(_.expectedType.itemType,z)}else{if(!(z>0&&um(p[1][0])))return null;F=Bd(oh(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]),!C))return new Ci(_[0]/255,_[1]/255,_[2]/255,_[3])}throw new lh(C||`Could not parse color from value '${typeof _=="string"?_:String(JSON.stringify(_))}'`)}if(this.type.kind==="number"){let _=null;for(const C of this.args){if(_=C.evaluate(p),_===null)return 0;const M=Number(_);if(!isNaN(M))return M}throw new lh(`Could not convert ${JSON.stringify(_)} to number.`)}return this.type.kind==="formatted"?xu.fromString(sp(this.args[0].evaluate(p))):this.type.kind==="resolvedImage"?yh.build(sp(this.args[0].evaluate(p))):this.type.kind==="array"?this.args.map(_=>_.evaluate(p)):sp(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 P1([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new I1(this.args[0]).serialize();const p=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(_=>{p.push(_.serialize())}),p}}const N3=["Unknown","Point","LineString","Polygon"];class U2{constructor(p,_,C){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=C}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?N3[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:C,y:M}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(C*_-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 np{constructor(p,_,C,M,F){this.name=p,this.type=_,this._evaluate=C,this.args=M,this._overloadIndex=F}evaluate(p){if(!this._evaluate){const _=np.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 C=p[0],M=np.definitions[C];if(!M)return _.error(`Unknown expression "${C}". 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 Y=null,se=-1;for(const[me,xe]of z){if(Array.isArray(me)&&me.length!==p.length-1)continue;H.push(me),se++,Y===null?Y=_._forkForSignature():Y.errors.length=0;const _e=[];let Te=!1;for(let De=1;De_e)).map(Pk).join(" | "),xe=[];for(let _e=1;_e_[2]){const M=.5*C;let F=N[0]-_[0]>M?-C:_[0]-N[0]>M?C:0;F===0&&(F=N[0]-_[2]>M?-C:_[2]-N[0]>M?C:0),N[0]+=F}ii(p,N)}function S3(N,p,_,C){const M=Math.pow(2,C.z)*zv,F=[C.x*zv,C.y*zv],z=[];if(!N)return z;for(const H of N)for(const Y of H){const se=[Y.x+F[0],Y.y+F[1]];IC(se,p,_,M),z.push(se)}return z}function Lb(N,p,_,C){const M=Math.pow(2,C.z)*zv,F=[C.x*zv,C.y*zv],z=[];if(!N)return z;for(const Y of N){const se=[];for(const me of Y){const xe=[me.x+F[0],me.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 Y of z)for(const se of Y)IC(se,p,_,M)}var H;return z}class ap{constructor(p,_){this.type=fl,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(um(p[1])){const C=p[1];if(C.type==="FeatureCollection")for(let M=0;MCM?1:0){if(this.data=p,this.length=this.data.length,this.compare=_,this.length>0)for(let C=(this.length>>1)-1;C>=0;C--)this._down(C)}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:C}=this,M=_[p];for(;p>0;){const F=p-1>>1,z=_[F];if(C(M,z)>=0)break;_[p]=z,p=F}_[p]=M}_down(p){const{data:_,compare:C}=this,M=this.length>>1,F=_[p];for(;p=0)break;_[p]=_[z],p=z}_[p]=F}}var Pr=8192;function Ik(N,p,_){return[N,p,_].filter(Boolean).join("")}function LC(N,p){switch(N){case"string":return sp(p);case"number":return+p;case"boolean":return!!p;case"color":return Ci.parse(p);case"formatted":return xu.fromString(sp(p));case"resolvedImage":return yh.build(sp(p))}return p}function Xg(N,p,_,C){return C!==void 0&&(N=C*Math.round(N/C)),p!==void 0&&N_&&(N=_),N}class uf{constructor(p,_,C,M=!1){this.type=p,this.key=_,this.scope=C,this.featureConstant=M}static parse(p,_){let C=_.expectedType;if(C??(C=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 Kg))return _.error("Key name of 'config' expression must be a string literal.");let F,z=!0;const H=sp(M.value);if(p.length>=3){const Y=_.parse(p[2],2);if(!(Y instanceof Kg))return _.error("Scope of 'config' expression must be a string literal.");F=sp(Y.value)}if(_.options){const Y=Ik(H,F,_._scope),se=_.options.get(Y);se&&(z=D1(se.value||se.default))}return new uf(C,H,F,z)}evaluate(p){const _=Ik(this.key,this.scope,p.scope),C=p.getConfig(_);if(!C)return null;const{type:M,value:F,values:z,minValue:H,maxValue:Y,stepValue:se}=C,me=C.default.evaluate(p);let xe=me;if(F){const _e=p.scope;p.scope=(_e||"").split("").slice(1).join(""),xe=F.evaluate(p),p.scope=_e}return M&&(xe=LC(M,xe)),xe===void 0||H===void 0&&Y===void 0&&se===void 0||(typeof xe=="number"?xe=Xg(xe,H,Y,se):Array.isArray(xe)&&(xe=xe.map(_e=>typeof _e=="number"?Xg(_e,H,Y,se):_e))),F!==void 0&&xe!==void 0&&z&&!z.includes(xe)&&(xe=me,M&&(xe=LC(M,xe))),(M&&M!==this.type||xe!==void 0&&!Mb(oh(xe),this.type))&&(xe=LC(this.type.kind,xe)),xe}eachChild(){}outputDefined(){return!1}serialize(){const p=["config",this.key];return this.scope&&p.concat(this.scope),p}}function D1(N){if(N instanceof np&&(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 ap||N instanceof Fi)return!1;if(N instanceof uf)return N.featureConstant;let p=!0;return N.eachChild(_=>{p&&!D1(_)&&(p=!1)}),p}function U0(N){if(N instanceof np&&N.name==="feature-state")return!1;let p=!0;return N.eachChild(_=>{p&&!U0(_)&&(p=!1)}),p}function q0(N,p){if(N instanceof np&&p.has(N.name))return!1;let _=!0;return N.eachChild(C=>{_&&!q0(C,p)&&(_=!1)}),_}function Dx(N,p){return q0(N,new Set(p))}const Lk=1/298.257223563,q2=Lk*(2-Lk),Rk=Math.PI/180;function Dk(N){const p=6378.137*Rk*1e3,_=Math.cos(N*Rk),C=1/(1-q2*(1-_*_)),M=Math.sqrt(C);return[p*M*_,p*M*C*(1-q2)]}function F_(N){for(;N<-180;)N+=360;for(;N>180;)N-=360;return N}function Xw(N,p,_,C){const M=F_(N[0]-p[0])*_,F=(N[1]-p[1])*C;return Math.sqrt(M*M+F*F)}function O_(N,p,_,C,M){let F=p[0],z=p[1],H=F_(_[0]-F)*C,Y=(_[1]-z)*M;if(H!==0||Y!==0){const se=(F_(N[0]-F)*C*H+(N[1]-z)*M*Y)/(H*H+Y*Y);se>1?(F=_[0],z=_[1]):se>0&&(F+=H/C*se,z+=Y/M*se)}return H=F_(N[0]-F)*C,Y=(N[1]-z)*M,Math.sqrt(H*H+Y*Y)}function RC(N,p){return p.dist-N.dist}function V2(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 _=z_(N);if(p){if(_===2)return[N,null];const C=Math.floor(_/2);return[[N[0],N[0]+C],[N[0]+C,N[1]]]}{if(_===1)return[N,null];const C=Math.floor(_/2)-1;return[[N[0],N[0]+C],[N[0]+C+1,N[1]]]}}function F1(N,p){const _=[1/0,1/0,-1/0,-1/0];if(!Qg(p,N.length))return _;for(let C=p[0];C<=p[1];++C)ii(_,N[C]);return _}function Qw(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[_e+1][0],De=F[_e+1][1]):nt>0&&(Te+=Ue/H*nt,De+=Ye/Y*nt)),Ue=F_(z[0]-Te)*H,Ye=(z[1]-De)*Y;const it=Ue*Ue+Ye*Ye;it=M)return M;if($i(F,z)){if(Kn(N,p))return 0}else if(Kn(p,N))return 0;let H=M;for(const Y of N)for(let se=0,me=Y.length,xe=me-1;se=z)continue;const xe=me.range1;if(z_(xe)<=Y){if(!Qg(xe,N.length))return NaN;if(p){const _e=an(N,xe,_,C,M);if((z=Math.min(z,_e))===0)return z}else for(let _e=xe[0];_e<=xe[1];++_e){const Te=qs(N[_e],_,C,M);if((z=Math.min(z,Te))===0)return z}}else{const _e=DC(xe,p);if(_e[0]!==null){const Te=Pe(F1(N,_e[0]),se,C,M);Te=H)continue;const _e=xe.range1,Te=xe.range2;if(z_(_e)<=se&&z_(Te)<=me){if(!Qg(_e,N.length)||!Qg(Te,_.length))return NaN;if(p&&C?H=Math.min(H,As(N,_e,_,Te,M,F)):p||C?p&&!C?H=Math.min(H,cs(_,Te,N,_e,M,F)):!p&&C&&(H=Math.min(H,cs(N,_e,_,Te,M,F))):H=Math.min(H,Is(N,_e,_,Te,M,F)),H===0)return H}else{const De=DC(_e,p),Ue=DC(Te,C);Qs(Y,H,M,F,N,_,De[0],Ue[0]),Qs(Y,H,M,F,N,_,De[0],Ue[1]),Qs(Y,H,M,F,N,_,De[1],Ue[0]),Qs(Y,H,M,F,N,_,De[1],Ue[1])}}return H}function ra(N,p,_,C,M,F=1/0){let z=F;const H=F1(N,[0,N.length-1]);for(const Y of _)if(!(z!==1/0&&Pe(H,F1(Y,[0,Y.length-1]),C,M)>=z)&&(z=Math.min(z,yr(N,p,Y,!0,C,M,z)),z===0))return z;return z}function dr(N,p,_,C,M,F=1/0){let z=F;const H=F1(N,[0,N.length-1]);for(const Y of _){if(z!==1/0&&Pe(H,Qw(Y),C,M)>=z)continue;const se=ir(N,p,Y,C,M,z);if(isNaN(se))return se;if((z=Math.min(z,se))===0)return z}return z}function ua(N,p,_){const C=[];for(const z of N)for(const H of z)C.push(He(H,p));const[M,F]=Dk(C[0][1]);return _.type==="Point"||_.type==="MultiPoint"||_.type==="LineString"?yr(C,!1,_.type==="Point"?[_.coordinates]:_.coordinates,_.type==="LineString",M,F):_.type==="MultiLineString"?ra(C,!1,_.coordinates,M,F):_.type==="Polygon"||_.type==="MultiPolygon"?dr(C,!1,_.type==="Polygon"?[_.coordinates]:_.coordinates,M,F):null}function lr(N,p,_){const C=[];for(const z of N){const H=[];for(const Y of z)H.push(He(Y,p));C.push(H)}const[M,F]=Dk(C[0][0][1]);if(_.type==="Point"||_.type==="MultiPoint"||_.type==="LineString")return ra(_.type==="Point"?[_.coordinates]:_.coordinates,_.type==="LineString",C,M,F);if(_.type==="MultiLineString"){let z=1/0;for(let H=0;H<_.coordinates.length;H++){const Y=ra(_.coordinates[H],!0,C,M,F,z);if(isNaN(Y))return Y;if((z=Math.min(z,Y))===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(C,p))}checkSubtype(p,_,C){const M=Fv(p,_);return M&&this.error(M,...typeof C=="number"?[C]:[]),M}}const Lc=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 hf(N,p,_){return _==="assert"?new Yg(p,[N]):_==="coerce"?new Ov(p,[N]):N}function Xl(N){if(N instanceof bl)return Xl(N.boundExpression);if(N instanceof np&&N.name==="error"||N instanceof R1||N instanceof ap||N instanceof Fi||N instanceof uf)return!1;const p=N instanceof Ov||N instanceof Yg;let _=!0;return N.eachChild(C=>{_=p?_&&Xl(C):_&&C instanceof Kg}),!!_&&D1(N)&&q0(N,Lc)}function yo(N,p){const _=N.length-1;let C,M,F=0,z=_,H=0;for(;F<=z;)if(H=Math.floor((F+z)/2),C=N[H],M=N[H+1],C<=p){if(H===_||pp))throw new lh("Input is not a number.");z=H-1}return 0}class vi{constructor(p,_,C){this.type=p,this.input=_,this.labels=[],this.outputs=[];for(const[M,F]of C)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 C=_.parse(p[1],1,da);if(!C)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(Y,me,F);if(!xe)return null;F=F||xe.type,M.push([H,xe])}return new vi(F,C,M)}evaluate(p){const _=this.labels,C=this.outputs;if(_.length===1)return C[0].evaluate(p);const M=this.input.evaluate(p);if(M<=_[0])return C[0].evaluate(p);const F=_.length;return M>=_[F-1]?C[F-1].evaluate(p):C[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 hm=.95047,To=1.08883,Ql=4/29,$c=6/29,If=3*$c*$c,rg=$c*$c*$c,Yd=Math.PI/180,ag=180/Math.PI;function Lh(N){return N>rg?Math.pow(N,1/3):N/If+Ql}function mf(N){return N>$c?N*N*N:If*(N-Ql)}function ud(N){return 255*(N<=.0031308?12.92*N:1.055*Math.pow(N,1/2.4)-.055)}function lu(N){return(N/=255)<=.04045?N/12.92:Math.pow((N+.055)/1.055,2.4)}function ch(N){const p=lu(N.r),_=lu(N.g),C=lu(N.b),M=Lh((.4124564*p+.3575761*_+.1804375*C)/hm),F=Lh((.2126729*p+.7151522*_+.072175*C)/1);return{l:116*F-16,a:500*(M-F),b:200*(F-Lh((.0193339*p+.119192*_+.9503041*C)/To)),alpha:N.a}}function cu(N){let p=(N.l+16)/116,_=isNaN(N.a)?p:p+N.a/500,C=isNaN(N.b)?p:p-N.b/200;return p=1*mf(p),_=hm*mf(_),C=To*mf(C),new Ci(ud(3.2404542*_-1.5371385*p-.4985314*C),ud(-.969266*_+1.8760108*p+.041556*C),ud(.0556434*_-.2040259*p+1.0572252*C),N.alpha)}function Lf(N,p,_){const C=p-N;return N+_*(C>180||C<-180?C-360*Math.round(C/360):C)}const ip={forward:ch,reverse:cu,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,_)}}},dh={forward:function(N){const{l:p,a:_,b:C}=ch(N),M=Math.atan2(C,_)*ag;return{h:M<0?M+360:M,c:Math.sqrt(_*_+C*C),l:p,alpha:N.a}},reverse:function(N){const p=N.h*Yd,_=N.c;return cu({l:N.l,a:Math.cos(p)*_,b:Math.sin(p)*_,alpha:N.alpha})},interpolate:function(N,p,_){return{h:Lf(N.h,p.h,_),c:ya(N.c,p.c,_),l:ya(N.l,p.l,_),alpha:ya(N.alpha,p.alpha,_)}}};var vh=Object.freeze({__proto__:null,hcl:dh,lab:ip});class xc{constructor(p,_,C,M,F){this.type=p,this.operator=_,this.interpolation=C,this.input=M,this.labels=[],this.outputs=[];for(const[z,H]of F)this.labels.push(z),this.outputs.push(H)}static interpolationFactor(p,_,C,M){let F=0;if(p.name==="exponential")F=Rh(_,p.base,C,M);else if(p.name==="linear")F=Rh(_,1,C,M);else if(p.name==="cubic-bezier"){const z=p.controlPoints;F=bn(z[0],z[1],z[2],z[3])(Rh(_,1,C,M))}return F}static parse(p,_){let[C,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(me=>typeof me!="number"||me<0||me>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,da),!F)return null;const H=[];let Y=null;C==="interpolate-hcl"||C==="interpolate-lab"?Y=Qc:_.expectedType&&_.expectedType.kind!=="value"&&(Y=_.expectedType);for(let se=0;se=me)return _.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',_e);const De=_.parse(xe,Te,Y);if(!De)return null;Y=Y||De.type,H.push([me,De])}return Y.kind==="number"||Y.kind==="color"||Y.kind==="array"&&Y.itemType.kind==="number"&&typeof Y.N=="number"?new xc(Y,C,M,F,H):_.error(`Type ${gu(Y)} is not interpolatable.`)}evaluate(p){const _=this.labels,C=this.outputs;if(_.length===1)return C[0].evaluate(p);const M=this.input.evaluate(p);if(M<=_[0])return C[0].evaluate(p);const F=_.length;if(M>=_[F-1])return C[F-1].evaluate(p);const z=yo(_,M),H=xc.interpolationFactor(this.interpolation,M,_[z],_[z+1]),Y=C[z].evaluate(p),se=C[z+1].evaluate(p);return this.operator==="interpolate"?kc[this.type.kind.toLowerCase()](Y,se,H):this.operator==="interpolate-hcl"?dh.reverse(dh.interpolate(dh.forward(Y),dh.forward(se),H)):ip.reverse(ip.interpolate(ip.forward(Y),ip.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 C=0;CFv(M,H.type));return new Bm(z?Wo:C,F)}evaluate(p){let _,C=null,M=0;for(const F of this.args){if(M++,C=F.evaluate(p),C&&C instanceof yh&&!C.available&&(_||(_=C),C=null,M===this.args.length))return _;if(C!==null)break}return C}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 Rf=/[^a-zA-Z0-9_]/;class Tp{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 C=[];for(let F=1;F=C.length)throw new lh("Array index out of bounds: index exceeds array size");if(_!==Math.floor(_))throw new lh("Array index must be an integer. Use at-interpolated for fractional indices");return C[_]}eachChild(p){p(this.index),p(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class Mp{constructor(p,_,C){this.type=p,this.index=_,this.input=C}static parse(p,_){if(p.length!==3)return _.error(`Expected 2 arguments, but found ${p.length-1} instead.`);const C=_.parse(p[1],1,da),M=_.parse(p[2],2,Bd(_.expectedType||Wo));return C&&M?new Mp(M.type.itemType,C,M):null}evaluate(p){const _=this.index.evaluate(p),C=this.input.evaluate(p);if(_<0)throw new lh(`Array index out of bounds: ${_} < 0.`);if(_>C.length-1)throw new lh(`Array index out of bounds: ${_} > ${C.length-1}.`);if(_===Math.floor(_))return C[_];const M=Math.floor(_),F=Math.ceil(_),z=C[M],H=C[F];if(typeof z!="number"||typeof H!="number")throw new lh(`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 ex{constructor(p,_,C,M,F,z){this.inputType=p,this.type=_,this.input=C,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 C,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(C){if(_.checkSubtype(C,oh(Te),se))return null}else C=oh(Te);if(F[String(Te)]!==void 0)return _.error("Branch labels must be unique.",se);F[String(Te)]=z.length}const _e=_.parse(xe,se,M);if(!_e)return null;M=M||_e.type,z.push(_e)}const H=_.parse(p[1],1,Wo);if(!H)return null;const Y=_.parse(p.at(-1),p.length-1,M);return Y?H.type.kind!=="value"&&_.checkSubtype(C,H.type,1)?null:new ex(C,M,H,F,z,Y):null}evaluate(p){const _=this.input.evaluate(p);return(Mb(oh(_),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(),C=[],M={};for(const z of _){const H=M[this.cases[z]];H===void 0?(M[this.cases[z]]=C.length,C.push([this.cases[z],[z]])):C[H][1].push(z)}const F=z=>this.inputType.kind==="number"?Number(z):z;for(const[z,H]of C)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 Zd{constructor(p,_,C){this.type=p,this.branches=_,this.otherwise=C}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 C;_.expectedType&&_.expectedType.kind!=="value"&&(C=_.expectedType);const M=[];for(let z=1;z_.outputDefined())&&this.otherwise.outputDefined()}serialize(){const p=["case"];return this.eachChild(_=>{p.push(_.serialize())}),p}}class ff{constructor(p,_,C,M){this.type=p,this.input=_,this.beginIndex=C,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 C=_.parse(p[1],1,Wo),M=_.parse(p[2],2,da);if(!C||!M)return null;if(F=C.type,![Bd(Wo),Ao,Wo].some(z=>z.kind===F.kind))return _.error(`Expected first argument to be of type array or string, but found ${gu(C.type)} instead`),null;var F;if(p.length===4){const z=_.parse(p[3],3,da);return z?new ff(C.type,C,M,z):null}return new ff(C.type,C,M)}evaluate(p){const _=this.input.evaluate(p),C=this.beginIndex.evaluate(p);if(!Lx(_,["string","array"]))throw new lh(`Expected first argument to be of type array or string, but found ${gu(oh(_))} instead.`);if(this.endIndex){const M=this.endIndex.evaluate(p);return _.slice(C,M)}return _.slice(C)}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 Td(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 Jl(N,p,_,C){return C.compare(p,_)===0}function Ud(N,p,_){const C=N!=="=="&&N!=="!=";return class P7t{constructor(F,z,H){this.type=fl,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 Y=z.parse(F[1],1,Wo);if(!Y)return null;if(!Td(H,Y.type))return z.error(`"${H}" comparisons are not supported for type '${gu(Y.type)}'.`,1);let se=z.parse(F[2],2,Wo);if(!se)return null;if(!Td(H,se.type))return z.error(`"${H}" comparisons are not supported for type '${gu(se.type)}'.`,2);if(Y.type.kind!==se.type.kind&&Y.type.kind!=="value"&&se.type.kind!=="value")return z.error(`Cannot compare types '${gu(Y.type)}' and '${gu(se.type)}'.`);C&&(Y.type.kind==="value"&&se.type.kind!=="value"?Y=new Yg(se.type,[Y]):Y.type.kind!=="value"&&se.type.kind==="value"&&(se=new Yg(Y.type,[se])));let me=null;if(F.length===4){if(Y.type.kind!=="string"&&se.type.kind!=="string"&&Y.type.kind!=="value"&&se.type.kind!=="value")return z.error("Cannot use collator to compare non-string types.");if(me=z.parse(F[3],3,B0),!me)return null}return new P7t(Y,se,me)}evaluate(F){const z=this.lhs.evaluate(F),H=this.rhs.evaluate(F);if(C&&this.hasUntypedArgument){const Y=oh(z),se=oh(H);if(Y.kind!==se.kind||Y.kind!=="string"&&Y.kind!=="number")throw new lh(`Expected arguments for "${N}" to be (string, string) or (number, number), but found (${Y.kind}, ${se.kind}) instead.`)}if(this.collator&&!C&&this.hasUntypedArgument){const Y=oh(z),se=oh(H);if(Y.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 bd=Ud("==",function(N,p,_){return p===_},Jl),Df=Ud("!=",function(N,p,_){return p!==_},function(N,p,_,C){return!Jl(0,p,_,C)}),Fx=Ud("<",function(N,p,_){return p<_},function(N,p,_,C){return C.compare(p,_)<0}),O1=Ud(">",function(N,p,_){return p>_},function(N,p,_,C){return C.compare(p,_)>0}),bm=Ud("<=",function(N,p,_){return p<=_},function(N,p,_,C){return C.compare(p,_)<=0}),Fk=Ud(">=",function(N,p,_){return p>=_},function(N,p,_,C){return C.compare(p,_)>=0});class z1{constructor(p,_,C,M,F,z){this.type=Ao,this.number=p,this.locale=_,this.currency=C,this.unit=M,this.minFractionDigits=F,this.maxFractionDigits=z}static parse(p,_){if(p.length!==3)return _.error("Expected two arguments.");const C=_.parse(p[1],1,da);if(!C)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 Y=null;if(M["min-fraction-digits"]!==void 0&&(Y=_.parseObjectValue(M["min-fraction-digits"],2,"min-fraction-digits",da),!Y))return null;let se=null;return M["max-fraction-digits"]===void 0||(se=_.parseObjectValue(M["max-fraction-digits"],2,"max-fraction-digits",da),se)?new z1(C,F,z,H,Y,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 B1{constructor(p){this.type=da,this.input=p}static parse(p,_){if(p.length!==2)return _.error(`Expected 1 argument, but found ${p.length-1} instead.`),null;const C=_.parse(p[1],1);return C?C.type.kind!=="array"&&C.type.kind!=="string"&&C.type.kind!=="value"?(_.error(`Expected argument of type string or array, but found ${gu(C.type)} instead.`),null):new B1(C):null}evaluate(p){const _=this.input.evaluate(p);if(typeof _=="string"||Array.isArray(_))return _.length;throw new lh(`Expected value to be of type string or array, but found ${gu(oh(_))} instead.`)}eachChild(p){p(this.input)}outputDefined(){return!1}serialize(){const p=["length"];return this.eachChild(_=>{p.push(_.serialize())}),p}}function ig(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 Rb={"==":bd,"!=":Df,">":O1,"<":Fx,">=":Fk,"<=":bm,array:Yg,at:Jg,"at-interpolated":Mp,boolean:Yg,case:Zd,coalesce:Bm,collator:R1,format:P1,image:I1,interpolate:xc,"interpolate-hcl":xc,"interpolate-lab":xc,length:B1,let:Tp,literal:Kg,match:ex,number:Yg,"number-format":z1,object:Yg,slice:ff,step:vi,string:Yg,"to-boolean":Ov,"to-color":Ov,"to-number":Ov,"to-string":Ov,var:bl,within:ap,distance:Fi,config:uf};function tx(N,[p,_,C,M]){p=p.evaluate(N),_=_.evaluate(N),C=C.evaluate(N);const F=M?M.evaluate(N):1,z=Ui(p,_,C,F);if(z)throw new lh(z);return new Ci(p/255,_/255,C/255,F)}function H2(N,[p,_,C,M]){p=p.evaluate(N),_=_.evaluate(N),C=C.evaluate(N);const F=M?M.evaluate(N):1,z=function(se,me,xe,_e){return typeof se=="number"&&se>=0&&se<=360?typeof me=="number"&&me>=0&&me<=100&&typeof xe=="number"&&xe>=0&&xe<=100?_e===void 0||typeof _e=="number"&&_e>=0&&_e<=1?null:`Invalid hsla value [${[se,me,xe,_e].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof _e=="number"?[se,me,xe,_e]:[se,me,xe]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof _e=="number"?[se,me,xe,_e]:[se,me,xe]).join(", ")}]: 'h' must be between 0 and 360.`}(p,_,C,F);if(z)throw new lh(z);const H=`hsla(${p}, ${_}%, ${C}%, ${F})`,Y=Ci.parse(H);if(!Y)throw new lh(`Failed to parse HSLA color: ${H}`);return Y}function Ok(N,p){return N in p}function py(N,p){const _=p[N];return _===void 0?null:_}function gy(N){return{type:N}}function Jw(N,p){if(!Lx(N,["boolean","string","number","null"]))throw new lh(`Expected first argument to be of type boolean, string, number or null, but found ${gu(oh(N))} instead.`);if(!Lx(p,["string","array"]))throw new lh(`Expected second argument to be of type array or string, but found ${gu(oh(p))} instead.`)}function Db(N){if(N instanceof uf)return new Set([N.key]);let p=new Set;return N.eachChild(_=>{p=new Set([...p,...Db(_)])}),p}function Ox(N){if(N instanceof np&&N.name==="is-active-floor")return!0;let p=!1;return N.eachChild(_=>{!p&&Ox(_)&&(p=!0)}),p}function $1(N){return{result:"success",value:N}}function op(N){return{result:"error",value:N}}function B_(N,p){return!!N&&!!N.parameters&&N.parameters.includes(p)}function Yy(N){return N["property-type"]==="data-driven"}function zk(N){return B_(N.expression,"measure-light")}function ej(N){return B_(N.expression,"zoom")}function Zy(N){return!!N.expression&&N.expression.interpolated}function lp(N){return typeof N=="object"&&N!==null&&!Array.isArray(N)}function U1(N){return N}function zx(N,p){const _=p.type==="color",C=N.stops&&typeof N.stops[0][0]=="object",M=C||!(C||N.property!==void 0),F=N.type||(Zy(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"&&!vh[N.colorSpace])throw new Error(`Unknown color space: ${N.colorSpace}`);let z,H,Y;if(F==="exponential")z=Bk;else if(F==="interval")z=C3;else if(F==="categorical"){z=q1,H=Object.create(null);for(const se of N.stops)H[se[0]]=se[1];Y=typeof N.stops[0][0]}else{if(F!=="identity")throw new Error(`Unknown function type "${F}"`);z=VT}if(C){const se={},me=[];for(let Te=0;TeTe[0]),evaluate:({zoom:Te},De)=>Bk({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:xc.interpolationFactor.bind(void 0,se),zoomStops:N.stops.map(me=>me[0]),evaluate:({zoom:me})=>z(N,p,me,H,Y)}}return{kind:"source",evaluate(se,me){const xe=me&&me.properties?me.properties[N.property]:void 0;return xe===void 0?cp(N.default,p.default):z(N,p,xe,H,Y)}}}function cp(N,p,_){return N!==void 0?N:p!==void 0?p:_!==void 0?_:void 0}function q1(N,p,_,C,M){return cp(typeof _===M?C[_]:void 0,N.default,p.default)}function C3(N,p,_){if(!D_(_))return cp(N.default,p.default);const C=N.stops.length;if(C===1||_<=N.stops[0][0])return N.stops[0][1];if(_>=N.stops[C-1][0])return N.stops[C-1][1];const M=yo(N.stops.map(F=>F[0]),_);return N.stops[M][1]}function Bk(N,p,_){const C=N.base!==void 0?N.base:1;if(!D_(_))return cp(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(me=>me[0]),_),z=function(me,xe,_e,Te){const De=Te-_e,Ue=me-_e;return De===0?0:xe===1?Ue/De:(Math.pow(xe,Ue)-1)/(Math.pow(xe,De)-1)}(_,C,N.stops[F][0],N.stops[F+1][0]),H=N.stops[F][1],Y=N.stops[F+1][1];let se=kc[p.type]||U1;if(N.colorSpace&&N.colorSpace!=="rgb"){const me=vh[N.colorSpace];se=(xe,_e)=>me.reverse(me.interpolate(me.forward(xe),me.forward(_e),z))}return typeof H.evaluate=="function"?{evaluate(...me){const xe=H.evaluate.apply(void 0,me),_e=Y.evaluate.apply(void 0,me);if(xe!==void 0&&_e!==void 0)return se(xe,_e,z)}}:se(H,Y,z)}function VT(N,p,_){return p.type==="color"?_=Ci.parse(_):p.type==="formatted"?_=xu.fromString(_.toString()):p.type==="resolvedImage"?_=yh.build(_.toString()):L1(_)===p.type||p.type==="enum"&&p.values[_]||(_=void 0),cp(_,N.default,p.default)}np.register(Rb,{error:[{kind:"error"},[Ao],(N,[p])=>{throw new lh(p.evaluate(N))}],typeof:[Ao,[Wo],(N,[p])=>gu(oh(p.evaluate(N)))],"to-rgba":[Bd(da,4),[Qc],(N,[p])=>p.evaluate(N).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Bd(da,4),[Qc],(N,[p])=>p.evaluate(N).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[Qc,[da,da,da],tx],rgba:[Qc,[da,da,da,da],tx],hsl:[Qc,[da,da,da],H2],hsla:[Qc,[da,da,da,da],H2],has:{type:fl,overloads:[[[Ao],(N,[p])=>Ok(p.evaluate(N),N.properties())],[[Ao,ng],(N,[p,_])=>Ok(p.evaluate(N),_.evaluate(N))]]},get:{type:Wo,overloads:[[[Ao],(N,[p])=>py(p.evaluate(N),N.properties())],[[Ao,ng],(N,[p,_])=>py(p.evaluate(N),_.evaluate(N))]]},"feature-state":[Wo,[Ao],(N,[p])=>py(p.evaluate(N),N.featureState||{})],properties:[ng,[],N=>N.properties()],"geometry-type":[Ao,[],N=>N.geometryType()],worldview:[Ao,[],N=>N.globals.worldview||""],"is-active-floor":[fl,gy(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(C=>{const M=C.evaluate(N);return _.has(M)})}],id:[Wo,[],N=>N.id()],zoom:[da,[],N=>N.globals.zoom],pitch:[da,[],N=>N.globals.pitch||0],"distance-from-center":[da,[],N=>N.distanceFromCenter()],"measure-light":[da,[Ao],(N,[p])=>N.measureLight(p.evaluate(N))],"heatmap-density":[da,[],N=>N.globals.heatmapDensity||0],"line-progress":[da,[],N=>N.globals.lineProgress||0],"raster-value":[da,[],N=>N.globals.rasterValue||0],"raster-particle-speed":[da,[],N=>N.globals.rasterParticleSpeed||0],"sky-radial-progress":[da,[],N=>N.globals.skyRadialProgress||0],accumulated:[Wo,[],N=>N.globals.accumulated===void 0?null:N.globals.accumulated],"+":[da,gy(da),(N,p)=>{let _=0;for(const C of p)_+=C.evaluate(N);return _}],"*":[da,gy(da),(N,p)=>{let _=1;for(const C of p)_*=C.evaluate(N);return _}],"-":{type:da,overloads:[[[da,da],(N,[p,_])=>p.evaluate(N)-_.evaluate(N)],[[da],(N,[p])=>-p.evaluate(N)]]},"/":[da,[da,da],(N,[p,_])=>p.evaluate(N)/_.evaluate(N)],"%":[da,[da,da],(N,[p,_])=>p.evaluate(N)%_.evaluate(N)],ln2:[da,[],()=>Math.LN2],pi:[da,[],()=>Math.PI],e:[da,[],()=>Math.E],"^":[da,[da,da],(N,[p,_])=>Math.pow(p.evaluate(N),_.evaluate(N))],sqrt:[da,[da],(N,[p])=>Math.sqrt(p.evaluate(N))],log10:[da,[da],(N,[p])=>Math.log(p.evaluate(N))/Math.LN10],ln:[da,[da],(N,[p])=>Math.log(p.evaluate(N))],log2:[da,[da],(N,[p])=>Math.log2(p.evaluate(N))],sin:[da,[da],(N,[p])=>Math.sin(p.evaluate(N))],cos:[da,[da],(N,[p])=>Math.cos(p.evaluate(N))],tan:[da,[da],(N,[p])=>Math.tan(p.evaluate(N))],asin:[da,[da],(N,[p])=>Math.asin(p.evaluate(N))],acos:[da,[da],(N,[p])=>Math.acos(p.evaluate(N))],atan:[da,[da],(N,[p])=>Math.atan(p.evaluate(N))],min:[da,gy(da),(N,p)=>Math.min(...p.map(_=>_.evaluate(N)))],max:[da,gy(da),(N,p)=>Math.max(...p.map(_=>_.evaluate(N)))],abs:[da,[da],(N,[p])=>Math.abs(p.evaluate(N))],round:[da,[da],(N,[p])=>{const _=p.evaluate(N);return _<0?-Math.round(-_):Math.round(_)}],floor:[da,[da],(N,[p])=>Math.floor(p.evaluate(N))],ceil:[da,[da],(N,[p])=>Math.ceil(p.evaluate(N))],"filter-==":[fl,[Ao,Wo],(N,[p,_])=>N.properties()[p.value]===_.value],"filter-id-==":[fl,[Wo],(N,[p])=>N.id()===p.value],"filter-type-==":[fl,[Ao],(N,[p])=>N.geometryType()===p.value],"filter-<":[fl,[Ao,Wo],(N,[p,_])=>{const C=N.properties()[p.value],M=_.value;return typeof C==typeof M&&C{const _=N.id(),C=p.value;return typeof _==typeof C&&_":[fl,[Ao,Wo],(N,[p,_])=>{const C=N.properties()[p.value],M=_.value;return typeof C==typeof M&&C>M}],"filter-id->":[fl,[Wo],(N,[p])=>{const _=N.id(),C=p.value;return typeof _==typeof C&&_>C}],"filter-<=":[fl,[Ao,Wo],(N,[p,_])=>{const C=N.properties()[p.value],M=_.value;return typeof C==typeof M&&C<=M}],"filter-id-<=":[fl,[Wo],(N,[p])=>{const _=N.id(),C=p.value;return typeof _==typeof C&&_<=C}],"filter->=":[fl,[Ao,Wo],(N,[p,_])=>{const C=N.properties()[p.value],M=_.value;return typeof C==typeof M&&C>=M}],"filter-id->=":[fl,[Wo],(N,[p])=>{const _=N.id(),C=p.value;return typeof _==typeof C&&_>=C}],"filter-has":[fl,[Wo],(N,[p])=>p.value in N.properties()],"filter-has-id":[fl,[],N=>N.id()!==null&&N.id()!==void 0],"filter-type-in":[fl,[Bd(Ao)],(N,[p])=>p.value.includes(N.geometryType())],"filter-id-in":[fl,[Bd(Wo)],(N,[p])=>p.value.includes(N.id())],"filter-in-small":[fl,[Ao,Bd(Wo)],(N,[p,_])=>_.value.includes(N.properties()[p.value])],"filter-in-large":[fl,[Ao,Bd(Wo)],(N,[p,_])=>function(C,M,F,z){for(;F<=z;){const H=F+z>>1;if(M[H]===C)return!0;M[H]>C?z=H-1:F=H+1}return!1}(N.properties()[p.value],_.value,0,_.value.length-1)],all:{type:fl,overloads:[[[fl,fl],(N,[p,_])=>p.evaluate(N)&&_.evaluate(N)],[gy(fl),(N,p)=>{for(const _ of p)if(!_.evaluate(N))return!1;return!0}]]},any:{type:fl,overloads:[[[fl,fl],(N,[p,_])=>p.evaluate(N)||_.evaluate(N)],[gy(fl),(N,p)=>{for(const _ of p)if(_.evaluate(N))return!0;return!1}]]},"!":[fl,[fl],(N,[p])=>!p.evaluate(N)],"is-supported-script":[fl,[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,gy(Wo),(N,p)=>p.map(_=>sp(_.evaluate(N))).join("")],split:[Bd(Ao),[Ao,Ao],(N,[p,_])=>p.evaluate(N).split(_.evaluate(N))],in:[fl,[Wo,Wo],(N,[p,_])=>{const C=p.evaluate(N),M=_.evaluate(N);return M!=null&&(Jw(C,M),M.includes(C))}],"index-of":{type:da,overloads:[[[Wo,Wo],(N,[p,_])=>{const C=p.evaluate(N),M=_.evaluate(N);return Jw(C,M),M.indexOf(C)}],[[Wo,Wo,da],(N,[p,_,C])=>{const M=p.evaluate(N),F=_.evaluate(N),z=C.evaluate(N);return Jw(M,F),F.indexOf(M,z)}]]},"resolved-locale":[Ao,[B0],(N,[p])=>p.evaluate(N).resolvedLocale()],random:[da,[da,da,Wo],(N,p)=>{const[_,C,M]=p.map(z=>z.evaluate(N));if(_>C||_===C)return _;let F;if(typeof M=="string")F=function(z){let H=0;if(z.length===0)return H;for(let Y=0;YJSON.stringify(xe)).join(", ")}, but found ${JSON.stringify(me)} instead.`);return me}catch(me){const xe=me;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 $v(N){return Array.isArray(N)&&N.length>0&&typeof N[0]=="string"&&Object.hasOwn(Rb,N[0])}function V0(N,p,_,C,M){const F=new oo(Rb,[],p?function(H){const Y={color:Qc,string:Ao,number:da,enum:Ao,boolean:fl,formatted:xh,resolvedImage:df,object:ng};return H.type==="array"?Bd(Y[H.value]||Wo,H.length):Y[H.type]}(p):void 0,void 0,void 0,_,C,M),z=F.parse(N,void 0,void 0,void 0,p&&p.type==="string"?{typeAnnotation:"coerce"}:void 0);return z?$1(new Bv(z,p,_,C,M)):op(F.errors)}class $_{constructor(p,_,C,M){this.kind=p,this._styleExpression=_,this.isLightConstant=C,this.isLineProgressConstant=M,this.isStateDependent=p!=="constant"&&!U0(_.expression),this.configDependencies=Db(_.expression),this.isIndoorDependent=Ox(_.expression)}evaluateWithoutErrorHandling(p,_,C,M,F,z){return this._styleExpression.evaluateWithoutErrorHandling(p,_,C,M,F,z)}evaluate(p,_,C,M,F,z,H){return this._styleExpression.evaluate(p,_,C,M,F,z,void 0,void 0,H)}}class og{constructor(p,_,C,M,F,z){this.kind=p,this.zoomStops=C,this._styleExpression=_,this.isStateDependent=p!=="camera"&&!U0(_.expression),this.isIndoorDependent=Ox(_.expression),this.isLightConstant=F,this.isLineProgressConstant=z,this.configDependencies=Db(_.expression),this.interpolationType=M}evaluateWithoutErrorHandling(p,_,C,M,F,z){return this._styleExpression.evaluateWithoutErrorHandling(p,_,C,M,F,z)}evaluate(p,_,C,M,F,z){return this._styleExpression.evaluate(p,_,C,M,F,z)}interpolationFactor(p,_,C){return this.interpolationType?xc.interpolationFactor(this.interpolationType,p,_,C):0}}function H0(N,p,_,C,M){if((N=V0(N,p,_,C,M)).result==="error")return N;const F=N.value.expression,z=D1(F);if(!z&&!Yy(p))return op([new Ro("","data expressions not supported")]);const H=Dx(F,["zoom","pitch","distance-from-center"]);if(!H&&!ej(p))return op([new Ro("","zoom expressions not supported")]);const Y=Dx(F,["measure-light"]);if(!Y&&!zk(p))return op([new Ro("","measure-light expression not supported")]);const se=Dx(F,["line-progress"]);if(!se&&!function(_e){return B_(_e.expression,"line-progress")}(p))return op([new Ro("","line-progress expression not supported")]);const me=p.expression&&p.expression.relaxZoomRestriction,xe=dp(F);return xe||H||me?xe instanceof Ro?op([xe]):xe instanceof xc&&!Zy(p)?op([new Ro("",'"interpolate" expressions cannot be used with this property')]):$1(xe?new og(z&&se?"camera":"composite",N.value,xe.labels,xe instanceof xc?xe.interpolation:void 0,Y,se):new $_(z&&se?"constant":"source",N.value,Y,se)):op([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 Xy{constructor(p,_){this._parameters=p,this._specification=_,Object.assign(this,zx(this._parameters,this._specification))}static deserialize(p){return new Xy(p._parameters,p._specification)}static serialize(p){return{_parameters:p._parameters,_specification:p._specification}}}function dp(N){let p=null;if(N instanceof Tp)p=dp(N.result);else if(N instanceof Bm){for(const _ of N.args)if(p=dp(_),p)break}else(N instanceof vi||N instanceof xc)&&N.input instanceof np&&N.input.name==="zoom"&&(p=N);return p instanceof Ro||N.eachChild(_=>{const C=dp(_);C instanceof Ro?p=C:p&&C&&p!==C&&(p=new Ro("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),p}class Uv{constructor(p,_,C){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 me=0;methis.width||M<0||_>this.height)return z;const H=this._nextGen(),{boxCells:Y,circleCells:se,boxKeys:me,circleKeys:xe,bboxes:_e,circles:Te,boxSeen:De,circleSeen:Ue,xCellCount:Ye}=this,nt=this._xCell(p),it=this._yCell(_),ut=this._xCell(C),ot=this._yCell(M);for(let vt=nt;vt<=ut;vt++)for(let kt=it;kt<=ot;kt++){const ls=Ye*kt+vt,At=Y[ls];if(At)for(let ts=0;ts=Ws&&M>=mn&&(!F||F(me[ns]))&&z.push({key:me[ns],x1:Ws,y1:mn,x2:ln,y2:_n})}const qt=se[ls];if(qt)for(let ts=0;tsthis.width||M<0||_>this.height)return z;const H=this._nextGen(),{boxCells:Y,boxKeys:se,bboxes:me,boxSeen:xe,xCellCount:_e,xScale:Te,yScale:De}=this,Ue=this._xCell(p),Ye=this._yCell(_),nt=this._xCell(C),it=this._yCell(M);for(let ut=Ue;ut<=nt;ut++)for(let ot=Ye;ot<=it;ot++){if(F&&!F(ut/Te,ot/De,(ut+1)/Te,(ot+1)/De))continue;const vt=Y[_e*ot+ut];if(vt)for(let kt=0;kt=qt&&M>=ts)&&z.push(se[ls])}}return z}hitTest(p,_,C,M,F){if(C<0||p>this.width||M<0||_>this.height)return!1;const z=this._nextGen(),{boxCells:H,circleCells:Y,boxKeys:se,circleKeys:me,bboxes:xe,circles:_e,boxSeen:Te,circleSeen:De,xCellCount:Ue}=this,Ye=this._xCell(p),nt=this._yCell(_),it=this._xCell(C),ut=this._yCell(M);for(let ot=Ye;ot<=it;ot++)for(let vt=nt;vt<=ut;vt++){const kt=Ue*vt+ot,ls=H[kt];if(ls)for(let qt=0;qt=xe[ns]&&M>=xe[ns+1]&&(!F||F(se[ts])))return!0}const At=Y[kt];if(At)for(let qt=0;qtthis.width||Y<0||z>this.height)return!1;const se=this._nextGen(),{boxCells:me,circleCells:xe,boxKeys:_e,circleKeys:Te,bboxes:De,circles:Ue,boxSeen:Ye,circleSeen:nt,xCellCount:it}=this,ut=this._xCell(F),ot=this._yCell(z),vt=this._xCell(H),kt=this._yCell(Y);for(let ls=ut;ls<=vt;ls++)for(let At=ot;At<=kt;At++){const qt=it*At+ls,ts=me[qt];if(ts)for(let Ps=0;Ps>>0,this.generation===0&&(this.boxSeen.fill(0),this.circleSeen.fill(0),this.generation=1),this.generation}_circlesCollide(p,_,C,M,F,z){const H=M-p,Y=F-_,se=C+z;return se*se>H*H+Y*Y}_circleAndRectCollide(p,_,C,M,F,z,H){const Y=(z-M)/2,se=Math.abs(p-(M+Y));if(se>Y+C)return!1;const me=(H-F)/2,xe=Math.abs(_-(F+me));if(xe>me+C)return!1;if(se<=Y||xe<=me)return!0;const _e=se-Y,Te=xe-me;return _e*_e+Te*Te<=C*C}}const G2={};function oa(N,p,_={}){Object.defineProperty(N,"_classRegistryKey",{value:p,writable:!1}),G2[p]={klass:N,omit:_.omit||[]}}oa(Object,"Object"),oa(Uv,"Grid"),delete xs.prototype.constructor,oa(Ci,"Color"),oa(xu,"Formatted"),oa(zm,"FormattedSection"),oa(yh,"ResolvedImage"),oa(Xy,"StylePropertyFunction"),oa(Bv,"StyleExpression",{omit:["_evaluator"]}),oa(vd,"ImageId"),oa(Ih,"ImageVariant"),oa(og,"ZoomDependentExpression"),oa($_,"ZoomConstantExpression"),oa(np,"CompoundExpression",{omit:["_evaluate"]});for(const N in Rb)G2[Rb[N]._classRegistryKey]||oa(Rb[N],`Expression${N}`);function A3(N){return N&&(N instanceof ArrayBuffer||N.constructor&&N.constructor.name==="ArrayBuffer")}const W2={Error,TypeError,RangeError,SyntaxError,ReferenceError,URIError,EvalError},lg=new Set(["message","stack","cause","errors","name","class"]);function qv(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 Y=0;Yme!==z).map(me=>qv(me,p)));const se=z;for(const me in se)Object.hasOwn(se,me)&&(lg.has(me)||(Y[me]=qv(se[me],p)));return Y}const C=N.constructor||Object,M=C._classRegistryKey;if(!M)throw new Error(`Can't serialize object of unregistered class "${C.name}".`);const F=C.serialize?C.serialize(N,p):{};if(!C.serialize){const z=G2[M].omit,H=N;for(const Y in H)Object.hasOwn(H,Y)&&(z.includes(Y)||(F[Y]=qv(H[Y],p)))}if(F.$name)throw new Error("$name property is reserved for worker serialization logic.");return M!=="Object"&&(F.$name=M),F}function Bx(N){if(N===null||typeof N!="object")return N;if(Array.isArray(N)){for(let M=0;MN>=1536&&N<=1791,_m=N=>N>=1872&&N<=1919,E3=N=>N>=2208&&N<=2303,HT=N=>N>=11904&&N<=12031,_9=N=>N>=12032&&N<=12255,w9=N=>N>=12272&&N<=12287,$k=N=>N>=12288&&N<=12351,FC=N=>N>=12352&&N<=12447,OC=N=>N>=12448&&N<=12543,G0=N=>N>=12544&&N<=12591,GT=N=>N>=12704&&N<=12735,T3=N=>N>=12736&&N<=12783,Fb=N=>N>=12784&&N<=12799,Uk=N=>N>=12800&&N<=13055,tj=N=>N>=13056&&N<=13311,qk=N=>N>=13312&&N<=19903,zC=N=>N>=19968&&N<=40959,BC=N=>N>=40960&&N<=42127,I6=N=>N>=42128&&N<=42191,M3=N=>N>=44032&&N<=55215,L6=N=>N>=63744&&N<=64255,WT=N=>N>=64336&&N<=65023,R6=N=>N>=65040&&N<=65055,$C=N=>N>=65072&&N<=65103,j9=N=>N>=65104&&N<=65135,D6=N=>N>=65136&&N<=65279,ie=N=>N>=65280&&N<=65519;function de(N){for(const p of N)if(tt(p.charCodeAt(0)))return!0;return!1}function Oe(N){return!(K2(N)||_m(N)||E3(N)||WT(N)||D6(N))}function tt(N){return!(N!==746&&N!==747&&(N<4352||!(GT(N)||G0(N)||$C(N)&&!(N>=65097&&N<=65103)||L6(N)||tj(N)||HT(N)||T3(N)||!(!$k(N)||N>=12296&&N<=12305||N>=12308&&N<=12319||N===12336)||qk(N)||zC(N)||Uk(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)||M3(N)||FC(N)||w9(N)||(p=>p>=12688&&p<=12703)(N)||_9(N)||Fb(N)||OC(N)&&N!==12540||!(!ie(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)||!(!j9(N)||N>=65112&&N<=65118||N>=65123&&N<=65126)||(p=>p>=5120&&p<=5759)(N)||(p=>p>=6320&&p<=6399)(N)||R6(N)||(p=>p>=19904&&p<=19967)(N)||BC(N)||I6(N))))}function lt(N){return!(tt(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)||$k(p)||OC(p)||(_=>_>=57344&&_<=63743)(p)||$C(p)||j9(p)||ie(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||WT(N)||D6(N)}function Ys(N,p){return!(!p&&Ot(N)||N>=2304&&N<=3583||N>=3840&&N<=4255||(_=>_>=6016&&_<=6143)(N))}function ur(N){for(const p of N)if(Ot(p.charCodeAt(0)))return!0;return!1}const Or={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let ci=null,Mi=Or.unavailable,pl=null;const Zi=function(N){N&&(Mi=Or.error),ci&&ci(N)};function Hh(){uh.fire(new zl("pluginStateChange",{pluginStatus:Mi,pluginURL:pl}))}const uh=new Xc,xy=function(){return Mi},U_=function(){if(Mi!==Or.deferred||!pl)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Mi=Or.loading,Hh(),pl&&Xr({url:pl}).then(()=>{Mi=Or.loaded,Hh()}).catch(N=>{Zi(N)})},zr={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Mi===Or.loaded||zr.applyArabicShaping!=null,isLoading:()=>Mi===Or.loading,setState(N){Mi=N.pluginStatus,pl=N.pluginURL},isParsing:()=>Mi===Or.parsing,isParsed:()=>Mi===Or.parsed,getPluginURL:()=>pl};class Hn{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(_,C){for(const M of _)if(!Ys(M.charCodeAt(0),C))return!1;return!0}(p,zr.isLoaded())}}class aa{constructor(p,_,C,M,F){this.property=p,this.value=_,this.expression=function(z,H,Y,se,me){if(lp(z))return new Xy(z,H);if($v(z)||Array.isArray(z)&&z.length>0){const xe=H0(z,H,Y,se,me);if(xe.result==="error")throw new Error(xe.value.map(_e=>`${_e.key}: ${_e.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,C,M,F)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(p,_,C,M){return this.property.possiblyEvaluate(this,p,_,C,M)}}class Qi{constructor(p,_,C,M){this.property=p,this.value=new aa(p,void 0,_,C,M)}transitioned(p,_){return new Jc(this.property,this.value,_,{...p.transition,...this.transition},p.now)}untransitioned(){return new Jc(this.property,this.value,null,{},0)}}class gl{constructor(p,_,C,M){this._properties=p,this._values=Object.create(p.defaultTransitionablePropertyValues),this._scope=_,this._options=C,this._iconImageUseTheme=M,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(p){return $l(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 aa(this._values[p].property,_===null?void 0:$l(_),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 C=this._properties.properties;if(p)for(const M in p){const F=p[M];if(M.endsWith("-transition")){const z=M.slice(0,-11);C[z]&&this.setTransition(z,F)}else Object.hasOwn(C,M)&&this.setValue(M,F)}}getTransition(p){return $l(this._values[p].transition)}setTransition(p,_){Object.hasOwn(this._values,p)||(this._values[p]=new Qi(this._values[p].property)),this._values[p].transition=$l(_)||void 0}serialize(){const p={};for(const _ of Object.keys(this._values)){const C=this.getValue(_);C!==void 0&&(p[_]=C);const M=this.getTransition(_);M!==void 0&&(p[`${_}-transition`]=M)}return p}transitioned(p,_){const C=new Sc(this._properties);for(const M of Object.keys(this._values))C._values[M]=this._values[M].transitioned(p,_._values[M]);return C}untransitioned(){const p=new Sc(this._properties);for(const _ of Object.keys(this._values))p._values[_]=this._values[_].untransitioned();return p}isIndoorDependent(){return this._isIndoorDependent}}class Jc{constructor(p,_,C,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=C)}possiblyEvaluate(p,_,C){const M=p.now||0,F=this.value.possiblyEvaluate(p,_,C),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 N9(N){return N instanceof Number||N instanceof String||N instanceof Boolean?N.valueOf():N}function k9(N){if(Array.isArray(N))return N.map(k9);if(N instanceof Object&&!(N instanceof Number||N instanceof String||N instanceof Boolean)){const p={},_=N;for(const C in _)p[C]=k9(_[C]);return p}return N9(N)}function F6(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(!F6(p)&&typeof p!="boolean")return!1;return!0;default:return!0}}function dY(N,p="",_=null,C="fill"){if(N==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};F6(N)||(N=O6(N));const M=N;let F=!0;try{F=function(me){if(!KT(me))return me;let xe=k9(me);return coe(xe),xe=loe(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(C!=="background"&&C!=="sky"&&C!=="slot"){H=Zs[`filter_${C}`];const me=V0(F,H,p,_);if(me.result==="error")throw new Error(me.value.map(xe=>`${xe.key}: ${xe.message}`).join(", "));z=(xe,_e,Te)=>me.value.evaluate(xe,_e,{},Te)}let Y=null,se=null;if(F!==M){const me=V0(M,H,p,_);if(me.result==="error")throw new Error(me.value.map(xe=>`${xe.key}: ${xe.message}`).join(", "));Y=(xe,_e,Te,De,Ue)=>me.value.evaluate(xe,_e,{},Te,void 0,void 0,De,Ue),se=!D1(me.value.expression)}return{filter:z,dynamicFilter:Y||void 0,needGeometry:uoe(F),needFeature:!!se}}function loe(N){if(!Array.isArray(N))return N;const p=function(_){if(doe.has(_[0])){for(let C=1;C<_.length;C++)if(KT(_[C]))return!0}return _}(N);return p===!0?p:p.map(_=>loe(_))}function coe(N){let p=!1;const _=[];if(N[0]==="case"){for(let C=1;C",">=","<","<=","to-boolean"]);function uY(N,p){return Np?1:0}function uoe(N){if(!Array.isArray(N))return!1;if(N[0]==="within"||N[0]==="distance")return!0;for(let p=1;p"||p==="<="||p===">="?S9(N[1],N[2],p):p==="any"?(_=N.slice(1),["any"].concat(_.map(O6))):p==="all"?["all"].concat(N.slice(1).map(O6)):p==="none"?["all"].concat(N.slice(1).map(O6).map(I3)):p==="in"?hoe(N[1],N.slice(2)):p==="!in"?I3(hoe(N[1],N.slice(2))):p==="has"?C9(N[1]):p!=="!has"||I3(C9(N[1]));var _}function S9(N,p,_){switch(N){case"$type":return[`filter-type-${_}`,p];case"$id":return[`filter-id-${_}`,p];default:return[`filter-${_}`,N,p]}}function hoe(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(uY)]]:["filter-in-small",N,["literal",p]]}}function C9(N){switch(N){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",N]}}function I3(N){return["!",N]}const YT="";function z6(N,p){return p?`${N}${YT}${p}`:N}function hY(N){const p=N.indexOf(YT);return p>=0?N.slice(p+1):""}let moe,mY=1;const foe=()=>moe||(moe=new Wu({"icon-size":new kr(Zs.layout_symbol["icon-size"]),"icon-image":new kr(Zs.layout_symbol["icon-image"]),"icon-rotate":new kr(Zs.layout_symbol["icon-rotate"]),"icon-offset":new kr(Zs.layout_symbol["icon-offset"]),"text-size":new kr(Zs.layout_symbol["text-size"]),"text-rotate":new kr(Zs.layout_symbol["text-rotate"]),"text-offset":new kr(Zs.layout_symbol["text-offset"])}));let poe;const goe=()=>poe||(poe=new Wu({"icon-opacity":new kr(Zs.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new kr(Zs.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new kr(Zs.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new kr(Zs.paint_symbol["text-emissive-strength"]),"icon-color":new kr(Zs.paint_symbol["icon-color"]),"icon-halo-color":new kr(Zs.paint_symbol["icon-halo-color"]),"icon-halo-width":new kr(Zs.paint_symbol["icon-halo-width"]),"icon-halo-blur":new kr(Zs.paint_symbol["icon-halo-blur"]),"icon-translate":new kr(Zs.paint_symbol["icon-translate"]),"text-opacity":new kr(Zs.paint_symbol["text-opacity"]),"text-occlusion-opacity":new kr(Zs.paint_symbol["text-occlusion-opacity"]),"text-color":new kr(Zs.paint_symbol["text-color"],{runtimeType:Qc,getOverride:N=>N.textColor,hasOverride:N=>!!N.textColor}),"text-halo-color":new kr(Zs.paint_symbol["text-halo-color"]),"text-halo-width":new kr(Zs.paint_symbol["text-halo-width"]),"text-halo-blur":new kr(Zs.paint_symbol["text-halo-blur"]),"text-translate":new kr(Zs.paint_symbol["text-translate"]),"symbol-z-offset":new kr(Zs.paint_symbol["symbol-z-offset"]),"placement-priority":new kr(Zs.paint_symbol["placement-priority"]),"placement-group":new kr(Zs.paint_symbol["placement-group"]),"icon-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}));class TFe{constructor(p,_,C,M,F,z){this._conditionSpec=p,this._propertiesSpec=C;const H=V0(p,Zs.appearance.condition);if(H.result==="success"&&(this.condition=H.value),this.name=_,C){this.layoutProperties=new Sl(foe()),this.unevaluatedLayout=new Md(foe(),M,F,z),this.paintProperties=new Sl(goe()),this.unevaluatedPaint=new Md(goe(),M,F,"");for(const Y in C)Y in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(Y,C[Y]):Y in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(Y,C[Y])}}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,_,C){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(p,void 0,_,C)),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"),C=this.hasLayoutProperty("icon-offset"),M=this.hasLayoutProperty("icon-rotate");return p||_||C||M}hasTextLayoutProperties(){const p=this.hasLayoutProperty("text-size"),_=this.hasLayoutProperty("text-offset"),C=this.hasLayoutProperty("text-rotate");return p||_||C}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 fY="-transition",MFe=new Set(["fill","line","background","hillshade","raster"]);class Qy extends Xc{constructor(p,_,C,M,F,z){if(super(),this.id=p.id,this.fqid=z6(this.id,C),this.runtimeLayerUID=mY++,this.type=p.type,this.scope=C,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 Md(_.layout,this.scope,F,this.iconImageUseTheme)),_.paint)){this._transitionablePaint=new gl(_.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,_,C,M,F){}isDraped(p){return!this.is3D(!0)&&MFe.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 C=this._unevaluatedLayout;C._properties.properties[p]&&(C.setValue(p,_),p==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(p){this.appearances=[],p.forEach(_=>{this.appearances.push(new TFe(_.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(fY)?this._transitionablePaint.getTransition(p.slice(0,-11)):this._transitionablePaint.getValue(p)}isPaintProperty(p){return!!this._transitionablePaint._properties.properties[p]}setPaintProperty(p,_){const C=this._transitionablePaint,M=C._properties.properties;if(p.endsWith(fY)){const xe=p.slice(0,-11);return M[xe]&&C.setTransition(xe,_||void 0),!1}if(!M[p])return!1;const F=C._values[p],z=F.value.isDataDriven(),H=F.value;C.setValue(p,_),this._handleSpecialPaintPropertyUpdate(p);const Y=C._values[p].value,se=Y.isDataDriven(),me=p.endsWith("pattern")||p==="line-dasharray";return se||z||me||this._handleOverridablePaintPropertyUpdate(p,H,Y)}_handleSpecialPaintPropertyUpdate(p){}getProgramIds(){return null}getDefaultProgramParams(p,_,C){return null}_handleOverridablePaintPropertyUpdate(p,_,C){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())),gc(p,(_,C)=>!(_===void 0||C==="layout"&&!Object.keys(_).length||C==="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 bh&&Yy(_.property.specification)&&(_.value.kind==="source"||_.value.kind==="composite")&&_.value.isStateDependent)return!0}for(const p of this.appearances)if(!U0(p.condition.expression))return!0;return!1}compileFilter(p){this._filterCompiled||(this._featureFilter=dY(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,_,C){return{}}queryRadius(p){}queryIntersectsFeature(p,_,C,M,F,z,H,Y,se,me){}}function A9(N,p,_){if(!N._unevaluatedLayout)return!1;const C=N._unevaluatedLayout.getValue(p);return C!==void 0&&(typeof C!="string"||_(C))}function ZT(N,p,_=2){const C=p&&p.length,M=C?p[0]*_:N.length;let F=xoe(N,0,M,_,!0);const z=[];if(!F||F.next===F.prev)return z;let H,Y,se;if(C&&(F=function(me,xe,_e,Te){const De=[];for(let Ue=0,Ye=xe.length;Ue80*_){H=N[0],Y=N[1];let me=H,xe=Y;for(let _e=_;_eme&&(me=Te),De>xe&&(xe=De)}se=Math.max(me-H,xe-Y),se=se!==0?32767/se:0}return B6(F,z,_,H,Y,se,0),z}function xoe(N,p,_,C,M){let F;if(M===function(z,H,Y,se){let me=0;for(let xe=H,_e=Y-se;xe0)for(let z=p;z<_;z+=C)F=woe(z/C|0,N[z],N[z+1],F);else for(let z=_-C;z>=p;z-=C)F=woe(z/C|0,N[z],N[z+1],F);return F&&QT(F,F.next)&&(q6(F),F=F.next),F}function L3(N,p){if(!N)return N;p||(p=N);let _,C=N;do if(_=!1,C.steiner||!QT(C,C.next)&&Ff(C.prev,C,C.next)!==0)C=C.next;else{if(q6(C),C=p=C.prev,C===C.next)break;_=!0}while(_||C!==p);return p}function B6(N,p,_,C,M,F,z){if(!N)return;!z&&F&&function(Y,se,me,xe){let _e=Y;do _e.z===0&&(_e.z=M9(_e.x,_e.y,se,me,xe)),_e.prevZ=_e.prev,_e.nextZ=_e.next,_e=_e.next;while(_e!==Y);_e.prevZ.nextZ=null,_e.prevZ=null,function(Te){let De,Ue=1;do{let Ye,nt=Te;Te=null;let it=null;for(De=0;nt;){De++;let ut=nt,ot=0;for(let kt=0;kt0||vt>0&&ut;)ot!==0&&(vt===0||!ut||nt.z<=ut.z)?(Ye=nt,nt=nt.nextZ,ot--):(Ye=ut,ut=ut.nextZ,vt--),it?it.nextZ=Ye:Te=Ye,Ye.prevZ=it,it=Ye;nt=ut}it.nextZ=null,Ue*=2}while(De>1)}(_e)}(N,C,M,F);let H=N;for(;N.prev!==N.next;){const Y=N.prev,se=N.next;if(F?IFe(N,C,M,F):PFe(N))p.push(Y.i,N.i,se.i),q6(N),N=se.next,H=se.next;else if((N=se)===H){z?z===1?B6(N=E9(L3(N),p),p,_,C,M,F,2):z===2&&LFe(N,p,_,C,M,F):B6(L3(N),p,_,C,M,F,1);break}}}function PFe(N){const p=N.prev,_=N,C=N.next;if(Ff(p,_,C)>=0)return!1;const M=p.x,F=_.x,z=C.x,H=p.y,Y=_.y,se=C.y,me=Math.min(M,F,z),xe=Math.min(H,Y,se),_e=Math.max(M,F,z),Te=Math.max(H,Y,se);let De=C.next;for(;De!==p;){if(De.x>=me&&De.x<=_e&&De.y>=xe&&De.y<=Te&&XT(M,H,F,Y,z,se,De.x,De.y)&&Ff(De.prev,De,De.next)>=0)return!1;De=De.next}return!0}function IFe(N,p,_,C){const M=N.prev,F=N,z=N.next;if(Ff(M,F,z)>=0)return!1;const H=M.x,Y=F.x,se=z.x,me=M.y,xe=F.y,_e=z.y,Te=Math.min(H,Y,se),De=Math.min(me,xe,_e),Ue=Math.max(H,Y,se),Ye=Math.max(me,xe,_e),nt=M9(Te,De,p,_,C),it=M9(Ue,Ye,p,_,C);let ut=N.prevZ,ot=N.nextZ;for(;ut&&ut.z>=nt&&ot&&ot.z<=it;){if(ut.x>=Te&&ut.x<=Ue&&ut.y>=De&&ut.y<=Ye&&ut!==M&&ut!==z&&XT(H,me,Y,xe,se,_e,ut.x,ut.y)&&Ff(ut.prev,ut,ut.next)>=0||(ut=ut.prevZ,ot.x>=Te&&ot.x<=Ue&&ot.y>=De&&ot.y<=Ye&&ot!==M&&ot!==z&&XT(H,me,Y,xe,se,_e,ot.x,ot.y)&&Ff(ot.prev,ot,ot.next)>=0))return!1;ot=ot.nextZ}for(;ut&&ut.z>=nt;){if(ut.x>=Te&&ut.x<=Ue&&ut.y>=De&&ut.y<=Ye&&ut!==M&&ut!==z&&XT(H,me,Y,xe,se,_e,ut.x,ut.y)&&Ff(ut.prev,ut,ut.next)>=0)return!1;ut=ut.prevZ}for(;ot&&ot.z<=it;){if(ot.x>=Te&&ot.x<=Ue&&ot.y>=De&&ot.y<=Ye&&ot!==M&&ot!==z&&XT(H,me,Y,xe,se,_e,ot.x,ot.y)&&Ff(ot.prev,ot,ot.next)>=0)return!1;ot=ot.nextZ}return!0}function E9(N,p){let _=N;do{const C=_.prev,M=_.next.next;!QT(C,M)&&boe(C,_,_.next,M)&&U6(C,M)&&U6(M,C)&&(p.push(C.i,_.i,M.i),q6(_),q6(_.next),_=N=M),_=_.next}while(_!==N);return L3(_)}function LFe(N,p,_,C,M,F){let z=N;do{let H=z.next.next;for(;H!==z.prev;){if(z.i!==H.i&&voe(z,H)){let Y=_oe(z,H);return z=L3(z,z.next),Y=L3(Y,Y.next),B6(z,p,_,C,M,F,0),void B6(Y,p,_,C,M,F,0)}H=H.next}z=z.next}while(z!==N)}function RFe(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 T9(N,p){const _=function(M,F){let z=F;const H=M.x,Y=M.y;let se,me=-1/0;if(QT(M,z))return z;do{if(QT(M,z.next))return z.next;if(Y<=z.y&&Y>=z.next.y&&z.next.y!==z.y){const Ue=z.x+(Y-z.y)*(z.next.x-z.x)/(z.next.y-z.y);if(Ue<=H&&Ue>me&&(me=Ue,se=z.x=z.x&&z.x>=_e&&H!==z.x&&yoe(Yse.x||z.x===se.x&&DFe(se,z)))&&(se=z,De=Ue)}z=z.next}while(z!==xe);return se}(N,p);if(!_)return p;const C=_oe(_,N);return L3(C,C.next),L3(_,_.next)}function DFe(N,p){return Ff(N.prev,N,p.prev)<0&&Ff(p.next,N,N.next)<0}function M9(N,p,_,C,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-C)*M|0)|p<<8))|p<<4))|p<<2))|p<<1))<<1}function FFe(N){let p=N,_=N;do(p.x<_.x||p.x===_.x&&p.y<_.y)&&(_=p),p=p.next;while(p!==N);return _}function yoe(N,p,_,C,M,F,z,H){return(M-z)*(p-H)>=(N-z)*(F-H)&&(N-z)*(C-H)>=(_-z)*(p-H)&&(_-z)*(F-H)>=(M-z)*(C-H)}function XT(N,p,_,C,M,F,z,H){return!(N===z&&p===H)&&yoe(N,p,_,C,M,F,z,H)}function voe(N,p){return N.next.i!==p.i&&N.prev.i!==p.i&&!function(_,C){let M=_;do{if(M.i!==_.i&&M.next.i!==_.i&&M.i!==C.i&&M.next.i!==C.i&&boe(M,M.next,_,C))return!0;M=M.next}while(M!==_);return!1}(N,p)&&(U6(N,p)&&U6(p,N)&&function(_,C){let M=_,F=!1;const z=(_.x+C.x)/2,H=(_.y+C.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)&&(Ff(N.prev,N,p.prev)||Ff(N,p.prev,p))||QT(N,p)&&Ff(N.prev,N,N.next)>0&&Ff(p.prev,p,p.next)>0)}function Ff(N,p,_){return(p.y-N.y)*(_.x-p.x)-(p.x-N.x)*(_.y-p.y)}function QT(N,p){return N.x===p.x&&N.y===p.y}function boe(N,p,_,C){const M=P9(Ff(N,p,_)),F=P9(Ff(N,p,C)),z=P9(Ff(_,C,N)),H=P9(Ff(_,C,p));return M!==F&&z!==H||!(M!==0||!$6(N,_,p))||!(F!==0||!$6(N,C,p))||!(z!==0||!$6(_,N,C))||!(H!==0||!$6(_,p,C))}function $6(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 P9(N){return N>0?1:N<0?-1:0}function U6(N,p){return Ff(N.prev,N,N.next)<0?Ff(N,p,N.next)>=0&&Ff(N,N.prev,p)>=0:Ff(N,p,N.prev)<0||Ff(N,N.next,p)<0}function _oe(N,p){const _=pY(N.i,N.x,N.y),C=pY(p.i,p.x,p.y),M=N.next,F=p.prev;return N.next=p,p.prev=N,_.next=M,M.prev=_,C.next=_,_.prev=C,F.next=C,C.prev=F,C}function woe(N,p,_,C){const M=pY(N,p,_);return C?(M.next=C.next,M.prev=C,C.next.prev=M,C.next=M):(M.prev=M,M.next=M),M}function q6(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 pY(N,p,_){return{i:N,x:p,y:_,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function gY(N,p,_=1){if(!N)return null;const C=typeof N=="string"?yh.from(N).getPrimary():N.getPrimary(),M=typeof N=="string"?null:N.getSecondary();for(const F of[C,M]){if(!F)continue;const z=F.id.toString();p.has(z)||p.set(z,[]),F.scaleSelf(_),p.get(z).push(F)}return{primary:C.toString(),secondary:M?M.toString():null}}function V6(N,p,_,C){const M=C.patternDependencies;let F=!1;for(const z of p){const H=z.paint.get(`${N}-pattern`);H.isConstant()||(F=!0),gY(H.constantOr(null),M,_)&&(F=!0)}return F}function xY(N,p,_,C,M,F){const z=F.patternDependencies;for(const H of p){const Y=H.paint.get(`${N}-pattern`).value;if(Y.kind!=="constant"){const se=gY(Y.evaluate({zoom:C},_,{},void 0,F.availableImages),z,M);if(!se)continue;const{primary:me,secondary:xe}=se;me&&(_.patterns[H.id]=[me,xe].filter(Boolean))}}return _}const pf=Pr/Math.PI/2,Vk=64,yY=[Vk,32,16],Vv=-pf,q_=pf;function sj(N,p,_,C=pf){return _=Yr(_),[N*Math.sin(_)*C,-p*C,N*Math.cos(_)*C]}function R3(N,p,_){return sj(Math.cos(Yr(N)),Math.sin(Yr(N)),p,_)}const JT=63710088e-1,vY=2*Math.PI*JT;class Il{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 Il(ml(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,C=this.lat*_,M=p.lat*_,F=Math.sin(C)*Math.sin(M)+Math.cos(C)*Math.cos(M)*Math.cos((p.lng-this.lng)*_);return JT*Math.acos(Math.min(F,1))}toBounds(p=0){const _=360*p/40075017,C=_/Math.cos(Math.PI/180*this.lat);return new V_({lng:this.lng-C,lat:this.lat-_},{lng:this.lng+C,lat:this.lat+_})}toEcef(p){return R3(this.lat,this.lng,pf+p*pf/JT)}static convert(p){if(p instanceof Il)return p;if(Array.isArray(p)&&(p.length===2||p.length===3))return new Il(Number(p[0]),Number(p[1]));if(!Array.isArray(p)&&typeof p=="object"&&p!==null)return new Il(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 V_{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 Il?new Il(p.lng,p.lat):Il.convert(p),this}setSouthWest(p){return this._sw=p instanceof Il?new Il(p.lng,p.lat):Il.convert(p),this}extend(p){const _=this._sw,C=this._ne;let M,F;if(p instanceof Il)M=p,F=p;else{if(!(p instanceof V_))return Array.isArray(p)?p.length===4||p.every(Array.isArray)?this.extend(V_.convert(p)):this.extend(Il.convert(p)):typeof p=="object"&&p!==null&&Object.hasOwn(p,"lat")&&(Object.hasOwn(p,"lon")||Object.hasOwn(p,"lng"))?this.extend(Il.convert(p)):this;if(M=p._sw,F=p._ne,!M||!F)return this}return _||C?(_.lng=Math.min(M.lng,_.lng),_.lat=Math.min(M.lat,_.lat),C.lng=Math.max(F.lng,C.lng),C.lat=Math.max(F.lat,C.lat)):(this._sw=new Il(M.lng,M.lat),this._ne=new Il(F.lng,F.lat)),this}getCenter(){return new Il((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 Il(this.getWest(),this.getNorth())}getSouthEast(){return new Il(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:C}=Il.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<=C&&C<=this._ne.lat&&M}static convert(p){if(p)return p instanceof V_?p:new V_(p)}}function H6(N){return vY*Math.cos(N*Math.PI/180)}function Xd(N,p){return N/H6(p)}function joe(N,p){return N*H6($d(p))}const L=85.051129;function k(N){return Math.cos(Yr(ea(N,-85.051129,L)))}function T(N,p){const _=ea(p,0,25.5),C=Math.pow(2,_);return k(N)*vY/(512*C)}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/Pr)/(1<=Y?(oe(N,p,_,se,me,F,xe,H,Y),oe(N,se,me,C,M,xe,z,H,Y)):N.push(z)}function he(N,p,_){let C=N[0],M=C.x,F=C.y;p(C);const z=[C];for(let H=1;HN.x+1||CN.y+1)&&Yo("Geometry exceeds allowed extent, reduce your vector tile buffer size"),N}function dt(N,p,_){const C=N.loadGeometry(),M=N.extent,F=Pr/M;if(p&&_&&_.projection.isReprojectedInTileSpace){const z=1<{const Te=Rx((p.x+_e.x/M)/z),De=$d((p.y+_e.y/M)/z),Ue=me.project(Te,De);_e.x=(Ue.x*H-Y)*M,_e.y=(Ue.y*H-se)*M};for(let _e=0;_e=M||De.y<0||De.y>=M||(xe(De),Te.push(De));C[_e]=Te}}for(const z of C)for(const H of z)Xe(H,F);return C}function _t(N,p){return{type:N.type,id:N.id,properties:N.properties,geometry:p?dt(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 ss=new ArrayBuffer(0);class Jt{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=ss),_._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,C=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 C=Math.max(C,F),_+=F*H,{name:M.name,type:M.type,components:H,offset:z,normalized:M.normalized}}),size:ps(_,Math.max(C,p)),alignment:p}}function ps(N,p){return Math.ceil(N/p)*p}class Gs extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_){const C=this.length;return this.resize(C+1),this.emplace(C,p,_)}emplace(p,_,C){const M=2*p;return this.int16[M+0]=_,this.int16[M+1]=C,p}}Gs.prototype.bytesPerElement=4,oa(Gs,"StructArrayLayout2i4");class Ls extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,p,_,C)}emplace(p,_,C,M){const F=3*p;return this.int16[F+0]=_,this.int16[F+1]=C,this.int16[F+2]=M,p}}Ls.prototype.bytesPerElement=6,oa(Ls,"StructArrayLayout3i6");class sn extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,C,M){const F=this.length;return this.resize(F+1),this.emplace(F,p,_,C,M)}emplace(p,_,C,M,F){const z=4*p;return this.int16[z+0]=_,this.int16[z+1]=C,this.uint16[z+2]=M,this.uint16[z+3]=F,p}}sn.prototype.bytesPerElement=8,oa(sn,"StructArrayLayout2i2ui8");class Bs extends Jt{_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}}Bs.prototype.bytesPerElement=4,oa(Bs,"StructArrayLayout1f4");class nn extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,p,_,C)}emplace(p,_,C,M){const F=4*p,z=2*p;return this.int16[F+0]=_,this.int16[F+1]=C,this.float32[z+1]=M,p}}nn.prototype.bytesPerElement=8,oa(nn,"StructArrayLayout2i1f8");class yn extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,p,_,C)}emplace(p,_,C,M){const F=4*p;return this.int16[F+0]=_,this.int16[F+1]=C,this.int16[F+2]=M,p}}yn.prototype.bytesPerElement=8,oa(yn,"StructArrayLayout3i8");class Tn extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,C,M){const F=this.length;return this.resize(F+1),this.emplace(F,p,_,C,M)}emplace(p,_,C,M,F){const z=4*p;return this.int16[z+0]=_,this.int16[z+1]=C,this.int16[z+2]=M,this.int16[z+3]=F,p}}Tn.prototype.bytesPerElement=8,oa(Tn,"StructArrayLayout4i8");class Gn extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F){const z=this.length;return this.resize(z+1),this.emplace(z,p,_,C,M,F)}emplace(p,_,C,M,F,z){const H=5*p;return this.int16[H+0]=_,this.int16[H+1]=C,this.int16[H+2]=M,this.int16[H+3]=F,this.int16[H+4]=z,p}}Gn.prototype.bytesPerElement=10,oa(Gn,"StructArrayLayout5i10");class zn extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H){const Y=this.length;return this.resize(Y+1),this.emplace(Y,p,_,C,M,F,z,H)}emplace(p,_,C,M,F,z,H,Y){const se=6*p,me=12*p,xe=3*p;return this.int16[se+0]=_,this.int16[se+1]=C,this.uint8[me+4]=M,this.uint8[me+5]=F,this.uint8[me+6]=z,this.uint8[me+7]=H,this.float32[xe+2]=Y,p}}zn.prototype.bytesPerElement=12,oa(zn,"StructArrayLayout2i4ub1f12");class Dn extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,p,_,C)}emplace(p,_,C,M){const F=3*p;return this.float32[F+0]=_,this.float32[F+1]=C,this.float32[F+2]=M,p}}Dn.prototype.bytesPerElement=12,oa(Dn,"StructArrayLayout3f12");class Mr extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F){const z=this.length;return this.resize(z+1),this.emplace(z,p,_,C,M,F)}emplace(p,_,C,M,F,z){const H=6*p,Y=3*p;return this.uint16[H+0]=_,this.uint16[H+1]=C,this.uint16[H+2]=M,this.uint16[H+3]=F,this.float32[Y+2]=z,p}}Mr.prototype.bytesPerElement=12,oa(Mr,"StructArrayLayout4ui1f12");class kn extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,C,M){const F=this.length;return this.resize(F+1),this.emplace(F,p,_,C,M)}emplace(p,_,C,M,F){const z=4*p;return this.uint16[z+0]=_,this.uint16[z+1]=C,this.uint16[z+2]=M,this.uint16[z+3]=F,p}}kn.prototype.bytesPerElement=8,oa(kn,"StructArrayLayout4ui8");class pr extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z){const H=this.length;return this.resize(H+1),this.emplace(H,p,_,C,M,F,z)}emplace(p,_,C,M,F,z,H){const Y=6*p;return this.int16[Y+0]=_,this.int16[Y+1]=C,this.int16[Y+2]=M,this.int16[Y+3]=F,this.int16[Y+4]=z,this.int16[Y+5]=H,p}}pr.prototype.bytesPerElement=12,oa(pr,"StructArrayLayout6i12");class ta extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H,Y,se,me,xe,_e){const Te=this.length;return this.resize(Te+1),this.emplace(Te,p,_,C,M,F,z,H,Y,se,me,xe,_e)}emplace(p,_,C,M,F,z,H,Y,se,me,xe,_e,Te){const De=12*p;return this.int16[De+0]=_,this.int16[De+1]=C,this.int16[De+2]=M,this.int16[De+3]=F,this.uint16[De+4]=z,this.uint16[De+5]=H,this.uint16[De+6]=Y,this.uint16[De+7]=se,this.int16[De+8]=me,this.int16[De+9]=xe,this.int16[De+10]=_e,this.int16[De+11]=Te,p}}ta.prototype.bytesPerElement=24,oa(ta,"StructArrayLayout4i4ui4i24");class ka extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z){const H=this.length;return this.resize(H+1),this.emplace(H,p,_,C,M,F,z)}emplace(p,_,C,M,F,z,H){const Y=10*p,se=5*p;return this.int16[Y+0]=_,this.int16[Y+1]=C,this.int16[Y+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 qr extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M){const F=this.length;return this.resize(F+1),this.emplace(F,p,_,C,M)}emplace(p,_,C,M,F){const z=4*p;return this.float32[z+0]=_,this.float32[z+1]=C,this.float32[z+2]=M,this.float32[z+3]=F,p}}qr.prototype.bytesPerElement=16,oa(qr,"StructArrayLayout4f16");class Jr extends Jt{_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}}Jr.prototype.bytesPerElement=4,oa(Jr,"StructArrayLayout1ul4");class si extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_){const C=this.length;return this.resize(C+1),this.emplace(C,p,_)}emplace(p,_,C){const M=2*p;return this.uint16[M+0]=_,this.uint16[M+1]=C,p}}si.prototype.bytesPerElement=4,oa(si,"StructArrayLayout2ui4");class Gr extends Jt{_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,_,C,M,F,z,H,Y,se,me,xe,_e,Te){const De=this.length;return this.resize(De+1),this.emplace(De,p,_,C,M,F,z,H,Y,se,me,xe,_e,Te)}emplace(p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De){const Ue=20*p,Ye=10*p;return this.int16[Ue+0]=_,this.int16[Ue+1]=C,this.int16[Ue+2]=M,this.int16[Ue+3]=F,this.int16[Ue+4]=z,this.float32[Ye+3]=H,this.float32[Ye+4]=Y,this.float32[Ye+5]=se,this.float32[Ye+6]=me,this.int16[Ue+14]=xe,this.uint32[Ye+8]=_e,this.uint16[Ue+18]=Te,this.uint16[Ue+19]=De,p}}Gr.prototype.bytesPerElement=40,oa(Gr,"StructArrayLayout5i4f1i1ul2ui40");class Sr extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H){const Y=this.length;return this.resize(Y+1),this.emplace(Y,p,_,C,M,F,z,H)}emplace(p,_,C,M,F,z,H,Y){const se=8*p;return this.int16[se+0]=_,this.int16[se+1]=C,this.int16[se+2]=M,this.int16[se+4]=F,this.int16[se+5]=z,this.int16[se+6]=H,this.int16[se+7]=Y,p}}Sr.prototype.bytesPerElement=16,oa(Sr,"StructArrayLayout3i2i2i16");class Hr extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F){const z=this.length;return this.resize(z+1),this.emplace(z,p,_,C,M,F)}emplace(p,_,C,M,F,z){const H=4*p,Y=8*p;return this.float32[H+0]=_,this.float32[H+1]=C,this.float32[H+2]=M,this.int16[Y+6]=F,this.int16[Y+7]=z,p}}Hr.prototype.bytesPerElement=16,oa(Hr,"StructArrayLayout2f1f2i16");class Ha extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z){const H=this.length;return this.resize(H+1),this.emplace(H,p,_,C,M,F,z)}emplace(p,_,C,M,F,z,H){const Y=20*p,se=5*p;return this.uint8[Y+0]=_,this.uint8[Y+1]=C,this.float32[se+1]=M,this.float32[se+2]=F,this.float32[se+3]=z,this.float32[se+4]=H,p}}Ha.prototype.bytesPerElement=20,oa(Ha,"StructArrayLayout2ub4f20");class $r extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,p,_,C)}emplace(p,_,C,M){const F=3*p;return this.uint16[F+0]=_,this.uint16[F+1]=C,this.uint16[F+2]=M,p}}$r.prototype.bytesPerElement=6,oa($r,"StructArrayLayout3ui6");class Ya extends Jt{_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,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye,nt,it,ut,ot,vt){const kt=this.length;return this.resize(kt+1),this.emplace(kt,p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye,nt,it,ut,ot,vt)}emplace(p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye,nt,it,ut,ot,vt,kt){const ls=30*p,At=15*p,qt=60*p;return this.int16[ls+0]=_,this.int16[ls+1]=C,this.int16[ls+2]=M,this.float32[At+2]=F,this.float32[At+3]=z,this.uint16[ls+8]=H,this.uint16[ls+9]=Y,this.uint32[At+5]=se,this.uint32[At+6]=me,this.uint32[At+7]=xe,this.uint16[ls+16]=_e,this.uint16[ls+17]=Te,this.uint16[ls+18]=De,this.float32[At+10]=Ue,this.float32[At+11]=Ye,this.uint8[qt+48]=nt,this.uint8[qt+49]=it,this.uint8[qt+50]=ut,this.uint32[At+13]=ot,this.int16[ls+28]=vt,this.uint8[qt+58]=kt,p}}Ya.prototype.bytesPerElement=60,oa(Ya,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class Oi extends Jt{_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,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye,nt,it,ut,ot,vt,kt,ls,At,qt,ts,ns,Ps,Ws,mn,ln,_n,Un){const Cs=this.length;return this.resize(Cs+1),this.emplace(Cs,p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye,nt,it,ut,ot,vt,kt,ls,At,qt,ts,ns,Ps,Ws,mn,ln,_n,Un)}emplace(p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye,nt,it,ut,ot,vt,kt,ls,At,qt,ts,ns,Ps,Ws,mn,ln,_n,Un,Cs){const Xs=20*p,rn=40*p,In=80*p;return this.float32[Xs+0]=_,this.float32[Xs+1]=C,this.int16[rn+4]=M,this.int16[rn+5]=F,this.int16[rn+6]=z,this.int16[rn+7]=H,this.int16[rn+8]=Y,this.int16[rn+9]=se,this.int16[rn+10]=me,this.int16[rn+11]=xe,this.int16[rn+12]=_e,this.uint16[rn+13]=Te,this.uint16[rn+14]=De,this.uint16[rn+15]=Ue,this.uint16[rn+16]=Ye,this.uint16[rn+17]=nt,this.uint16[rn+18]=it,this.uint16[rn+19]=ut,this.uint16[rn+20]=ot,this.uint16[rn+21]=vt,this.uint16[rn+22]=kt,this.uint16[rn+23]=ls,this.uint16[rn+24]=At,this.uint16[rn+25]=qt,this.uint16[rn+26]=ts,this.uint16[rn+27]=ns,this.uint32[Xs+14]=Ps,this.float32[Xs+15]=Ws,this.float32[Xs+16]=mn,this.float32[Xs+17]=ln,this.float32[Xs+18]=_n,this.uint8[In+76]=Un,this.uint16[rn+39]=Cs,p}}Oi.prototype.bytesPerElement=80,oa(Oi,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class Do extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z){const H=this.length;return this.resize(H+1),this.emplace(H,p,_,C,M,F,z)}emplace(p,_,C,M,F,z,H){const Y=6*p;return this.float32[Y+0]=_,this.float32[Y+1]=C,this.float32[Y+2]=M,this.float32[Y+3]=F,this.float32[Y+4]=z,this.float32[Y+5]=H,p}}Do.prototype.bytesPerElement=24,oa(Do,"StructArrayLayout6f24");class to extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F){const z=this.length;return this.resize(z+1),this.emplace(z,p,_,C,M,F)}emplace(p,_,C,M,F,z){const H=5*p;return this.float32[H+0]=_,this.float32[H+1]=C,this.float32[H+2]=M,this.float32[H+3]=F,this.float32[H+4]=z,p}}to.prototype.bytesPerElement=20,oa(to,"StructArrayLayout5f20");class ql extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H){const Y=this.length;return this.resize(Y+1),this.emplace(Y,p,_,C,M,F,z,H)}emplace(p,_,C,M,F,z,H,Y){const se=7*p;return this.float32[se+0]=_,this.float32[se+1]=C,this.float32[se+2]=M,this.float32[se+3]=F,this.float32[se+4]=z,this.float32[se+5]=H,this.float32[se+6]=Y,p}}ql.prototype.bytesPerElement=28,oa(ql,"StructArrayLayout7f28");class yu extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H,Y,se,me,xe){const _e=this.length;return this.resize(_e+1),this.emplace(_e,p,_,C,M,F,z,H,Y,se,me,xe)}emplace(p,_,C,M,F,z,H,Y,se,me,xe,_e){const Te=11*p;return this.float32[Te+0]=_,this.float32[Te+1]=C,this.float32[Te+2]=M,this.float32[Te+3]=F,this.float32[Te+4]=z,this.float32[Te+5]=H,this.float32[Te+6]=Y,this.float32[Te+7]=se,this.float32[Te+8]=me,this.float32[Te+9]=xe,this.float32[Te+10]=_e,p}}yu.prototype.bytesPerElement=44,oa(yu,"StructArrayLayout11f44");class Uc extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H,Y,se){const me=this.length;return this.resize(me+1),this.emplace(me,p,_,C,M,F,z,H,Y,se)}emplace(p,_,C,M,F,z,H,Y,se,me){const xe=9*p;return this.float32[xe+0]=_,this.float32[xe+1]=C,this.float32[xe+2]=M,this.float32[xe+3]=F,this.float32[xe+4]=z,this.float32[xe+5]=H,this.float32[xe+6]=Y,this.float32[xe+7]=se,this.float32[xe+8]=me,p}}Uc.prototype.bytesPerElement=36,oa(Uc,"StructArrayLayout9f36");class Ko extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_){const C=this.length;return this.resize(C+1),this.emplace(C,p,_)}emplace(p,_,C){const M=2*p;return this.float32[M+0]=_,this.float32[M+1]=C,p}}Ko.prototype.bytesPerElement=8,oa(Ko,"StructArrayLayout2f8");class so extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,C,M){const F=this.length;return this.resize(F+1),this.emplace(F,p,_,C,M)}emplace(p,_,C,M,F){const z=6*p;return this.uint32[3*p+0]=_,this.uint16[z+2]=C,this.uint16[z+3]=M,this.uint16[z+4]=F,p}}so.prototype.bytesPerElement=12,oa(so,"StructArrayLayout1ul3ui12");class _d extends Jt{_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}}_d.prototype.bytesPerElement=2,oa(_d,"StructArrayLayout1ui2");class Gh extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int8=new Int8Array(this.arrayBuffer)}emplaceBack(p,_,C,M){const F=this.length;return this.resize(F+1),this.emplace(F,p,_,C,M)}emplace(p,_,C,M,F){const z=4*p;return this.int8[z+0]=_,this.int8[z+1]=C,this.int8[z+2]=M,this.int8[z+3]=F,p}}Gh.prototype.bytesPerElement=4,oa(Gh,"StructArrayLayout4b4");class _h extends Jt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye){const nt=this.length;return this.resize(nt+1),this.emplace(nt,p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye)}emplace(p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye,nt){const it=16*p;return this.float32[it+0]=_,this.float32[it+1]=C,this.float32[it+2]=M,this.float32[it+3]=F,this.float32[it+4]=z,this.float32[it+5]=H,this.float32[it+6]=Y,this.float32[it+7]=se,this.float32[it+8]=me,this.float32[it+9]=xe,this.float32[it+10]=_e,this.float32[it+11]=Te,this.float32[it+12]=De,this.float32[it+13]=Ue,this.float32[it+14]=Ye,this.float32[it+15]=nt,p}}_h.prototype.bytesPerElement=64,oa(_h,"StructArrayLayout16f64");class Vl extends Jt{_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}}Vl.prototype.bytesPerElement=2,oa(Vl,"StructArrayLayout1i2");class mm extends Jt{_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}}mm.prototype.bytesPerElement=1,oa(mm,"StructArrayLayout1ub1");class yc 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]}}yc.prototype.size=40;class dc extends Gr{get(p){return new yc(this,p)}}oa(dc,"CollisionBoxArray");class Dh 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}}Dh.prototype.size=60;class Wh extends Ya{get(p){return new Dh(this,p)}}oa(Wh,"PlacedSymbolArray");class Pd 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]}}Pd.prototype.size=80;class vc extends Oi{get(p){return new Pd(this,p)}}oa(vc,"SymbolInstanceArray");class Kh extends Bs{getoffsetX(p){return this.float32[1*p+0]}}oa(Kh,"GlyphOffsetArray");class cg extends Gs{getx(p){return this.int16[2*p+0]}gety(p){return this.int16[2*p+1]}}oa(cg,"SymbolLineVertexArray");class H_ 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]}}H_.prototype.size=12;class Jy extends so{get(p){return new H_(this,p)}}oa(Jy,"FeatureIndexArray");class nj extends si{geta_centroid_pos0(p){return this.uint16[2*p+0]}geta_centroid_pos1(p){return this.uint16[2*p+1]}}oa(nj,"FillExtrusionCentroidArray");class vu 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]}}vu.prototype.size=6;class id extends Ls{get(p){return new vu(this,p)}}oa(id,"FillExtrusionWallArray");const Rc=Lt([{name:"a_pos",components:2,type:"Int16"}],4),Yh=Lt([{name:"a_road_z_offset",components:1,type:"Float32"}],4),sx=Lt([{name:"a_pos",components:2,type:"Int16"},{name:"a_height",components:1,type:"Float32"}],4),Ku=Lt([{name:"a_pos_normal_3",components:3,type:"Int16"}],4);class Li{constructor(p=[]){this.segments=p}_prepareSegment(p,_,C,M,F){let z=this.segments.at(-1);return p>Li.MAX_VERTEX_ARRAY_LENGTH&&Yo(`Max vertices per segment is ${Li.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${p}`),(!z||z.vertexLength+p>Li.MAX_VERTEX_ARRAY_LENGTH||z.sortKey!==M||F!==void 0&&z&&z.batchIndex!==void 0&&z.batchIndex!==F)&&(z={vertexOffset:_,primitiveOffset:C,vertexLength:0,primitiveLength:0},M!==void 0&&(z.sortKey=M),F!==void 0&&(z.batchIndex=F),this.segments.push(z)),z}prepareSegment(p,_,C,M,F){return this._prepareSegment(p,_.length,C.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,_,C,M){return new Li([{vertexOffset:p,primitiveOffset:_,vertexLength:C,primitiveLength:M,vaos:{},sortKey:0}])}}function wm(N,p){return 256*(N=ea(Math.floor(N),0,255))+ea(Math.floor(p),0,255)}Li.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,oa(Li,"SegmentVector");const dg=Lt([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),rj=Lt([{name:"a_pattern_b",components:4,type:"Uint16"}]),aj=Lt([{name:"a_dash",components:4,type:"Uint16"}]);class Ob{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(p,_,C,M){this.ids.push(zb(p)),this.positions.push(_,C,M)}eachPosition(p,_){const C=zb(p);let M=0,F=this.ids.length-1;for(;M>1;this.ids[z]>=C?F=z:M=z+1}for(;this.ids[M]===C;)_(this.positions[3*M],this.positions[3*M+1],this.positions[3*M+2]),M++}static serialize(p,_){const C=new Float64Array(p.ids),M=new Uint32Array(p.positions);return Y2(C,M,0,C.length-1),_&&(_.add(C.buffer),_.add(M.buffer)),{ids:C,positions:M}}static deserialize(p){const _=new Ob;let C;_.ids=p.ids,_.positions=p.positions;for(const M of _.ids)M!==C&&_.uniqueIds.push(M),C=M;return _.indexed=!0,_}}function zb(N){const p=+N;return Number.isSafeInteger(p)?p:dd(String(N))}function Y2(N,p,_,C){for(;_>1];let F=_-1,z=C+1;for(;;){do F++;while(N[F]M);if(F>=z)break;Bb(N,F,z),Bb(p,3*F,3*z),Bb(p,3*F+1,3*z+1),Bb(p,3*F+2,3*z+2)}z-_`u_${F}`),this.type=C,this.context=M}setUniform(p,_,C,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 G6(p):new lo(p)}}class _Y{constructor(p,_){this.uniformNames=_.map(C=>`u_${C}`),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,_,C,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 bY(p):new lo(p)}}class D3{constructor(p,_,C,M){this.expression=p,this.type=C,this.maxValue=0,this.paintVertexAttributes=_.map(F=>({name:`a_${F}`,type:"Float32",components:C==="color"?2:1,offset:0})),this.paintVertexArray=new M}populatePaintArray(p,_,C,M,F,z,H,Y){const se=this.paintVertexArray.length,me=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new Hn(0,{brightness:z,worldview:Y}),_,{},F,M,H):this.expression.kind==="constant"&&this.expression.value,xe=L9(this.lutExpression,_,{},M,F,z,H,Y);this.paintVertexArray.resize(p),this._setPaintValue(se,p,me,xe?null:this.context.lut)}updatePaintArray(p,_,C,M,F,z,H,Y){const se=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:H,worldview:Y},C,M,void 0,F):this.expression.kind==="constant"&&this.expression.value,me=L9(this.lutExpression,C,M,F,void 0,H,void 0,Y);this._setPaintValue(p,_,se,me?null:this.context.lut)}_setPaintValue(p,_,C,M){if(this.type==="color"){const F=I9(C.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,C);this.maxValue=Math.max(this.maxValue,Math.abs(C))}}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 UC{constructor(p,_,C,M,F,z){this.expression=p,this.uniformNames=_.map(H=>`u_${H}_t`),this.type=C,this.useIntegerZoom=M,this.context=F,this.maxValue=0,this.paintVertexAttributes=_.map(H=>({name:`a_${H}`,type:"Float32",components:C==="color"?4:2,offset:0})),this.paintVertexArray=new z}populatePaintArray(p,_,C,M,F,z,H,Y){const se=this.expression.evaluate(new Hn(this.context.zoom,{brightness:z,worldview:Y}),_,{},F,M,H),me=this.expression.evaluate(new Hn(this.context.zoom+1,{brightness:z,worldview:Y}),_,{},F,M,H),xe=L9(this.lutExpression,_,{},M,F,z,H,Y),_e=this.paintVertexArray.length;this.paintVertexArray.resize(p),this._setPaintValue(_e,p,se,me,xe?null:this.context.lut)}updatePaintArray(p,_,C,M,F,z,H,Y){const se=this.expression.evaluate({zoom:this.context.zoom,brightness:H,worldview:Y},C,M,void 0,F),me=this.expression.evaluate({zoom:this.context.zoom+1,brightness:H,worldview:Y},C,M,void 0,F),xe=L9(this.lutExpression,C,M,F,void 0,H,void 0,Y);this._setPaintValue(p,_,se,me,xe?null:this.context.lut)}_setPaintValue(p,_,C,M,F){if(this.type==="color"){const z=I9(C.toPremultipliedRenderColor(F)),H=I9(M.toPremultipliedRenderColor(F));for(let Y=p;Y<_;Y++)this.paintVertexArray.emplace(Y,z[0],z[1],H[0],H[1])}else{for(let z=p;z<_;z++)this.paintVertexArray.emplace(z,C,M);this.maxValue=Math.max(this.maxValue,Math.abs(C),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,_,C,M,F){const z=this.useIntegerZoom?Math.floor(C.zoom):C.zoom,H=ea(this.expression.interpolationFactor(z,this.context.zoom,this.context.zoom+1),0,1);_.set(p,F,H)}getBinding(p,_){return new lo(p)}}class qC{constructor(p,_,C,M,F){this.expression=p,this.layerId=F,this.paintVertexAttributes=(C==="array"?aj:dg).members;for(let z=0;z<_.length;++z);this.paintVertexArray=new M,this.paintTransitionVertexArray=new kn}populatePaintArray(p,_,C,M){const F=this.paintVertexArray.length;this.paintVertexArray.resize(p),this._setPaintValues(F,p,_.patterns&&_.patterns[this.layerId],C)}updatePaintArray(p,_,C,M,F,z,H){this._setPaintValues(p,_,C.patterns&&C.patterns[this.layerId],z)}_setPaintValues(p,_,C,M){if(!M||!C)return;const F=M[C[0]],z=M[C[1]];if(F){if(F){const{tl:H,br:Y,pixelRatio:se}=F;for(let me=p;me<_;me++)this.paintVertexArray.emplace(me,H[0],H[1],Y[0],Y[1],se)}if(z){this.paintTransitionVertexArray.resize(this.paintVertexArray.length);const{tl:H,br:Y}=z;for(let se=p;se<_;se++)this.paintTransitionVertexArray.emplace(se,H[0],H[1],Y[0],Y[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,rj.members,_))}destroy(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy(),this.paintTransitionVertexBuffer&&this.paintTransitionVertexBuffer.destroy()}}class K6{constructor(p,_,C=()=>!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")||!C(z)||!(H instanceof bh&&Yy(H.property.specification)))continue;const Y=Mus(z,p.type),se=H.value,me=H.property.specification.type,xe=!!H.property.useIntegerZoom,_e=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||_e){const Ue=Yct(z,me,"source");this.binders[z]=_e?new qC(se,Y,me,Ue,p.id):new D3(se,Y,me,Ue),M.push(`/a_${z}`)}else{const Ue=Yct(z,me,"composite");this.binders[z]=new UC(se,Y,me,xe,_,Ue),M.push(`/z_${z}`)}else this.binders[z]=_e?new _Y(se.value,Y):new Noe(se.value,Y,me,_),M.push(`/u_${z}`);Te&&(this.binders[z].lutExpression=Te.value)}this.cacheKey=M.sort().join("")}updateExpressions(p){const _=p;for(const C in this.binders){const M=this.binders[C];if(M instanceof D3||M instanceof UC||M instanceof qC){const F=_.paint.get(C);M.expression=F.value}}}getMaxValue(p){const _=this.binders[p];return _ instanceof D3||_ instanceof UC?_.maxValue:0}populatePaintArrays(p,_,C,M,F,z,H,Y){for(const se in this.binders){const me=this.binders[se];me.context=this.context,(me instanceof D3||me instanceof UC||me instanceof qC)&&me.populatePaintArray(p,_,C,M,F,z,H,Y)}}setConstantPatternPositions(p,_){for(const C in this.binders){const M=this.binders[C];M instanceof _Y&&M.setConstantPatternPositions(p,_)}}getPatternTransitionVertexBuffer(p){const _=this.binders[p];return _ instanceof qC?_.paintTransitionVertexBuffer:null}updatePaintArrays(p,_,C,M,F,z,H,Y,se,me){let xe=!1;const _e=Object.keys(p),Te=_e.length!==0&&!Y,De=Te?_e:_.uniqueIds;this.context.lut=F.lut;for(const Ue in this.binders){const Ye=this.binders[Ue];if(Ye.context=this.context,(Ye instanceof D3||Ye instanceof UC||Ye instanceof qC)&&Ye.expression&&Ye.expression.kind&&Ye.expression.kind!=="constant"&&(Ye.expression.isStateDependent===!0||Ye.expression.isLightConstant===!1)){const nt=F.paint.get(Ue);Ye.expression=nt.value;for(const it of De){const ut=p[it.toString()];_.eachPosition(it,(ot,vt,kt)=>{const ls=M.feature(ot);Ye.updatePaintArray(vt,kt,ls,ut,z,H,se,me)})}if(!Te)for(const it of C.uniqueIds){const ut=p[it.toString()];C.eachPosition(it,(ot,vt,kt)=>{const ls=M.feature(ot);Ye.updatePaintArray(vt,kt,ls,ut,z,H,se,me)})}xe=!0}}return xe}defines(){const p=[];for(const _ in this.binders){const C=this.binders[_];(C instanceof Noe||C instanceof _Y)&&p.push(...C.uniformNames.map(M=>`#define HAS_UNIFORM_${M}`))}return p}getPaintVertexBuffers(){return this._buffers}getUniforms(p){const _=[];for(const C in this.binders){const M=this.binders[C];if(M instanceof Noe||M instanceof _Y||M instanceof UC)for(const F of M.uniformNames)_.push({name:F,property:C,binding:M.getBinding(p,F)})}return _}setUniforms(p,_,C,M,F){for(const{name:z,property:H,binding:Y}of C)this.binders[H].setUniform(p,Y,F,M.get(H),z)}updatePaintBuffers(){this._buffers=[];for(const p in this.binders){const _=this.binders[p];(_ instanceof D3||_ instanceof UC||_ instanceof qC)&&_.paintVertexBuffer&&this._buffers.push(_.paintVertexBuffer),_ instanceof qC&&_.paintTransitionVertexBuffer&&this._buffers.push(_.paintTransitionVertexBuffer)}}upload(p){for(const _ in this.binders){const C=this.binders[_];(C instanceof D3||C instanceof UC||C instanceof qC)&&C.upload(p)}this.updatePaintBuffers()}destroy(){for(const p in this.binders){const _=this.binders[p];(_ instanceof D3||_ instanceof UC||_ instanceof qC)&&_.destroy()}}}class Hk{constructor(p,_,C=()=>!0){this.programConfigurations={};for(const M of p)this.programConfigurations[M.id]=new K6(M,_,C);this.needsUpload=!1,this._featureMap=new Ob,this._featureMapWithoutIds=new Ob,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(p,_,C,M,F,z,H,Y,se){for(const me in this.programConfigurations)this.programConfigurations[me].populatePaintArrays(p,_,M,F,z,H,Y,se);_.id!==void 0?this._featureMap.add(_.id,C,this._bufferOffset,p):(this._featureMapWithoutIds.add(this._idlessCounter,C,this._bufferOffset,p),this._idlessCounter+=1),this._bufferOffset=p,this.needsUpload=!0}updatePaintArrays(p,_,C,M,F,z,H,Y){for(const se of C)this.needsUpload=this.programConfigurations[se.id].updatePaintArrays(p,this._featureMap,this._featureMapWithoutIds,_,se,M,F,z,H||0,Y)||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 C of p){const M=this.programConfigurations[C.id];M&&(M.updateExpressions(C),_.add(C.id))}for(const C in this.programConfigurations)_.has(C)||delete this.programConfigurations[C]}}const Tus={"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 Mus(N,p){return Tus[N]||[N.replace(`${p}-`,"").replace(/-/g,"_")]}const Pus={"line-pattern":{source:Mr,composite:Mr},"fill-pattern":{source:Mr,composite:Mr},"fill-extrusion-pattern":{source:Mr,composite:Mr},"line-dasharray":{source:kn,composite:kn}},Ius={color:{source:Ko,composite:qr},number:{source:Bs,composite:Ko}};function Yct(N,p,_){const C=Pus[N];return C&&C[_]||Ius[p][_]}oa(Noe,"ConstantBinder"),oa(_Y,"PatternConstantBinder"),oa(D3,"SourceExpressionBinder",{omit:["expression"]}),oa(qC,"PatternCompositeBinder",{omit:["expression"]}),oa(UC,"CompositeExpressionBinder",{omit:["expression"]}),oa(K6,"ProgramConfiguration",{omit:["_buffers"]}),oa(Hk,"ProgramConfigurationSet");class OFe{constructor(p,_,C){this.layoutVertexArray=new Gs,this.indexArray=new $r,this.lineIndexArray=new si,this.triangleSegments=new Li,this.lineSegments=new Li,this.programConfigurations=new Hk(p,{zoom:_,lut:C}),this.uploaded=!1}update(p,_,C,M,F,z,H,Y){this.programConfigurations.updatePaintArrays(p,_,F,C,M,z,H,Y)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(p){this.uploaded||(this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,Rc.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,_,C,M,F,z,H){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,p,_,C,M,F,z,void 0,H)}}oa(OFe,"FillBufferData");class zFe{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 OFe(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,_,C,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,C,M){this.hasPattern=V6("fill",this.layers,this.pixelRatio,_);const F=this.layers[0].layout.get("fill-sort-key"),z=[];for(const{feature:H,id:Y,index:se,sourceLayerIndex:me}of p){const xe=this.layers[0]._featureFilter.needGeometry,_e=_t(H,xe);if(!this.layers[0]._featureFilter.filter(new Hn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),_e,C))continue;const Te=F?F.evaluate(_e,{},C,_.availableImages):void 0,De={id:Y,properties:H.properties,type:H.type,sourceLayerIndex:me,index:se,geometry:xe?_e.geometry:dt(H,C,M),patterns:{},sortKey:Te};z.push(De)}F&&z.sort((H,Y)=>H.sortKey-Y.sortKey);for(const H of z){const{geometry:Y,index:se,sourceLayerIndex:me}=H;if(this.hasPattern){const xe=xY("fill",this.layers,H,this.zoom,this.pixelRatio,_);this.patternFeatures.push(xe)}else this.addFeature(H,Y,se,C,{},_.availableImages,_.brightness,_.elevationFeatures);_.featureIndex.insert(p[se].feature,Y,se,me,this.index)}!this.hasPattern&&this.hdExt&&this.hdExt.buildFrcSegments(this)}update(p,_,C,M,F,z,H){this.bufferData.update(p,_,C,M,F,z,H,this.worldview),this.hdExt&&this.hdExt.update(p,_,C,M,F,z,H,this.worldview)}updateExpressions(p){this.bufferData.programConfigurations.updateExpressions(p),this.hdExt&&this.hdExt.updateExpressions(p)}addFeatures(p,_,C,M,F,z){for(const H of this.patternFeatures)this.addFeature(H,H.geometry,H.index,_,C,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,_,C,M,F,z=[],H,Y){const se=this.hdExt?this.hdExt.trackFeatureFrc(p.properties):null,me=this.bufferData.indexArray.length,xe=Pa(_,500);this.hdExt!=null&&this.hdExt.handleFeature(p,xe,C,M,Y,this)||this.addGeometry(xe,this.bufferData),this.bufferData.populatePaintArrays(p,C,F,z,M,H,this.worldview),this.hdExt&&this.hdExt.populatePaintArrays(p,C,F,z,M,H,this.worldview),this.hdExt&&this.hdExt.recordFeatureRange(this,me,this.bufferData.indexArray.length,se)}addGeometry(p,_,C,M){let F=Number.POSITIVE_INFINITY,z=Number.NEGATIVE_INFINITY,H=null;C&&(H=C.elevationSampler.constantElevation(C.elevation,C.bias),H!=null&&(F=H,z=H));const Y=C?_:null,se=(me,xe,_e)=>{if(C!=null)if(xe.push(me),H!=null)Y.elevatedLayoutVertexArray.emplaceBack(H),_e.push(H);else{const Te=C.elevationSampler.pointElevation(me,C.elevation,C.bias);Y.elevatedLayoutVertexArray.emplaceBack(Te),_e.push(Te),F=Math.min(F,Te),z=Math.max(z,Te)}};for(const me of p){let xe=0;for(const vt of me)xe+=vt.length;const _e=_.triangleSegments.prepareSegment(xe,_.layoutVertexArray,_.indexArray),Te=_e.vertexLength,De=[],Ue=[],Ye=[],nt=[],it=[],ut=_.layoutVertexArray.length;for(const vt of me){if(vt.length===0)continue;vt!==me[0]&&Ue.push(De.length/2);const kt=_.lineSegments.prepareSegment(vt.length,_.layoutVertexArray,_.lineIndexArray),ls=kt.vertexLength;C&&it.push(_.layoutVertexArray.length-ut),se(vt[0],Ye,nt),_.layoutVertexArray.emplaceBack(vt[0].x,vt[0].y),_.lineIndexArray.emplaceBack(ls+vt.length-1,ls),De.push(vt[0].x),De.push(vt[0].y);for(let At=1;At0&&C&&M){const vt=C.elevation.isTunnel(),kt=C.elevation.safeArea,ls=M.addVertices(Ye,nt);M.addTriangles(ot,ls,vt);const At=it.length;if(At>0){for(let qt=0;qt>3,z===0)continue}if(z--,F===1)H+=p.readSVarint(),Y+=p.readSVarint(),M&&C.push(M),M=[new xs(H,Y)];else if(F===2)H+=p.readSVarint(),Y+=p.readSVarint(),M&&M.push(new xs(H,Y));else{if(F!==7)throw new Error(`unknown command ${F}`);M&&M.push(M[0].clone())}}return M&&C.push(M),C}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 C=1,M=0,F=0,z=0,H=1/0,Y=-1/0,se=1/0,me=-1/0;for(;p.pos<_;){if(M<=0){const xe=p.readVarint();if(C=7&xe,M=xe>>3,M===0)continue}if(M--,C===1||C===2)F+=p.readSVarint(),z+=p.readSVarint(),FY&&(Y=F),zme&&(me=z);else if(C!==7)throw new Error(`unknown command ${C}`)}return[H,se,Y,me]}toGeoJSON(p,_,C){const M=this.extent*Math.pow(2,C),F=this.extent*p,z=this.extent*_,H=this.loadGeometry();function Y(_e){return[360*(_e.x+F)/M-180,360/Math.PI*Math.atan(Math.exp((1-2*(_e.y+z)/M)*Math.PI))-90]}function se(_e){return _e.map(Y)}let me;if(this.type===1){const _e=[];for(const De of H)_e.push(De[0]);const Te=se(_e);me=_e.length===1?{type:"Point",coordinates:Te[0]}:{type:"MultiPoint",coordinates:Te}}else if(this.type===2){const _e=H.map(se);me=_e.length===1?{type:"LineString",coordinates:_e[0]}:{type:"MultiLineString",coordinates:_e}}else{if(this.type!==3)throw new Error("unknown feature type");{const _e=function(De){const Ue=De.length;if(Ue<=1)return[De];const Ye=[];let nt,it;for(let ut=0;ut=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 eM(this._pbf,_,this.extent,this._keys,this._values)}}function Hus(N){let p=null;const _=N.readVarint()+N.pos;for(;N.pos<_;){const C=N.readVarint();p=C===10?N.readString():C===21?N.readFloat():C===25?N.readDouble():C===32?N.readVarint(!0):C===40?N.readVarint():C===48?N.readSVarint():C===56?N.readBoolean():(N.skip(C),null)}if(p==null)throw new Error("unknown feature value");return p}class BFe{constructor(p,_=p.length){const C=Object.create(null);for(;p.pos<_;){const M=p.readVarint();if(M===26){const F=new Vus(p,p.readVarint()+p.pos);F.length&&(C[F.name]=F)}else p.skip(M)}this.layers=C}}function $Fe(N,p){for(let _=0;_1){if(qFe(N,p))return!0;for(let C=0;C1?_:_.sub(p)._mult(M)._add(p))}function Xct(N,p){let _,C,M,F=!1;for(let z=0;zp.y!=M.y>p.y&&p.x<(M.x-C.x)*(p.y-C.y)/(M.y-C.y)+C.x&&(F=!F)}return F}function tM(N,p){let _=!1;for(let C=0,M=N.length-1;Cp.y!=z.y>p.y&&p.x<(z.x-F.x)*(p.y-F.y)/(z.y-F.y)+F.x&&(_=!_)}return _}function GFe(N,p,_,C,M){for(const z of N)if(p<=z.x&&_<=z.y&&C>=z.x&&M>=z.y)return!0;const F=[new xs(p,_),new xs(p,M),new xs(C,M),new xs(C,_)];if(N.length>2){for(const z of F)if(tM(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=Mc(N,p,_[0]);return F!==Mc(N,p,_[1])||F!==Mc(N,p,_[2])||F!==Mc(N,p,_[3])}function D9(N,p,_,C,M,F){let z=p.y-N.y,H=N.x-p.x;if(F=F||0){const Y=z*z+H*H;if(Y===0)return!0;const se=Math.sqrt(Y);z/=se,H/=se}return!((_.x-N.x)*z+(_.y-N.y)*H-F<0||(C.x-N.x)*z+(C.y-N.y)*H-F<0||(M.x-N.x)*z+(M.y-N.y)*H-F<0)}function WFe(N,p,_,C,M,F,z){return!(D9(N,p,C,M,F,z)||D9(p,_,C,M,F,z)||D9(_,N,C,M,F,z)||D9(C,M,N,p,_,z)||D9(M,F,N,p,_,z)||D9(F,C,N,p,_,z))}class Y6 extends xs{constructor(p,_,C){super(p,_),this.z=C}}class Qct extends Y6{constructor(p,_,C,M){super(p,_,C),this.w=M}}function Jct(N,p,_,C){const M=_==="x"?"y":"x",F=(C-N[_])/(p[_]-N[_]);N[M]=Math.round(N[M]+(p[M]-N[M])*F),N[_]=C,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 edt(N,p,_,C){const M=_,F=C;for(const z of["x","y"]){let H=N,Y=p;H[z]>=Y[z]&&(H=p,Y=N),H[z]M&&Jct(H,Y,z,M),H[z]F&&Jct(Y,H,z,F)}}function KFe(N,p,_,C,M,F){const z=[];for(let H=0;H=C&&De.x>=C||(Te.x>=C?Te=new xs(C,Te.y+(C-Te.x)/(De.x-Te.x)*(De.y-Te.y))._round():De.x>=C&&(De=new xs(C,Te.y+(C-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+tdt(nt,it,Te)*Ue,max:1},parentIndex:H,prevPoint:nt,nextPoint:it})),se.push(De),F&&(F.at(-1).progress.max=Ye+tdt(nt,it,De)*Ue,F.at(-1).nextPoint=it)))))}if(F&&xe>0)for(let _e=me;_ese.t-me.t);let z=0,H=0,Y=[];for(C.push(Y);z!==N.length;){if(H===F.length){for(;z!==N.length;)Y.length!==0&&Y.at(-1).equals(N[z])||Y.push(N[z]),z++;break}F[H].t<=z?(Y.length!==0&&Y.at(-1).equals(F[H].point)||Y.push(F[H].point),Math.trunc(F[H].t),H++):(Y.length!==0&&Y.at(-1).equals(N[z])||Y.push(N[z]),z++)}}function tdt(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 sdt(N,{width:p,height:_},C,M){if(M){if(M instanceof Uint8ClampedArray)M=new Uint8Array(M.buffer);else if(M.length!==p*_*C)throw new RangeError("mismatched image size")}else M=new Uint8Array(p*_*C);return N.width=p,N.height=_,N.data=M,N}function ndt(N,p,_){const{width:C,height:M}=p;C===N.width&&M===N.height||(YFe(N,p,{x:0,y:0},{x:0,y:0},{width:Math.min(N.width,C),height:Math.min(N.height,M)},_,null),N.width=C,N.height=M,N.data=p.data)}function YFe(N,p,_,C,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||C.x>p.width-M.width||C.y>p.height-M.height)throw new RangeError("out of range destination coordinates for image copy");const Y=N.data,se=p.data,me=F===4&&H;for(let xe=0;xe1&&(Y=p[++H]);const me=Math.abs(se-Y.left),xe=Math.abs(se-Y.right),_e=Math.min(me,xe);let Te;const De=F/C*(M+1);if(Y.isDash){const Ue=M-Math.abs(De);Te=Math.sqrt(_e*_e+Ue*Ue)}else Te=M-Math.sqrt(_e*_e+De*De);this.image.data[z+se]=Math.max(0,Math.min(255,Te+128))}}}addRegularDash(p,_){for(let Y=p.length-1;Y>=0;--Y){const se=p[Y],me=p[Y+1];se.zeroLength?p.splice(Y,1):me&&me.isDash===se.isDash&&(me.left=se.left,p.splice(Y,1))}const C=p[0],M=p.at(-1);C.isDash===M.isDash&&(C.left=M.left-this.width,M.right=C.right+this.width);const F=this.width*this.nextRow;let z=0,H=p[z];for(let Y=0;Y1&&(H=p[++z]);const se=Math.abs(Y-H.left),me=Math.abs(Y-H.right),xe=Math.min(se,me);this.image.data[F+Y]=Math.max(0,Math.min(255,(H.isDash?xe:-xe)+_+128))}}addDash(p,_){const C=this.getKey(p,_);if(this.positions[C])return this.positions[C];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 me=Math.round(se/this.width*4095);this.nextRow+=z;const xe=Math.floor(H),_e={tl:[Y,F|me<<4],br:[xe,Math.round(65535*(H-xe))]};return this.positions[C]=_e,_e}}oa(adt,"LineAtlas");const F3="3d_elevation_id",idt="level",Xus=eM.types,Qus=Math.cos(Math.PI/180*37.5),Jus=Math.cos(Math.PI/180*5);class ZFe{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 zn,this.layoutVertexArray2=new Dn,this.patternVertexArray=new Dn,this.indexArray=new $r,this.programConfigurations=new Hk(p.layers,{zoom:p.zoom,lut:p.lut}),this.segments=new Li,this.sourceLayerName=p.sourceLayerName||"",this.maxLineLength=0,this.zOffsetVertexArray=new qr,this.elevationIdColVertexArray=new Dn,this.elevationGroundScaleVertexArray=new Bs,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,_,C,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,C,M){this.showElevationIdDebug=_.showElevationIdDebug,this.terrainEnabled=_.terrainEnabled,this.hasPattern=V6("line",this.layers,this.pixelRatio,_);const F=this.layers[0].layout.get("line-sort-key");this.tileToMeter=K(C);const z=this.layers[0].layout.get("line-elevation-reference");if(z==="hd-road-markup")this.elevationType="road";else{const _e=this.layers[0].layout.get("line-z-offset"),Te=_e.isConstant()&&!_e.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 Y=[];for(const{feature:_e,id:Te,index:De,sourceLayerIndex:Ue}of p){const Ye=this.layers[0]._featureFilter.needGeometry,nt=_t(_e,Ye);if(!this.layers[0]._featureFilter.filter(new Hn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),nt,C))continue;const it=F?F.evaluate(nt,{},C):void 0,ut={id:Te,properties:_e.properties,type:_e.type,sourceLayerIndex:Ue,index:De,geometry:Ye?nt.geometry:dt(_e,C,M),patterns:{},sortKey:it};Y.push(ut)}F&&Y.sort((_e,Te)=>_e.sortKey-Te.sortKey);const{lineAtlas:se,featureIndex:me}=_,xe=this.addConstantDashes(se);for(const _e of Y){const{geometry:Te,index:De,sourceLayerIndex:Ue}=_e;if(xe&&this.addFeatureDashes(_e,se),this.hasPattern){const Ye=xY("line",this.layers,_e,this.zoom,this.pixelRatio,_);this.patternFeatures.push(Ye)}else this.addFeature(_e,Te,De,C,se.positions,_.availableImages,_.brightness,_.elevationFeatures,_.elevationParams,_.crossSourceElevationEnabled);me.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 C of this.layers){const M=C.paint.get("line-dasharray").value,F=C.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 C=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,Y;if(F.kind==="constant"){if(H=F.value,!H)continue}else H=F.evaluate({zoom:C},p);Y=z.kind==="constant"?z.value:z.evaluate({zoom:C},p),_.addDash(H,Y),p.patterns[M.id]=[_.getKey(H,Y)]}}update(p,_,C,M,F,z,H,Y,se){this.programConfigurations.updatePaintArrays(p,_,F,C,M,z,H,se)}updateExpressions(p){this.programConfigurations.updateExpressions(p)}addFeatures(p,_,C,M,F,z){for(const H of this.patternFeatures)this.addFeature(H,H.geometry,H.index,_,C,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,Bus)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=p.createVertexBuffer(this.patternVertexArray,Uus)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=p.createVertexBuffer(this.zOffsetVertexArray,Rus.members,!0)),!this.elevationIdColVertexBuffer&&this.elevationIdColVertexArray.length>0&&(this.elevationIdColVertexBuffer=p.createVertexBuffer(this.elevationIdColVertexArray,Dus.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=p.createVertexBuffer(this.elevationGroundScaleVertexArray,Fus.members,!0)),this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,Ous),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 C,M;if(_&&_>0?(C=`mapbox_clip_start_${_}`,M=`mapbox_clip_end_${_}`):(C="mapbox_clip_start",M="mapbox_clip_end"),p.properties&&Object.hasOwn(p.properties,C)&&Object.hasOwn(p.properties,M))return{start:+p.properties[C],end:+p.properties[M]}}addFeature(p,_,C,M,F,z,H,Y,se,me){const xe=this.layers[0].layout,_e=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"),nt=xe.get("line-round-limit");this.lineClips=this.lineFeatureClips(p),this.lineFeature=p;const it=!(!p.properties||!Object.hasOwn(p.properties,"mapbox_line_metrics"))&&p.properties.mapbox_line_metrics;this.zOffsetValue=xe.get("line-z-offset").value;const ut=this.layers[0].paint,ot=ut.get("line-width").value;ot.kind!=="constant"&&ot.isLineProgressConstant===!1&&(this.variableWidthValue=ot);const vt=ut.get("line-emissive-strength").value;if(vt.kind!=="constant"&&vt.isLineProgressConstant===!1&&(this.variableEmissiveStrengthValue=vt),this.isSeaLevelReference){const kt=xe.get("line-elevation-ground-scale").value;kt.kind==="constant"&&kt.value===0||(this.elevationGroundScaleValue=kt)}if(this.hdExt==null||!this.hdExt.handleFeature(p,_,M,Y,se,!!me,De,Ue,Ye,nt,this))for(let kt=0;kt<_.length;kt++)this.addLine(_[kt],p,M,De,Ue,Ye,nt,void 0,it&&kt>0?kt:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,p,C,F,z,M,H,void 0,this.worldview),this.hdExt&&this.hdExt.recordFeatureRange(this,Te,this.indexArray.length,_e)}fillNonElevatedRoadSegment(p){for(let _=Math.max(p,this.zOffsetVertexArray.length);_0,_e=Y&&Y.progress.max<1;if(this.lineClips){let qt={min:this.lineClips.start,max:this.lineClips.end},ts=1;if(Y){const Ws=this.lineClips.end-this.lineClips.start;qt=function(mn,ln,_n){return{min:Zo(mn.min,ln,_n),max:Zo(mn.max,ln,_n)}}(Y.progress,{min:0,max:1},qt),Ws>0&&(ts=(qt.max-qt.min)/Ws)}const ns=+_.properties.mapbox_clip_feature_len,Ps=+_.properties.mapbox_clip_seg_len;if(Number.isNaN(ns)||Number.isNaN(Ps)){for(let mn=0;mn=2&&p[De-1].equals(p[De-2]);)De--;let Ue=0;for(;Ue0,Xs=this.overscaling<=16?122880/(512*this.overscaling):0;if(ts&&ns==="round"){if(lnz&&(ns="bevel"),ns==="bevel"&&(ln>2&&(ns="flipbevel"),ln2*Xs){const Pn=nt.sub(nt.sub(it)._mult(Xs/rn)._round());this.updateDistance(it,Pn),this.addCurrentVertex(Pn,ot,0,0,Ye,At),it=Pn}this.updateDistance(it,nt),Ws._mult(ln),this.addCurrentVertex(nt,Ws,0,0,Ye,At);const In=nt.dist(ut);if(In>2*Xs){const Pn=nt.add(ut.sub(nt)._mult(Xs/In)._round());this.updateDistance(nt,Pn),this.addCurrentVertex(Pn,vt,0,0,Ye,At),nt=Pn}}else Ws._mult(ln),this.addCurrentVertex(nt,Ws,0,0,Ye,At);else if(ns==="flipbevel"){if(ln>100)Ws=vt.mult(-1);else{const rn=ln*ot.add(vt).mag()/ot.sub(vt).mag();Ws._perp()._mult(rn*(Cs?-1:1))}this.addCurrentVertex(nt,Ws,0,0,Ye,At),this.addCurrentVertex(nt,Ws.mult(-1),0,0,Ye,At)}else if(ns==="bevel"||ns==="fakeround"){const rn=nt.dist(it);let In=1;if(this.elevationType==="offset"&&ns==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&At!=null&&it&&ut){const or=4*Xs;rn1){this.lineSoFar=p.w;const Ue=(_.x-p.x)/xe,Ye=(_.y-p.y)/xe,nt=(_.z-p.z)/xe,it=(_.w-p.w)/xe,ut=_.x-p.x,ot=_.y-p.y,vt=Math.sqrt(ut*ut+ot*ot);if(vt===0)return;const kt=-ot/vt,ls=ut/vt,At=kt,qt=ls,ts=-kt,ns=-ls;for(let Ps=1;Ps=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,me),Y.primitiveLength++),z?this.e2=me:this.e1=me,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 XFe(N,p,_){return N.x_||N.y_}oa(ZFe,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const ehs=Lt([{name:"a_pos",components:2,type:"Int16"}],4),ths=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 koe{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 Gs,this.indexArray=new $r,this.segments=new Li,this.programConfigurations=new Hk(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,_,C,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,C,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:me,index:xe,sourceLayerIndex:_e}of p){const Te=this.layers[0]._featureFilter.needGeometry,De=_t(se,Te);if(!this.layers[0]._featureFilter.filter(new Hn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),De,C))continue;const Ue=H?H.evaluate(De,{},C):void 0,Ye={id:me,properties:se.properties,type:se.type,sourceLayerIndex:_e,index:xe,geometry:Te?De.geometry:dt(se,C,M),patterns:{},sortKey:Ue};z.push(Ye)}H&&z.sort((se,me)=>se.sortKey-me.sortKey);let Y=null;M.projection.name==="globe"&&(this.globeExtVertexArray=new pr,Y=M.projection);for(const se of z){const{geometry:me,index:xe,sourceLayerIndex:_e}=se,Te=p[xe].feature;this.addFeature(se,me,xe,_.availableImages,C,Y,_.brightness,_.elevationFeatures),_.featureIndex.insert(Te,me,xe,_e,this.index)}this.hdExt&&this.hdExt.finalize()}update(p,_,C,M,F,z,H){this.programConfigurations.updatePaintArrays(p,_,F,C,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,ehs.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,_,C,M,F,z,H,Y){this.hdExt&&this.hdExt.beginFeature(p,Y,F);for(const se of _)for(const me of se){const xe=me.x,_e=me.y;if(xe<0||xe>=Pr||_e<0||_e>=Pr)continue;if(z){const Ue=z.projectTilePoint(xe,_e,F),Ye=z.upVector(F,xe,_e);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,_e,-1,-1),this.addCircleVertex(xe,_e,1,-1),this.addCircleVertex(xe,_e,1,1),this.addCircleVertex(xe,_e,-1,1),this.hdExt&&this.hdExt.writeVertexQuad(xe,_e),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,C,{},M,F,H,void 0,this.worldview)}addCircleVertex(p,_,C,M){this.layoutVertexArray.emplaceBack(2*p+(C+1)/2,2*_+(M+1)/2)}addGlobeExtVertex(p,_){this.globeExtVertexArray.emplaceBack(p.x,p.y,p.z,_[0]*16384,_[1]*16384,_[2]*16384)}}oa(koe,"CircleBucket",{omit:["layers"]});const nhs=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),rhs=Lt([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),ahs=Lt([{name:"a_projected_pos",components:4,type:"Float32"}],4);Lt([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const ihs=Lt([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),ohs=Lt([{name:"a_feature_index",components:1,type:"Float32"}],4),lhs=Lt([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),chs=Lt([{name:"a_texb",components:2,type:"Uint16"}]),dhs=Lt([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),uhs=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 odt=Lt([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),hhs=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 ldt=new Float32Array(1),mhs=new Uint32Array(ldt.buffer);function Soe(N){return ldt[0]=N,mhs[0]}const F9=class hU{static getBlockIndices(p){let _=hU._blockIndicesTemplate;if(!_){_=hU._blockIndicesTemplate=new Uint32Array(p);for(let C=0;Cp.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,hU.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 C=this.headerData,M=4*C[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=C[0];for(let Y=0;Y<9;Y++)z&1<this._propsDirtyMax&&(this._propsDirtyMax=H)}rightSizeForTransfer(){const p=this._propsDirtyMax===-1?0:this._propsDirtyMax;p>>_&1?8:4);const F=hU.EVAL_FLAT_OFFSETS[_];this.propertiesData.set(C.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 C=!1;if(this._headerDirty&&(_.bindBuffer(_.UNIFORM_BUFFER,this.headerBuffer),_.bufferSubData(_.UNIFORM_BUFFER,0,this.headerData),this._headerDirty=!1,C=!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,C=!0}this._blockIndicesDirty&&(_.bindBuffer(_.UNIFORM_BUFFER,this.blockIndicesBuffer),_.bufferSubData(_.UNIFORM_BUFFER,0,hU.getBlockIndices(this.propsDwords)),this._blockIndicesDirty=!1,C=!0),C&&_.bindBuffer(_.UNIFORM_BUFFER,null)}bind(p,_){const C=p.gl,M=(z,H,Y)=>{if(!H)return;const se=C.getUniformBlockIndex(_,z);se!==C.INVALID_INDEX&&(C.uniformBlockBinding(_,se,Y),C.bindBufferBase(C.UNIFORM_BUFFER,Y,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)}}};F9.HEADER_DWORDS=16,F9.HEADER_BYTES=64,F9.EVAL_FLAT_OFFSETS=[0,8,16,20,24,28,32,36,40],F9.EVAL_FLAT_TOTAL=48,F9._blockIndicesTemplate=null;let wY=F9;function cdt(N,p,_,C,M,F,z,H){return!!N&&(N.kind==="constant"?N.value==="none":N.evaluate({zoom:0,brightness:F,worldview:H},p,_,M,C,z)==="none")}function ddt(N){if(!(N instanceof bh))return!1;const p=N.value;return(p.kind==="source"||p.kind==="composite")&&p.isStateDependent}oa(wY,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});const jY=["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`]),jm=new Float32Array(wY.EVAL_FLAT_TOTAL),fhs=[0,0],udt=new WeakMap;class QFe{constructor(p,_,C,M,F="",z,H){this.layer=p,this.zoom=_,this.lut=C,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(wY.HEADER_DWORDS),this.updateHeader(),this.isAllConstant=this.header[0]===0;const Y=4*this.header[2];this.maxFeaturesPerBatch=Y===0?Number.MAX_SAFE_INTEGER:Math.floor(this.uboSizeDwords/Y)}updateHeader(){const p=this.layer.paint;let _=0,C=0,M=0,F=0,z=!0;const H=this._floorZoom,Y=jY[+this.isText];for(let se=0;se<9;se++){const me=Y[se],xe=se<2,_e=p.get(me),Te=!(!_e||typeof _e.isConstant!="function"||_e.isConstant()),De=this._appearancesHavePaintProperties(me);if(!Te&&!De){const vt=this._layerUnevaluated(me);vt&&vt.expression&&vt.expression.kind==="camera"&&(M|=1<{if(!se)return;this._computeZoomRange(se,_,this._zoomRangeScratch,0);const me=this._zoomRangeScratch[0],xe=this._zoomRangeScratch[1];C?me===z&&xe===H||(M=!0):(C=!0,z=me,H=xe,F=se)};Y(this._zoomExprOf(this._layerUnevaluated(p)));for(const se of this.layer.getAppearances()||[])se.hasPaintProperty(p)&&Y(this._zoomExprOf(se.getUnevaluatedPaintProperty(p)));return{hasZoom:C,differs:M,representative:F}}evaluateAllProperties(p,_,C,M,F,z,H){const Y={brightness:F,worldview:this.worldview},se={feature:p,featureState:_,canonical:C,availableImages:M,params:new Hn(this.zoom,Y),paramsNext:new Hn(this.zoom+1,Y),formattedSection:z,activeAppearance:H},me=jY[+this.isText];for(let xe=0;xe<9;xe++){const _e=me[xe],Te=xe<2,De=xe===8,Ue=this.zoomDependency[xe],Ye=Ue!==0,nt=Ue===2,it=wY.EVAL_FLAT_OFFSETS[xe],ut=it+(Te||De?4:2);Te?this._evaluateColorValue(_e,xe,Ye,nt,ut,se,it):De?this._evaluateTranslateValue(_e,xe,Ye,nt,ut,se,it):this._evaluateFloatValue(_e,xe,Ye,nt,ut,se,it)}return jm}_resolveProp(p,_,C=!1,M){const F=this.layer.paint,z=F.get(p),H=p,Y=!(!_||!_.hasPaintProperty(H)),se=Y?M&&z&&z.property.overrides&&z.property.overrides.hasOverride(M)?z:_.paintProperties.get(H):F.get(p);if(C||!se||typeof se.isConstant!="function"||!se.isConstant())return se;const me=Y?_.getUnevaluatedPaintProperty(H):this._layerUnevaluated(p);return this._unbakeCamera(se,me)}_unbakeCamera(p,_){const C=_&&_.expression;if(!C||C.kind!=="camera")return p;let M=udt.get(_);return M||(M=new bh(p.property,C,p.parameters,p.iconImageUseTheme),udt.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,_,C){return p.property.evaluate(p.value,_,C.feature,C.featureState,C.canonical,C.availableImages,p.iconImageUseTheme,C.formattedSection)}_evaluateColorValue(p,_,C,M,F,z,H){const Y=this._resolveProp(p,z.activeAppearance,!1,z.formattedSection);if(this._writePropertyZoomRange(_,C,M,Y,F),!Y)return jm[H]=0,jm[H+1]=0,jm[H+2]=0,void(jm[H+3]=1);const se=this._resolveProp(`${p}-use-theme`,z.activeAppearance,!0),me=cdt(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=(Y.isConstant()?Y.constantOr(Ci.transparent):this._evalAt(Y,z.params,z)||Ci.transparent).toNonPremultipliedRenderColor(me);if(jm[H]=wm(255*xe.r,255*xe.g),jm[H+1]=wm(255*xe.b,255*xe.a),C){const _e=(this._evalAt(Y,z.paramsNext,z)||Ci.transparent).toNonPremultipliedRenderColor(me);jm[H+2]=wm(255*_e.r,255*_e.g),jm[H+3]=wm(255*_e.b,255*_e.a)}else jm[H+2]=jm[H],jm[H+3]=jm[H+1]}_computeZoomRange(p,_,C,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 Y of H)if(Y>_&&Y<_+1){F=z=Y-_;break}}else H[0]>_&&H[0]<_+1&&(F=H[0]-_);C[M]=F,C[M+1]=z}_writeZoomRange(p,_){this._computeZoomRange(p&&p.value,this._floorZoom,jm,_)}_writePropertyZoomRange(p,_,C,M,F){C?this._writeZoomRange(M,F):_?(jm[F]=this.sharedZoomRanges[2*p],jm[F+1]=this.sharedZoomRanges[2*p+1]):(jm[F]=0,jm[F+1]=0)}_evaluateFloatValue(p,_,C,M,F,z,H){const Y=p.endsWith("opacity")?1:0,se=this._resolveProp(p,z.activeAppearance);this._writePropertyZoomRange(_,C,M,se,F);const me=(se?se.isConstant()?se.constantOr(Y):this._evalAt(se,z.params,z):Y)??Y;if(jm[H]=me,C){const xe=this._evalAt(se,z.paramsNext,z);jm[H+1]=xe??Y}else jm[H+1]=me}_evaluateTranslateValue(p,_,C,M,F,z,H){const Y=this._resolveProp(p,z.activeAppearance);this._writePropertyZoomRange(_,C,M,Y,F);const se=!!Y&&typeof Y.isConstant=="function"&&!Y.isConstant(),me=Y?typeof Y.isConstant!="function"?Y:se?this._evalAt(Y,z.params,z):Y.constantOr(fhs):void 0;if(jm[H]=me?me[0]:0,jm[H+1]=me?me[1]:0,C){const xe=se?this._evalAt(Y,z.paramsNext,z):me;jm[H+2]=xe?xe[0]:0,jm[H+3]=xe?xe[1]:0}else jm[H+2]=jm[H],jm[H+3]=jm[H+1]}_appearancesHavePaintProperties(p){return this.layer.getAppearances().some(_=>_.hasPaintProperty(p))}hasStateDependentPaint(p){const _=p.paint,C=jY[+this.isText];for(const M of C)if(ddt(_.get(M)))return!0;for(const M of p.getAppearances()||[])for(const F of C){const z=F;if(M.hasPaintProperty(z)&&ddt(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 C=this.isAllConstant?0:p;let M=Math.floor(C/this.maxFeaturesPerBatch),F=C%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,_,C,M,F,z){if(!_)return;const H=this.allFeatureVtIndices[p],Y=_.feature(H);if(!Y)return;const se=this.allFeatureIds[p],me=se!=null&&F[se]||{},xe={type:Y.type,id:se,properties:Y.properties||{},geometry:[]},_e=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(H):void 0,Te=this.evaluateAllProperties(xe,me,C,M,z,(this.allFormattedSections?this.allFormattedSections[p]:void 0)||void 0,_e);this._writeFeatureBlock(p,Te)}_ensureRangeMaps(){if(!this.featureVertexRangesFromId){this.featureVertexRangesFromId=new Map,this.featureVertexRangesFromVtIndex=new Map;for(let p=0;p{const _e=H[xe],Te=M.get(_e);if(!Te)return[0,0,0,1];const De=M.get(`${_e}-use-theme`),Ue=cdt(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<{C.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()),zr.applyArabicShaping&&(M=zr.applyArabicShaping(M)),M}(C.text,p,_)}),N}const O3={horizontal:1,vertical:2,horizontalOnly:3};function hdt(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 mdt(N,p,_,C){const{horizontalAlign:M,verticalAlign:F}=hdt(C),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 fdt(N,p,_,C,M,F){const z=N.imagePrimary;let H;if(z.content){const Ye=z.content,nt=z.pixelRatio||1;H=[Ye[0]/nt,Ye[1]/nt,z.displaySize[0]-Ye[2]/nt,z.displaySize[1]-Ye[3]/nt]}const Y=p.left*F,se=p.right*F;let me,xe,_e,Te;_==="width"||_==="both"?(Te=M[0]+Y-C[3],xe=M[0]+se+C[1]):(Te=M[0]+(Y+se-z.displaySize[0])/2,xe=Te+z.displaySize[0]);const De=p.top*F,Ue=p.bottom*F;return _==="height"||_==="both"?(me=M[1]+De-C[0],_e=M[1]+Ue+C[2]):(me=M[1]+(De+Ue-z.displaySize[1])/2,_e=me+z.displaySize[1]),{imagePrimary:z,imageSecondary:void 0,top:me,right:xe,bottom:_e,left:Te,collisionPadding:H}}const NY={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};function ghs(N){return N==="︶"||N==="﹈"||N==="︸"||N==="﹄"||N==="﹂"||N==="︾"||N==="︼"||N==="︺"||N==="︘"||N==="﹀"||N==="︐"||N==="︓"||N==="︔"||N==="`"||N===" ̄"||N==="︑"||N==="︒"}function xhs(N){return N==="︵"||N==="﹇"||N==="︷"||N==="﹃"||N==="﹁"||N==="︽"||N==="︻"||N==="︹"||N==="︗"||N==="︿"}const nM=128;function z9(N,p,_,C){const{expression:M}=p;if(M.kind==="constant")return{kind:"constant",layoutSize:M.evaluate(new Hn(N+1,{worldview:_}),void 0,void 0,void 0,C)};if(M.kind==="source")return{kind:"source"};{const{zoomStops:F,interpolationType:z}=M;let H=0;for(;HY*H)}}function gdt(N,p,_,C,M,F,z){return{appearanceTextOffset:B9(N,p,_,C,"text-offset",M,([Y,se])=>[Y*O9,se*O9]),appearanceTextRotate:B9(N,p,_,C,"text-rotate",F),appearanceTextSize:B9(N,p,_,C,"text-size",z)}}function xdt(N,p,_,C,M,F,z,H,Y,se){if(!N)return;const me=function(xe,_e,Te,De,Ue,Ye,nt){if(xe.kind==="camera")return xe.maxSize;if(xe.kind==="composite"){const it=_e.possiblyEvaluate(new Hn(xe.maxZoom,{worldview:Ye}),Te,nt).evaluate(Ue,{},Te,nt),ut=_e.possiblyEvaluate(new Hn(xe.minZoom,{worldview:Ye}),Te,nt).evaluate(Ue,{},Te,nt);return Math.max(it,ut)}return _e.possiblyEvaluate(new Hn(De,{worldview:Ye}),Te,nt).evaluate(Ue,{},Te,nt)}(p,_,C,M,F,Y,se);return N.scaleSelf(me*H*z)}function JFe(N,p,_,C,M,F,z,H,Y,se){return{iconPrimary:xdt(N.getPrimary(),p,_,C,M,F,z,H,Y,se),iconSecondary:xdt(N.getSecondary(),p,_,C,M,F,z,H,Y,se)}}function ydt(N,p){return N*p/24}function vdt(N,p,_,C,M,F){let z=null;return p.kind==="source"?(z=[nM*_*C],z[0]>Z6&&Yo(`${N}: Value for "text-size" or "icon-size" is >= 255. Reduce your "text-size" or "icon-size".`)):p.kind==="composite"&&(z=[nM*M*C,nM*F*C],(z[0]>Z6||z[1]>Z6)&&Yo(`${N}: Value for "text-size" or "icon-size" is >= 255. Reduce your "text-size" or "icon-size".`)),z}const bhs=Lt([{type:"Float32",name:"a_globe_pos",components:3},{type:"Float32",name:"a_uv",components:2}]),{members:Aoe}=bhs,_hs=Lt([{name:"a_pos_3",components:3,type:"Int16"}]);var eOe=Lt([{name:"a_pos",type:"Int16",components:2}]);class whs{constructor(p,_){this.pos=p,this.dir=_}intersectsPlane(p,_,C){const M=Sn(_,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 C[0]=this.pos[0]+this.dir[0]*F,C[1]=this.pos[1]+this.dir[1]*F,!0}}class Eoe{constructor(p,_){this.pos=p,this.dir=_}intersectsPlane(p,_,C){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 C[0]=this.pos[0]+this.dir[0]*F,C[1]=this.pos[1]+this.dir[1]*F,C[2]=this.pos[2]+this.dir[2]*F,!0}closestPointOnSphere(p,_,C){if(function(Te,De){var Ue=Te[0],Ye=Te[1],nt=Te[2],it=De[0],ut=De[1],ot=De[2];return Math.abs(Ue-it)<=u*Math.max(1,Math.abs(Ue),Math.abs(it))&&Math.abs(Ye-ut)<=u*Math.max(1,Math.abs(Ye),Math.abs(ut))&&Math.abs(nt-ot)<=u*Math.max(1,Math.abs(nt),Math.abs(ot))}(this.pos,p)||_===0)return C[0]=C[1]=C[2]=0,!1;const[M,F,z]=this.dir,H=this.pos[0]-p[0],Y=this.pos[1]-p[1],se=this.pos[2]-p[2],me=M*M+F*F+z*z,xe=2*(H*M+Y*F+se*z),_e=xe*xe-4*me*(H*H+Y*Y+se*se-_*_);if(_e<0){const Te=Math.max(-xe/2,0),De=H+M*Te,Ue=Y+F*Te,Ye=se+z*Te,nt=Math.hypot(De,Ue,Ye);return C[0]=De*_/nt,C[1]=Ue*_/nt,C[2]=Ye*_/nt,!1}{const Te=(-xe-Math.sqrt(_e))/(2*me);if(Te<0){const De=Math.hypot(H,Y,se);return C[0]=H*_/De,C[1]=Y*_/De,C[2]=se*_/De,!1}return C[0]=H+M*Te,C[1]=Y+F*Te,C[2]=se+z*Te,!0}}}class tOe{constructor(p,_,C,M,F){this.TL=p,this.TR=_,this.BR=C,this.BL=M,this.horizon=F}static fromInvProjectionMatrix(p,_,C){const M=[-1,1,1],F=[1,1,1],z=[1,-1,1],H=[-1,-1,1],Y=Qe(M,M,p),se=Qe(F,F,p),me=Qe(z,z,p),xe=Qe(H,H,p);return new tOe(Y,se,me,xe,_/C)}}function sOe(N,p,_,C){const M=p[0],F=p[1],z=p[2],H=_[0],Y=_[1],se=_[2];let me=1/0,xe=-1/0;for(let _e=0;_exe&&(xe=De)}return C[0]=me,C[1]=xe,C}function bdt(N,p){let _=!0;for(let C=0;C=0);if(F===0)return 0;F!==p.length&&(_=!1)}return _?2:1}const jhs=[0,0];function _dt(N,p){for(const _ of N.projections){const C=sOe(p,N.points[0],_.axis,jhs);if(_.projection[1]C[1])return 0}return 1}function wdt(N,p){const _=p[0],C=p[1],M=p[2],F=p[3];for(let z=0;z=0)return!0}return!1}class B3{constructor(p,_){this.points=p||new Array(8).fill([0,0,0]),this.planes=_||new Array(6).fill([0,0,0,0]),this.bounds=du.fromPoints(this.points),this.projections=[],this.frustumEdges=[ft([],this.points[2],this.points[3]),ft([],this.points[0],this.points[3]),ft([],this.points[4],this.points[0]),ft([],this.points[5],this.points[1]),ft([],this.points[6],this.points[2]),ft([],this.points[7],this.points[3])];for(const C of this.frustumEdges){const M=[0,-C[2],C[1]],F=[C[2],0,-C[0]];this.projections.push({axis:M,projection:sOe(this.points,this.points[0],M,[0,0])}),this.projections.push({axis:F,projection:sOe(this.points,this.points[0],F,[0,0])})}}static fromInvProjectionMatrix(p,_,C,M){const F=Math.pow(2,C),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 me=Ft([],se,p),xe=1/me[3]/_*F;return(_e=me)[0]=(Te=me)[0]*(De=[xe,xe,M?1/me[3]:xe,xe])[0],_e[1]=Te[1]*De[1],_e[2]=Te[2]*De[2],_e[3]=Te[3]*De[3],_e;var _e,Te,De}),H=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(se=>{const me=qe([],Ve([],ft([],z[se[0]],z[se[1]]),ft([],z[se[2]],z[se[1]]))),xe=-ze(me,z[se[1]]);return me.concat(xe)}),Y=[];for(let se=0;seDe&&(De=ut)}let Ue=1/0,Ye=-1/0;for(let nt=0;ntYe&&(Ye=ut)}if(Te>Ye||Ue>De)return 0}return 1}containsPoint(p){for(const _ of this.planes){const C=_[3];if(ze([_[0],_[1],_[2]],p)+C<0)return!1}return!0}}class du{static fromPoints(p){const _=[1/0,1/0,1/0],C=[-1/0,-1/0,-1/0];for(const M of p)ke(_,_,M),Ie(C,C,M);return new du(_,C)}static fromTileIdAndHeight(p,_,C){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 Toe(N){return N*pf/JT}oa(du,"Aabb");const Nhs=[new du([Vv,Vv,Vv],[q_,q_,q_]),new du([Vv,Vv,Vv],[0,0,q_]),new du([0,Vv,Vv],[q_,0,q_]),new du([Vv,0,Vv],[0,q_,q_]),new du([0,0,Vv],[q_,q_,q_])];function jdt(N,p,_,C=!0){const M=Fe([],N._camera.position,N.worldSize),F=[p,_,1,1];Ft(F,F,N.pixelMatrixInverse),bs(F,F,1/F[3]);const z=qe([],ft([],F,M)),H=N.globeMatrix,Y=[H[12],H[13],H[14]],se=ft([],Y,M),me=ce(se),xe=qe([],se),_e=N.worldSize/(2*Math.PI),Te=ze(xe,z),De=Math.asin(_e/me);if(De1?null:function(C,M,F,z){const H=Math.sin(F);return C*(Math.sin((1-z)*F)/H)+M*(Math.sin(z*F)/H)}(N.a[p],N.b[p],N.angle,ea(_,0,1))+N.center[p]}function VC(N){if(N.z<=1)return Nhs[N.z+2*N.y+N.x];const p=aOe(Moe(N));return du.fromPoints(p)}function $3(N,p,_){return Fe(N,N,1-_),Ne(N,N,p,_)}function Ndt(N,p,_){for(const C of N)Qe(C,C,p),Fe(C,C,_)}function rOe(N,p,_,C){const M=p/N.worldSize,F=N.globeMatrix;if(_.z<=1){const qt=VC(_).getCorners();return Ndt(qt,F,M),du.fromPoints(qt)}const z=Moe(_,C),H=aOe(z,pf+Toe(N._tileCoverLift));Ndt(H,F,M);const Y=Number.MAX_VALUE,se=[-Y,-Y,-Y],me=[Y,Y,Y];if(z.contains(N.center)){for(const ns of H)ke(me,me,ns),Ie(se,se,ns);se[2]=0;const qt=N.point,ts=[qt.x*M,qt.y*M,0];return ke(me,me,ts),Ie(se,se,ts),new du(me,se)}if(N._tileCoverLift>0){for(const qt of H)ke(me,me,qt),Ie(se,se,qt);return new du(me,se)}const xe=[F[12]*M,F[13]*M,F[14]*M],_e=z.getCenter(),Te=ea(N.center.lat,-85.051129,L),De=ea(_e.lat,-85.051129,L),Ue=Zg(N.center.lng),Ye=rp(Te);let nt=Ue-Zg(_e.lng);const it=Ye-rp(De);nt>.5?nt-=1:nt<-.5&&(nt+=1);let ut=0;Math.abs(nt)>Math.abs(it)?ut=nt>=0?1:3:(ut=it>=0?0:2,Ne(xe,xe,[F[4]*M,F[5]*M,F[6]*M],-Math.sin(Yr(it>=0?z.getSouth():z.getNorth()))*pf));const ot=H[ut],vt=H[(ut+1)%4],kt=new khs(ot,vt,xe),ls=[nOe(kt,0)||ot[0],nOe(kt,1)||ot[1],nOe(kt,2)||ot[2]],At=U3(N.zoom);if(At>0){const qt=function({x:ns,y:Ps,z:Ws},mn,ln,_n,Un){const Cs=1/(1<.5?$n=-1:Rn<-.5&&($n=1),Xs=((Xs+$n)*mn-(_n*=mn))*ln+_n,rn=((rn+$n)*mn-_n)*ln+_n,In=(In*mn-(Un*=mn))*ln+Un,Pn=(Pn*mn-Un)*ln+Un,[[Xs,Pn,0],[rn,Pn,0],[rn,In,0],[Xs,In,0]]}(_,p,N._pixelsPerMercatorPixel,Ue,Ye);for(let ns=0;nsMath.PI/2*1.01}const Adt=Yr(85),Shs=Math.cos(Adt),Chs=Math.sin(Adt);function Edt(N,p){const _=N.fovAboveCenter,C=N.elevation?N.elevation.getMinElevationBelowMSL()*p:0,M=Math.min(C,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 Y=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,Y)}class rM{constructor(p,_,C){this.z=p,this.x=_,this.y=C,this.key=aM(0,p,p,_,C)}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 C=function(F,z,H){const Y=2**H,se=2*Math.PI*6378137,me=se*(F/Y-.5),xe=se*(.5-(z+1)/Y);return`${me},${xe},${me+se/Y},${xe+se/Y}`}(this.x,this.y,this.z),M=function(F,z,H){let Y,se="";for(let me=F;me>0;me--)Y=1<this.canonical.z?new ug(p,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new ug(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 aM(this.wrap*+_,p,this.canonical.z,this.canonical.x,this.canonical.y);{const C=this.canonical.z-p;return aM(this.wrap*+_,p,p,this.canonical.x>>C,this.canonical.y>>C)}}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 ug(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const _=this.canonical.z+1,C=2*this.canonical.x,M=2*this.canonical.y;return[new ug(_,this.wrap,_,C,M),new ug(_,this.wrap,_,C+1,M),new ug(_,this.wrap,_,C,M+1),new ug(_,this.wrap,_,C+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 ug(N.overscaledZ,N.wrap,N.canonical.z,N.canonical.x,(N.canonical.y===0?1<new ug(N.overscaledZ,N.wrap,N.canonical.z,N.canonical.x,N.canonical.y===(1<ut&&(ot(kt,mn,At,qt,Ps,Ws),ot(mn,ls,Ps,Ws,ts,ns))}ot(xe,_e,C,F,M,F),ot(_e,Te,M,F,M,z),ot(Te,De,M,z,C,z),ot(De,xe,C,z,C,F),Ue-=ut,Ye-=ut,nt+=ut,it+=ut;const vt=1/Math.max(nt-Ue,it-Ye);return{scale:vt,x:Ue*vt,y:Ye*vt,x2:nt*vt,y2:it*vt,projection:p}}function Mdt(N,p,_,C,M,F,z,H,Y){if(Y.name==="globe")return rOe(N,p,new rM(_,C,M),!1);const se=cOe({z:_,x:C,y:M},Y);return new du([(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(rM,"CanonicalTileID"),oa(ug,"OverscaledTileID",{omit:["projMatrix","expandedProjMatrix"]});const Ahs=w(new Float32Array(16));class iM{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 Il(0,0)}projectTilePoint(p,_,C){return{x:p,y:_,z:0}}locationPoint(p,_,C,M=!0){return p._coordinatePoint(p.locationCoordinate(_,C),M)}pixelsPerMeter(p,_){return Xd(1,p)*_}pixelSpaceConversion(p,_,C){return 1}farthestPixelDistance(p){return Edt(p,p.pixelsPerMeter)}pointCoordinate(p,_,C,M){const F=p.horizonLineFromTop(!1),z=new xs(_,Math.max(F,C));return p.rayIntersectionCoordinate(p.pointRayIntersection(z,M))}pointCoordinate3D(p,_,C){const M=new xs(_,C);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 C=p.horizonLineFromTop();return _.y0?_<-$9+C&&(_=-$9+C):_>$9-C&&(_=$9-C);const z=F/Math.pow(Foe(_),M);let H=z*Math.sin(M*p),Y=F-z*Math.cos(M*p);return H=.5*(H/Math.PI+.5),Y=.5*(Y/Math.PI+.5),{x:H,y:this.southernCenter?Y:1-Y,z:0}}unproject(p,_){p=(2*p-.5)*Math.PI,this.southernCenter&&(_=1-_),_=(2*(1-_)-.5)*Math.PI;const{n:C,f:M}=this,F=M-_,z=Math.sign(F),H=Math.sign(C)*Math.sqrt(p*p+F*F);let Y=Math.atan2(p,Math.abs(F))*z;F*C<0&&(Y-=Math.PI*Math.sign(p)*z);const se=ea(Eo(Y/C)+this.center[0],-180,180),me=ea(Eo(2*Math.atan(Math.pow(M/H,1/C))-$9),-85.051129,L);return new Il(se,this.southernCenter?-me:me)}}class Pdt extends iM{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:Zg(p),y:rp(_),z:0}}unproject(p,_){const C=Rx(p),M=$d(_);return new Il(C,M)}}const Idt=Yr(L);class Ihs extends iM{project(p,_){const C=(_=Yr(_))*_,M=C*C;return{x:.5*((p=Yr(p))*(.8707-.131979*C+M*(M*(.003971*C-.001529*M)-.013791))/Math.PI+.5),y:1-.5*(_*(1.007226+C*(.015085+M*(.028874*C-.044475-.005916*M)))/Math.PI+1),z:0}}unproject(p,_){p=(2*p-.5)*Math.PI;let C=_=(2*(1-_)-1)*Math.PI,M=25,F=0,z=C*C;do{z=C*C;const se=z*z;F=(C*(1.007226+z*(.015085+se*(.028874*z-.044475-.005916*se)))-_)/(1.007226+z*(.045255+se*(.259866*z-.311325-.005916*11*se))),C=ea(C-F,-Idt,Idt)}while(Math.abs(F)>1e-6&&--M>0);z=C*C;const H=ea(Eo(p/(.8707+z*(z*(z*z*z*(.003971-.001529*z)-.013791)-.131979))),-180,180),Y=Eo(C);return new Il(H,Y)}}const Ldt=Yr(L);class Lhs extends iM{project(p,_){_=Yr(_),p=Yr(p);const C=Math.cos(_),M=2/Math.PI,F=Math.acos(C*Math.cos(p/2)),z=Math.sin(F)/F,H=.5*(p*M+2*C*Math.sin(p/2)/z)||0,Y=.5*(_+Math.sin(_)/z)||0;return{x:.5*(H/Math.PI+.5),y:1-.5*(Y/Math.PI+1),z:0}}unproject(p,_){let C=p=(2*p-.5)*Math.PI,M=_=(2*(1-_)-1)*Math.PI,F=25;const z=1e-6;let H=0,Y=0;do{const se=Math.cos(M),me=Math.sin(M),xe=2*me*se,_e=me*me,Te=se*se,De=Math.cos(C/2),Ue=Math.sin(C/2),Ye=2*De*Ue,nt=Ue*Ue,it=1-Te*De*De,ut=it?1/it:0,ot=it?Math.acos(se*De)*Math.sqrt(1/it):0,vt=.5*(2*ot*se*Ue+2*C/Math.PI)-p,kt=.5*(ot*me+M)-_,ls=.5*ut*(Te*nt+ot*se*De*_e)+1/Math.PI,At=ut*(Ye*xe/4-ot*me*Ue),qt=.125*ut*(xe*Ue-ot*me*Te*Ye),ts=.5*ut*(_e*De+ot*nt*se)+.5,ns=At*qt-ts*ls;H=(kt*At-vt*ts)/ns,Y=(vt*qt-kt*ls)/ns,C=ea(C-H,-Math.PI,Math.PI),M=ea(M-Y,-Ldt,Ldt)}while((Math.abs(H)>z||Math.abs(Y)>z)&&--F>0);return new Il(Eo(C),Eo(M))}}class Rdt extends iM{constructor(p){super(p),this.center=p.center||[0,0],this.parallels=p.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Yr(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:C,cosPhi:M}=this;return{x:Yr(p)*M*C+.5,y:-Math.sin(Yr(_))/M*C+.5,z:0}}unproject(p,_){const{scale:C,cosPhi:M}=this,F=-(_-.5)/C,z=ea(Eo((p-.5)/C)/M,-180,180),H=Math.asin(ea(F*M,-1,1)),Y=ea(Eo(H),-85.051129,L);return new Il(z,Y)}}class Rhs extends Pdt{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,_,C){const M=kY(p,_,C);return Qe(M,M,Loe(VC(C))),{x:M[0],y:M[1],z:M[2]}}locationPoint(p,_,C){const M=R3(_.lat,_.lng),F=qe([],M),z=C?p._centerAltitude+C:p.elevation?p.elevation.getAtPointOrZero(p.locationCoordinate(_),p._centerAltitude):p._centerAltitude;Ne(M,M,F,Xd(1,0)*Pr*z);const H=w(new Float64Array(16));return E(H,p.pixelMatrix,p.globeMatrix),Qe(M,M,H),new xs(M[0],M[1])}pixelsPerMeter(p,_){return Xd(1,0)*_}pixelSpaceConversion(p,_,C){const M=Xd(1,p)*_,F=ya(Xd(1,45)*_,M,C);return this.pixelsPerMeter(p,_)/F}createTileMatrix(p,_,C){const M=iOe(VC(C.canonical));return E(new Float64Array(16),p.globeMatrix,M)}createInversionMatrix(p,_){const{center:C}=p,M=Loe(VC(_));return D(M,M,Yr(C.lng)),R(M,M,Yr(C.lat)),P(M,M,[p._pixelsPerMercatorPixel,p._pixelsPerMercatorPixel,1]),Float32Array.from(M)}pointCoordinate(p,_,C,M){return jdt(p,_,C,!0)||new Q(0,0)}pointCoordinate3D(p,_,C){const M=this.pointCoordinate(p,_,C,0);return[M.x,M.y,M.z]}isPointAboveHorizon(p,_){return!jdt(p,_.x,_.y,!1)}farthestPixelDistance(p){const _=function(M,F){const z=M.cameraToCenterDistance,H=M._centerAltitude*F,Y=M._camera,se=M._camera.forward(),me=ue([],Fe([],se,-z),[0,0,H]),xe=M.worldSize/(2*Math.PI),_e=[0,0,-xe],Te=M.width/M.height,De=Math.tan(M.fovAboveCenter),Ue=Fe([],Y.up(),De),Ye=Fe([],Y.right(),De*Te),nt=qe([],ue([],ue([],se,Ue),Ye)),it=[];let ut;if(new Eoe(me,nt).closestPointOnSphere(_e,xe,it)){const ot=ue([],it,_e),vt=ft([],ot,me);ut=Math.cos(M.fovAboveCenter)*ce(vt)}else{const ot=ft([],me,_e),vt=ft([],_e,me);qe(vt,vt);const kt=ce(ot)-xe;ut=Math.sqrt(kt*(kt+2*xe));const ls=Math.acos(ut/(xe+kt))-Math.acos(ze(se,vt));ut*=Math.cos(ls)}return 1.01*ut}(p,this.pixelsPerMeter(p.center.lat,p.worldSize)),C=U3(p.zoom);if(C>0){const M=Edt(p,Xd(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(C,10))}return _}upVector(p,_,C){return kY(_,C,p,1)}upVectorScale(p){return{metersToTile:Toe(Poe(VC(p)))}}}function Ooe(N){const p=N.parallels,_=!!p&&Math.abs(p[0]+p[1])<.01;switch(N.name){case"mercator":return new Pdt(N);case"equirectangular":return new Mhs(N);case"naturalEarth":return new Ihs(N);case"equalEarth":return new Ths(N);case"winkelTripel":return new Lhs(N);case"albers":return _?new Rdt(N):new Ehs(N);case"lambertConformalConic":return _?new Rdt(N):new Phs(N);case"globe":return new Rhs(N)}throw new Error(`Invalid projection name: ${N.name}`)}const TY=Number.MAX_SAFE_INTEGER,Dhs=TY-1;function dOe(N,p,_,C){return N.orderp.max.x||N.max.xp.max.y||N.max.ynew xs((Y.x+F.x*Pr)*H-z.x*Pr,(Y.y+F.y*Pr)*H-z.y*Pr))}return hOe(_,M,N.indices,0,N.indices.length,0,0)}function mOe(N,p,_,C){const M=Math.pow(2,C.z-_.z);return new xs((N+_.x*Pr)*M-C.x*Pr,(p+_.y*Pr)*M-C.y*Pr)}function $oe(N,p){const _=[];p.grid.queryPoint(N,_);const C=p.indices,M=p.vertices;for(let F=0;F<_.length;F++){const z=_[F];if(tM([M[C[3*z+0]],M[C[3*z+1]],M[C[3*z+2]]],N))return!0}return!1}const MY={None:0,Model:1,Symbol:2,FillExtrusion:4};function fOe(N,p,_){const C=p[0],M=p[1];return N[0]=_[0]*C+_[4]*M+_[12],N[1]=_[1]*C+_[5]*M+_[13],N[3]=_[3]*C+_[7]*M+_[15],N}class pOe{isDataAvailableAtPoint(p){const _=this._source();if(this.isUsingMockSource()||!_||p.y<0||p.y>1)return!1;const C=_.getSource().maxzoom,M=1<1)return _;const F=M.getSource().maxzoom,z=1<{const Y=this.getAtTileOffset(p,F,z,H),se=M.upVector(p.canonical,F.x,F.y);return Fe(se,se,Y*M.upVectorScale(p.canonical,_,C).metersToTile),se}}getForTilePoints(p,_,C,M){if(this.isUsingMockSource())return!1;const F=U9.create(this,p,M);return!!F&&(_.forEach(z=>{z[2]=this.exaggeration()*F.getElevationAt(z[0],z[1],C,!0)}),!0)}getMinMaxForTile(p){if(this.isUsingMockSource())return null;const _=this.findDEMTileFor(p);if(!_||!_.dem)return null;const C=_.dem.tree,M=_.tileID,F=1<"u"?null:new TextDecoder("utf-8");class qoe{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,_,C=this.length){let M;for(;M=this.nextField(C);)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)*yOe;return this.pos+=8,p}readSFixed64(){const p=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*yOe;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,C=_[this.pos++];if(C<128)return C;let M,F=127&C;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,Y){const se=Y.buf;let me,xe;if(xe=se[Y.pos++],me=(112&xe)>>4,xe<128||(xe=se[Y.pos++],me|=(127&xe)<<3,xe<128)||(xe=se[Y.pos++],me|=(127&xe)<<10,xe<128)||(xe=se[Y.pos++],me|=(127&xe)<<17,xe<128)||(xe=se[Y.pos++],me|=(127&xe)<<24,xe<128)||(xe=se[Y.pos++],me|=(1&xe)<<31,xe<128))return q9(z,me,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&&Vdt?Vdt.decode(this.buf.subarray(_,p)):function(C,M,F){let z="",H=M;for(;H239?4:Y>223?3:Y>191?2:1;if(H+Te>F)break;Te===1?Y<128&&(_e=Y):Te===2?(se=C[H+1],(192&se)==128&&(_e=(31&Y)<<6|63&se,_e<=127&&(_e=null))):Te===3?(se=C[H+1],me=C[H+2],(192&se)==128&&(192&me)==128&&(_e=(15&Y)<<12|(63&se)<<6|63&me,(_e<=2047||_e>=55296&&_e<=57343)&&(_e=null))):Te===4&&(se=C[H+1],me=C[H+2],xe=C[H+3],(192&se)==128&&(192&me)==128&&(192&xe)==128&&(_e=(15&Y)<<18|(63&se)<<12|(63&me)<<6|63&xe,(_e<=65535||_e>=1114112)&&(_e=null))),_e===null?(_e=65533,Te=1):_e>65535&&(_e-=65536,z+=String.fromCharCode(_e>>>10&1023|55296),_e=56320|1023&_e),z+=String.fromCharCode(_e),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 C=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 q9(N,p,_){return _?4294967296*p+(N>>>0):4294967296*(p>>>0)+(N>>>0)}function Hdt(N,p,_){const C=p<=16383?1:p<=2097151?2:p<=268435455?3:Math.floor(Math.log(p)/(7*Math.LN2));_.realloc(C),_.buf.copyWithin(N+C,N,_.pos)}function Ohs(N,p){const _=N.length;let C=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),C=p.buf,M=p.pos,F=p.length;else{for(;H>127;)C[M++]=H%128|128,H=Math.floor(H/128);C[M++]=H}}p.pos=M}function zhs(N,p){for(let _=0;_H.h-z.h);const C=[{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=C.length-1;H>=0;H--){const Y=C[H];if(!(z.w>Y.w||z.h>Y.h)){if(z.x=Y.x,z.y=Y.y,F=Math.max(F,z.y+z.h),M=Math.max(M,z.x+z.w),z.w===Y.w&&z.h===Y.h){const se=C.pop();se&&Hp.id?1:N.versionp.version?1:N.sxp.sx?1:N.syp.sy?1:0}function Hoe(N){let p=0;for(let _=0;_0,Wdt(p,C,this.iconDescriptors,z),Wdt(_,C,this.patternDescriptors,z),this.iconDescriptors.sort(Voe),this.patternDescriptors.sort(Voe);let H=0;H=ij(H,Hoe(F)),H=ij(H,1);const Y=M?M.data:"";Y&&(H=ij(H,Hoe(Y))),H=ij(H,1);for(const se of this.iconDescriptors)H=ij(H,Hoe(se.id)),H=ij(H,se.version),H=ij(H,se.sx),H=ij(H,se.sy);H=ij(H,1);for(const se of this.patternDescriptors)H=ij(H,Hoe(se.id)),H=ij(H,se.version),H=ij(H,se.sx),H=ij(H,se.sy);this.hash=H}subsetOf(p){return this.scope===p.scope&&this.isSubsetArray(this.iconDescriptors,p.iconDescriptors,Voe)&&this.isSubsetArray(this.patternDescriptors,p.patternDescriptors,Voe)}isSubsetArray(p,_,C){let M=0,F=0;if(p.length>_.length)return!1;for(;M0&&me>0){const _e=this.useMipmap?Math.floor(Math.log2(Math.max(se,me)))+1:1;z.texStorage2D(z.TEXTURE_2D,_e,this.format,se,me),this.size=[se,me]}this.size&&(xe?z.texSubImage2D(z.TEXTURE_2D,0,H,Y,bOe(this.format),_Oe(this.format),p):"data"in p&&p.data&&z.texSubImage2D(z.TEXTURE_2D,0,H,Y,C,M,bOe(this.format),_Oe(this.format),p.data)),this.useMipmap&&z.generateMipmap(z.TEXTURE_2D)}bind(p,_,C=!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&&!C?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,_,C,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),C!==this.wrapS&&(H.texParameteri(H.TEXTURE_2D,H.TEXTURE_WRAP_S,C),this.wrapS=C),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 Kdt{constructor(p,_,C,M){this.context=p,this.format=M,this.size=C,this.texture=p.gl.createTexture();const[F,z,H]=this.size,{gl:Y}=p;Y.bindTexture(Y.TEXTURE_3D,this.texture),p.pixelStoreUnpackFlipY.set(!1),p.pixelStoreUnpack.set(1),p.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in _&&_.data&&Y.texImage3D(Y.TEXTURE_3D,0,this.format,F,z,H,0,bOe(this.format),_Oe(this.format),_.data)}bind(p,_){const{context:C}=this,{gl:M}=C;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 IY{static getImagePositionScale(p,_,C){if(_&&p){const{sx:M,sy:F}=p;return{x:M,y:F}}return{x:C,y:C}}constructor(p,_,C,M){this.paddedRect=p;const{pixelRatio:F,version:z,stretchX:H,stretchY:Y,content:se,sdf:me,usvg:xe}=_;this.pixelRatio=F,this.stretchX=H,this.stretchY=Y,this.content=se,this.version=z,this.padding=C,this.sdf=me,this.usvg=xe,this.scale=IY.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 Ydt(N,p,_){const C=Ih.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,_,[C.sx,C.sy]);return{bin:M,imagePosition:new IY(M,p,_,C),imageVariant:C}}function wOe(N,p){const _=[];for(const[M,F]of N.entries()){const z=Ih.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 C=new Map;for(const M of _)C.set(M.key,M.value);return C}class Zdt{constructor(p){this.sourceAtlasHash=p}}class Xdt{constructor(p,_,C,M,F=""){const z=new Map,H=new Map;this.haveRenderCallbacks=[];const Y=[],se=M!==void 0,me=se?new Map:void 0,xe=se?wOe(p,me):p,_e=se?wOe(_,me):_;this.addImages(xe,z,1,Y),this.addImages(_e,H,2,Y);const{w:Te,h:De}=Gdt(Y),Ue=new e0({width:Te||1,height:De||1});for(const[Ye,nt]of xe.entries()){const it=z.get(Ye).paddedRect;e0.copy(nt.data,Ue,{x:0,y:0},{x:it.x+1,y:it.y+1},nt.data,null,nt.sdf)}for(const[Ye,nt]of _e.entries()){const it=H.get(Ye),ut=it.paddedRect;let ot=it.padding;const vt=ut.x+ot,kt=ut.y+ot,ls=nt.data.width,At=nt.data.height;ot=ot>1?ot-1:ot,e0.copy(nt.data,Ue,{x:0,y:0},{x:vt,y:kt},nt.data,C),e0.copy(nt.data,Ue,{x:0,y:At-ot},{x:vt,y:kt-ot},{width:ls,height:ot},C),e0.copy(nt.data,Ue,{x:0,y:0},{x:vt,y:kt+At},{width:ls,height:ot},C),e0.copy(nt.data,Ue,{x:ls-ot,y:0},{x:vt-ot,y:kt},{width:ot,height:At},C),e0.copy(nt.data,Ue,{x:0,y:0},{x:vt+ls,y:kt},{width:ot,height:At},C),e0.copy(nt.data,Ue,{x:ls-ot,y:At-ot},{x:vt-ot,y:kt-ot},{width:ot,height:ot},C),e0.copy(nt.data,Ue,{x:0,y:At-ot},{x:vt+ls,y:kt-ot},{width:ot,height:ot},C),e0.copy(nt.data,Ue,{x:0,y:0},{x:vt+ls,y:kt+At},{width:ot,height:ot},C),e0.copy(nt.data,Ue,{x:ls-ot,y:0},{x:vt-ot,y:kt+At},{width:ot,height:ot},C)}this.lut=C,this.image=Ue,this.iconPositions=z,this.patternPositions=H,se&&(this.contentDescriptor=new vOe(xe,_e,M,C,F,me))}addImages(p,_,C,M){for(const[F,z]of p.entries()){const{bin:H,imagePosition:Y,imageVariant:se}=Ydt(F,z,C);_.set(F,Y),M.push(H),z.hasRenderCallback&&this.haveRenderCallbacks.push(se.id)}}patchUpdatedImages(p,_,C,M){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(F=>p.hasImage(F,C)),p.dispatchRenderCallbacks(this.haveRenderCallbacks,C);for(const F of p.getUpdatedImages(C)){for(const z of this.iconPositions.keys()){const H=Ih.parse(z);if(vd.isEqual(H.id,F)){const Y=p.getImage(F,C);this.patchUpdatedImage(this.iconPositions.get(z),Y,_,null)}}for(const z of this.patternPositions.keys()){const H=Ih.parse(z);if(vd.isEqual(H.id,F)){const Y=p.getImage(F,C);this.patchUpdatedImage(this.patternPositions.get(z),Y,_,M||this.lut)}}}}patchUpdatedImage(p,_,C,M=null){if(!p||!_||p.version===_.version)return;p.version=_.version;const[F,z]=p.tl,H=p.sdf;if(this.lut||H){const Y={width:_.data.width,height:_.data.height},se=new e0(Y);e0.copy(_.data,se,{x:0,y:0},{x:0,y:0},Y,M,H),C.update(se,{position:{x:F,y:z},recreateWhenResize:!1})}else C.update(_.data,{position:{x:F,y:z},recreateWhenResize:!1})}}oa(IY,"ImagePosition"),oa(Xdt,"ImageAtlas",{omit:["lut"]}),oa(Zdt,"ImageAtlasReference");class LY{constructor(p){this.pendingRequests=new Map,this.cachedRanges=new Map,this.fontstackCompositing=p&&p.fontstackCompositing||"client"}loadGlyphRange(p,_,C,M,F){if(this.fontstackCompositing==="server")return void LY.loadGlyphRange(p,_,C,M,F);const z=p.split(",").map(H=>H.trim()).filter(H=>H.length>0);z.length!==0?z.length!==1?this._loadMultipleFonts(z,_,C,M,F):this._loadFont(z[0],_,C,M,F):F(new Error("Empty fontstack"))}_loadMultipleFonts(p,_,C,M,F){const z=p.map(()=>null),H={completed:0,firstError:null,callbackCalled:!1},Y=(se,me,xe)=>{if(!H.callbackCalled&&(me&&!H.firstError&&(H.firstError=me),xe&&(z[se]=xe),H.completed++,H.completed===p.length)){H.callbackCalled=!0;const _e=z.filter(De=>De!==null);if(_e.length===0)return void F(H.firstError||new Error("All fonts failed to load"));const Te=this._composeGlyphs(_e);F(null,Te)}};for(let se=0;se{Y(se,me,xe)})}_loadFont(p,_,C,M,F){const z=`${p}:${_}`;if(this.cachedRanges.has(z)){const Y=this.cachedRanges.get(z);return void ah.frame(()=>F(null,Y))}const H=this.pendingRequests.get(z);H?H.push(F):(this.pendingRequests.set(z,[F]),LY.loadGlyphRange(p,_,C,M,(Y,se)=>{Y||this.cachedRanges.set(z,se||null);const me=this.pendingRequests.get(z);if(this.pendingRequests.delete(z),me)for(const xe of me)xe(Y,se)}))}_composeGlyphs(p){const _={};let C,M;for(const F of p)if(C===void 0&&F.ascender!==void 0&&(C=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:C,descender:M}}}LY.loadGlyphRange=async function(N,p,_,C,M){const F=256*p,z=F+255;let H;try{const Y=await C.transformRequest(C.normalizeGlyphsURL(_).replace("{fontstack}",N).replace("{range}",`${F}-${z}`),gr.Glyphs),{data:se}=await Xr(Y),me={},xe=function(_e){return function(Te){const De={glyphs:[]};let Ue;for(;Ue=Te.nextField();)Ue===1&&Whs(Te,Te.readVarint()+Te.pos,De);return De}(new qoe(_e))}(se);for(const _e of xe.glyphs)me[_e.id]=_e;H={glyphs:me,ascender:xe.ascender,descender:xe.descender}}catch(Y){return M(Y)}M(null,H)};const RY=1e20,jOe=new Float64Array(256);for(let N=0;N<256;N++){const p=.5-Math.pow(N/255,.45454545454545453);jOe[N]=p*Math.abs(p)}function Qdt(N,p,_,C,M,F,z,H,Y){for(let se=p;se-1);Y++,F[Y]=H,z[Y]=se,z[Y+1]=RY}for(let H=0,Y=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 C=[],M=this.url||xt.GLYPHS_URL;for(const F in p)for(const z of p[F])C.push({stack:F,id:z});Co(C,({stack:F,id:z},H)=>{let Y=this.entries[F];Y||(Y=this.entries[F]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let se=Y.glyphs[z];if(se!==void 0)return void H(null,{stack:F,id:z,glyph:se});if(se=this._tinySDF(Y,F,z),se)return Y.glyphs[z]=se,void H(null,{stack:F,id:z,glyph:se});const me=Math.floor(z/256);if(256*me>65535)return Yo("glyphs > 65535 not supported"),void H(null,{stack:F,id:z,glyph:se});if(Y.ranges[me])return void H(null,{stack:F,id:z,glyph:se});let xe=Y.requests[me];xe||(xe=Y.requests[me]=[],this.glyphLoader.loadGlyphRange(F,me,M,this.requestManager,(_e,Te)=>{if(Te){Y.ascender=Te.ascender,Y.descender=Te.descender;for(const De in Te.glyphs)this._doesCharSupportLocalGlyph(+De)||(Y.glyphs[+De]=Te.glyphs[+De]);Y.ranges[me]=!0}for(const De of xe)De(_e,Te);delete Y.requests[me]})),xe.push((_e,Te)=>{_e?H(_e):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:Y,id:se,glyph:me}of z)H[Y]===void 0&&(H[Y]={}),H[Y].glyphs===void 0&&(H[Y].glyphs={}),H[Y].glyphs[se]=me&&{id:me.id,bitmap:me.bitmap.clone(),metrics:me.metrics},H[Y].ascender=this.entries[Y].ascender,H[Y].descender=this.entries[Y].descender;_(null,H)}})}_doesCharSupportLocalGlyph(p){return this.localGlyphMode!==NOe.none&&(this.localGlyphMode===NOe.all?!!this.localFontFamily:!!this.localFontFamily&&(zC(p)||M3(p)||FC(p)||OC(p)||$k(p)||qk(p)||(_=p)>=131072&&_<=173791||(C=>C>=66736&&C<=66815)(p)));var _}_tinySDF(p,_,C){const M=this.localFontFamily;if(!M||!this._doesCharSupportLocalGlyph(C))return;let F=p.tinySDF;if(!F){let Ye="400";Yhs.test(_)?Ye="900":Zhs.test(_)?Ye="500":Xhs.test(_)&&(Ye="200"),F=p.tinySDF=new Woe.TinySDF({fontFamily:M,fontWeight:Ye,fontSize:48,buffer:6,radius:16}),F.fontWeight=Ye}const z=F.fontWeight;if(this.localGlyphs[z][C])return this.localGlyphs[z][C];const H=String.fromCodePoint(C),{data:Y,width:se,height:me,glyphWidth:xe,glyphHeight:_e,glyphLeft:Te,glyphTop:De,glyphAdvance:Ue}=F.draw(H);return this.localGlyphs[z][C]={id:C,bitmap:new sM({width:se,height:me},Y),metrics:{width:xe/2,height:_e/2,left:Te/2,top:De/2-27,advance:Ue/2,localGlyph:!0}}}}function eut(N,p){return N+p[1]-p[0]}function tut(N,p,_,C,M=1){const F=[],z=N.imagePrimary,H=z.pixelRatio,Y=z.paddedRect.w-2,se=z.paddedRect.h-2,me=(N.right-N.left)*M,xe=(N.bottom-N.top)*M,_e=z.stretchX||[[0,Y]],Te=z.stretchY||[[0,se]],De=_e.reduce(eut,0),Ue=Te.reduce(eut,0),Ye=Y-De,nt=se-Ue;let it=0,ut=De,ot=0,vt=Ue,kt=0,ls=Ye,At=0,qt=nt;if(z.content&&C){const ns=z.content;it=Koe(_e,0,ns[0]),ot=Koe(Te,0,ns[1]),ut=Koe(_e,ns[0],ns[2]),vt=Koe(Te,ns[1],ns[3]),kt=ns[0]-it,At=ns[1]-ot,ls=ns[2]-ns[0]-ut,qt=ns[3]-ns[1]-vt}const ts=(ns,Ps,Ws,mn)=>{const ln=Yoe(ns.stretch-it,ut,me,N.left*M),_n=Zoe(ns.fixed-kt,ls,ns.stretch,De),Un=Yoe(Ps.stretch-ot,vt,xe,N.top*M),Cs=Zoe(Ps.fixed-At,qt,Ps.stretch,Ue),Xs=Yoe(Ws.stretch-it,ut,me,N.left*M),rn=Zoe(Ws.fixed-kt,ls,Ws.stretch,De),In=Yoe(mn.stretch-ot,vt,xe,N.top*M),Pn=Zoe(mn.fixed-At,qt,mn.stretch,Ue),$n=new xs(ln,Un),Rn=new xs(Xs,Un),rr=new xs(Xs,In),On=new xs(ln,In),Ar=new xs(_n/H,Cs/H),or=new xs(rn/H,Pn/H),vr=p*Math.PI/180;if(vr){const Ni=Math.sin(vr),Fo=Math.cos(vr),rl=[Fo,-Ni,Ni,Fo];$n._matMult(rl),Rn._matMult(rl),On._matMult(rl),rr._matMult(rl)}const Ga=ns.stretch+ns.fixed,Wa=Ws.stretch+Ws.fixed,oi=Ps.stretch+Ps.fixed,Fa=mn.stretch+mn.fixed,Ai=N.imageSecondary;return{tl:$n,tr:Rn,bl:On,br:rr,texPrimary:{x:z.paddedRect.x+1+Ga,y:z.paddedRect.y+1+oi,w:Wa-Ga,h:Fa-oi},texSecondary:Ai?{x:Ai.paddedRect.x+1+Ga,y:Ai.paddedRect.y+1+oi,w:Wa-Ga,h:Fa-oi}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:Ar,pixelOffsetBR:or,minFontScaleX:ls/H/me,minFontScaleY:qt/H/xe,isSDF:_}};if(z.stretchX||z.stretchY){const ns=sut(_e,Ye,De),Ps=sut(Te,nt,Ue);for(let Ws=0;Ws0?[it,-ut]:ot<0?[-it,ut]:it===0?[ut,it]:[ut,-it]}(_);let Te=Math.abs(p.top-p.bottom);for(const nt of p.positionedLines)Te-=nt.lineOffset;const De=p.positionedLines.length,Ue=Te/De;let Ye=p.top-_[1];for(let nt=0;ntfunction(F){if(!F.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const z=F.condition.expression;return{featureDependent:!D1(z),stateDependent:!U0(z),zoomDependent:!Dx(z,["zoom"]),pitchDependent:!Dx(z,["pitch"]),brightnessDependent:!Dx(z,["brightness","measure-light"]),worldviewDependent:!Dx(z,["worldview"])}}(M));this.anyFeatureDependent=C.some(M=>M.featureDependent),this.anyStateDependent=C.some(M=>M.stateDependent)}update(p,_){const C=this.lastParams,M=!C||C.zoom!==p.zoom||C.pitch!==(p.pitch||0)||C.brightness!==(p.brightness||0)||C.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=C.get(z);F.set(z,new Li(H))}return _&&(this.cachedBatchIndices=M,this.cachedBatchSegments=F),{batchIndices:M,batchSegments:F}}snapshotSymbolVertexData(p,_){const C=p*V9;return this.layoutVertexArray.uint16.slice(C,C+_*V9)}restoreSymbolVertexData(p,_){this.layoutVertexArray.uint16.set(_,p*V9)}snapshotIconTransitioningVertexData(p,_){const C=2*p;return this.iconTransitioningVertexArray.uint16.slice(C,C+2*_)}restoreIconTransitioningVertexData(p,_){this.iconTransitioningVertexArray.uint16.set(_,2*p)}updateSymbolVertexData(p,_,C,M,F,z,H,Y,se,me,xe,_e,Te){const De=this.layoutVertexArray.uint16,Ue=p*V9;De[Ue]=_,De[Ue+1]=C,De[Ue+2]=M,De[Ue+3]=F,De[Ue+4]=z,De[Ue+5]=H,De[Ue+6]=Y,De[Ue+7]=se,De[Ue+8]=me,De[Ue+9]=xe,De[Ue+10]=_e,De[Ue+11]=Te}upload(p,_,C,M,F,z){this.isEmpty()||(C&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,nhs.members,!!z),this.indexBuffer=p.createIndexBuffer(this.indexArray,_),this.dynamicLayoutVertexBuffer=p.createVertexBuffer(this.dynamicLayoutVertexArray,ahs.members,!0),this.opacityVertexBuffer=p.createVertexBuffer(this.opacityVertexArray,tms,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=p.createVertexBuffer(this.iconTransitioningVertexArray,chs.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=p.createVertexBuffer(this.globeExtVertexArray,rhs.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||F)&&(this.zOffsetVertexBuffer=p.createVertexBuffer(this.zOffsetVertexArray,ihs.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=p.createVertexBuffer(this.orientationVertexArray,lhs.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray.length>0&&(this.featureIdBuffer=p.createVertexBuffer(this.featureIdArray,ohs.members,!1))),(C||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(kOe,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class SOe{constructor(p,_,C){this.layoutVertexArray=new p,this.layoutAttributes=_,this.indexArray=new C,this.segments=new Li,this.collisionVertexArray=new Ha,this.collisionVertexArrayExt=new qr}upload(p){this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=p.createVertexBuffer(this.collisionVertexArray,dhs.members,!0),this.collisionVertexBufferExt=p.createVertexBuffer(this.collisionVertexArrayExt,uhs.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}oa(SOe,"CollisionBuffers");class Qoe{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=z9(this.zoom,_["text-size"],this.worldview,p.availableImages),this.iconSizeData=z9(this.zoom,_["icon-size"],this.worldview,p.availableImages);const C=this.layers[0].layout,M=C.get("symbol-sort-key"),F=C.get("symbol-z-order");this.lut=p.lut,this.canOverlap=C.get("text-allow-overlap")||C.get("icon-allow-overlap")||C.get("text-ignore-placement")||C.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=C.get("text-writing-mode").map(z=>O3[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 C=Array.isArray(p)?p:[p];return _.some(M=>C.some(F=>M.hasLayoutProperty(F)))}getAppearanceFeatureData(p){return this.featureAppearanceData.get(p)}createArrays(){this.text=new kOe(new Hk(this.layers,{zoom:this.zoom,lut:this.lut},p=>p.startsWith("text")||p.startsWith("symbol"))),this.icon=new kOe(new Hk(this.layers,{zoom:this.zoom,lut:this.lut},p=>p.startsWith("icon")||p.startsWith("symbol"))),this.text.uboBinder=new QFe(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new QFe(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.glyphOffsetArray=new Kh,this.lineVertexArray=new cg,this.symbolInstances=new vc}calculateGlyphDependencies(p,_,C,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 Y=NY[z];Y&&(_[Y.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(p,_,C,M,F,z,H){if(!p.hasLayoutProperty("icon-size"))return H*z;let Y=1;const se=p.getUnevaluatedLayoutProperty("icon-size"),me=z9(this.zoom,se,this.worldview,F),xe=z3(me,_);if(me.kind!=="constant"&&me.kind!=="camera"||(Y=xe.uSize),me.kind==="composite"){const{minZoom:_e,maxZoom:Te}=me,De=se.possiblyEvaluate(new Hn(_e,{worldview:this.worldview}),M),Ue=se.possiblyEvaluate(new Hn(Te,{worldview:this.worldview}),M),Ye=De.evaluate(C,{},M,F);Y=Ye+(Ue.evaluate(C,{},M,F)-Ye)*xe.uSizeT}return me.kind==="source"&&(Y=se.possiblyEvaluate(new Hn(this.zoom,{worldview:this.worldview}),M).evaluate(C,{},M,F)),Y*z}updateFootprints(p,_){}hideSymbolVariant(p,_){this._setSymbolVariantVisibility(p,!1)}showSymbolVariant(p,_){this._setSymbolVariantVisibility(p,!0)}_initPlacementOpacities(){const p=_=>{const C=_.layoutVertexArray.length/4;for(let M=0;M{if(Y<0)return;const se=H.placedSymbolArray.get(Y),me=se.vertexStartIndex/4;for(let xe=0;xe{for(let C=0;C<_.opacityVertexArray.length;C++)_.opacityVertexArray.emplace(C,0);_.opacityVertexBuffer&&_.opacityVertexBuffer.updateData(_.opacityVertexArray)};this.hasTextData()&&p(this.text),this.hasIconData()&&p(this.icon)}addToPlacement(p,_,C,M,F,z,H,Y,se,me,xe,_e){if(this.symbolInstances.length===0)return;if(_e&&this.updateReplacement(H.tileID,_e),!this.collisionArrays){if(!H.collisionBoxArray)return;this.deserializeCollisionBoxes(H.collisionBoxArray)}this.placementIdRangeStart===null&&(this.placementIdRangeStart=_.allocateRange(C,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(),nt=Ye.name!=="globe";nt||Yo("new placement: globe projection is not supported yet; hiding symbols");const it=H.tileID.toUnwrapped(),ut=F.pitch>0,ot={collisionRules:{},insertIntoCollisionGrid:!0},vt=F.zoom,kt=z3(this.iconSizeData,vt),ls=z3(this.textSizeData,vt),At=De.paint.get("symbol-z-offset"),qt=De.layout.get("symbol-elevation-reference")==="sea",ts=!At.isConstant(),ns=ts?0:At.evaluate(null,{}),Ps=F.elevation,Ws=Udt(me),mn=On=>{if(!On)return Ws;const Ar=se.get(z6(On,De.scope));return Ar!==void 0?Ar:(Yo(`global placement: placement-group "${On}" does not match any placement-group layer; using the layer's implicit group`),Ws)},ln=De.paint.get("placement-priority"),_n=De.paint.get("placement-group"),Un=!ln.isConstant(),Cs=!_n.isConstant(),Xs=Un?0:ln.evaluate(null,{}),rn=Cs?Ws:mn(_n.evaluate(null,{})),In=Un||Cs,Pn=ts||In?H.latestFeatureIndex:null;Pn&&Pn.loadVTLayers();const $n=Pn?Pn.sourceLayerCoder.decode(this.sourceLayerIndex):"",Rn=(On,Ar,or)=>{let vr;if(this.elevationType==="road")vr=qt?or:or+pOe.getAtTileOffset(H.tileID,new xs(On.tileAnchorX,On.tileAnchorY),Ps,null);else{const Ai=this.hdExt?this.hdExt.elevationFeatures[Ar.elevationFeatureIndex]:void 0;vr=qt?or:or+pOe.getAtTileOffset(H.tileID,new xs(On.tileAnchorX,On.tileAnchorY),Ps,Ai)}if(vr+=Ar.zOffset,!vr)return{x:On.projectedAnchorX,y:On.projectedAnchorY,z:On.projectedAnchorZ,elevated:!1};const[Ga,Wa,oi]=Ye.upVector(H.tileID.canonical,On.tileAnchorX,On.tileAnchorY),Fa=Ye.upVectorScale(H.tileID.canonical,F.center.lat,F.worldSize).metersToTile;return{x:On.projectedAnchorX+Ga*vr*Fa,y:On.projectedAnchorY+Wa*vr*Fa,z:On.projectedAnchorZ+oi*vr*Fa,elevated:!0}},rr=(On,Ar,or,vr)=>{if(!On)return;const{x:Ga,y:Wa,z:oi,elevated:Fa}=Rn(On,Ar,or),Ai=function(W0,Zh,_l,qd,hh,Vm,ho,mp,Ip){const gf=[Zh,_l,qd,1];let $x=!1;qd||hh.pitch>0?(Ft(gf,gf,W0),mp&&Vm.name!=="globe"&&($x=zdt(mp,Zh,_l,qd,Ip,hh)>.9)):fOe(gf,gf,W0);const Ux=gf[3];return{x:(gf[0]/Ux+1)/2*hh.width,y:(-gf[1]/Ux+1)/2*hh.height,perspectiveRatio:Math.min(.5+hh.getCameraToCenterDistance(Vm)/Ux*.5,1.5),occluded:ho&&gf[2]>Ux||$x}}(M,Ga,Wa,oi,F,Ye,ut||Fa,Y,it);if(Ai.occluded||Ai.perspectiveRatio<=.55)return;const Ni=vr(),Fo=z*Ai.perspectiveRatio,rl=(On.x1*Ni-On.padding)*Fo+Ai.x,Bl=(On.y1*Ni-On.padding)*Fo+Ai.y,bc=(On.x2*Ni+On.padding)*Fo+Ai.x,qm=(On.y2*Ni+On.padding)*Fo+Ai.y;rl0||Ar.numVerticalGlyphVertices>0)){Yo("new placement: text-variable-anchor is not supported yet; skipping symbols");continue}if(Ar.numVerticalGlyphVertices>0){Yo("new placement: vertical text-writing-mode is not supported yet; skipping symbols");continue}const or=this.collisionArrays[On];if(!or.iconBox&&!or.textBox)continue;let vr=!1;for(const Fo of this.activeReplacements)if(!dOe(Fo,me,MY.Symbol,De.scope)&&!(Fo.min.x>Ar.tileAnchorX||Ar.tileAnchorX>Fo.max.x||Fo.min.y>Ar.tileAnchorY||Ar.tileAnchorY>Fo.max.y)&&(vr=$oe(mOe(Ar.tileAnchorX,Ar.tileAnchorY,H.tileID.canonical,Fo.footprintTileId.canonical),Fo.footprint),vr))break;const Ga={symbolId:{styleLayerId:C,symbolIdOrigin:1,symbolId:Te+On},variantIdx:0},Wa=Pn?Pn.loadFeature({featureIndex:Ar.featureIndex,sourceLayerIndex:this.sourceLayerIndex,bucketIndex:this.index,layoutVertexArrayOffset:0}):null,oi=In&&Wa&&Pn?Pn.getId(Wa,$n):void 0,Fa=oi!==void 0&&xe[String(oi)]||nms,Ai=Un&&Wa?ln.evaluate(Wa,Fa):Xs,Ni=Cs&&Wa?mn(_n.evaluate(Wa,Fa)):rn;if(p.startSymbolVariantProcessing(Ga,{placementSubgroupOrder:Ni,symbolPlacementPriority:Ai,symbolVariantVisibility:this.placementVariantVisible[On]?xOe.VARIANT_VISIBLE:xOe.SYMBOL_INVISIBLE,symbolPlacementType:1,styleLayerOrder:me,symbolDisplayOrder:0},ot),nt&&!vr){const Fo=ts&&Wa?At.evaluate(Wa,{}):ns;rr(or.iconBox,Ar,Fo,()=>this.getSymbolInstanceIconSize(kt,vt,Ar.placedIconSymbolIndex)),rr(or.textBox,Ar,Fo,()=>this.getSymbolInstanceTextSize(ls,Ar,vt,On))}p.finishVariantProcessing()}}updateReplacement(p,_){if(_.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=_.updateTime;const C=_.getReplacementRegionsForTile(p.toUnwrapped(),!0);return!Boe(this.activeReplacements,C)&&(this.activeReplacements=C,!0)}getResolvedImageFromTokens(p){return typeof p=="string"?yh.build(p):p}populate(p,_,C,M){const F=this.layers[0],z=F.layout,H=this.projection.name==="globe",Y=z.get("text-font"),se=z.get("text-field"),me=z.get("icon-image"),[xe,_e]=z.get("icon-size-scale-range"),Te=ea(_.scaleFactor||1,xe,_e),[De,Ue]=z.get("text-size-scale-range"),Ye=ea(_.scaleFactor||1,De,Ue),nt=(se.value.kind!=="constant"||se.value.value instanceof xu&&!se.value.value.isEmpty()||se.value.value.toString().length>0)&&(Y.value.kind!=="constant"||Y.value.value.length>0),it=me.value.kind!=="constant"||!!me.value.value||Object.keys(me.parameters).length>0,ut=this.hasAnyAppearanceLayoutProperty("icon-image"),ot=z.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!nt&&!it&&!ut)return;const vt=_.iconDependencies,kt=_.glyphDependencies,ls=_.availableImages,At=new Hn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),qt=ts=>{const ns=ts.id.toString();vt.has(ns)?vt.get(ns).push(ts):vt.set(ns,[ts])};for(const ts of p){const{feature:ns,id:Ps,index:Ws,sourceLayerIndex:mn}=ts,ln=F._featureFilter.needGeometry,_n=_t(ns,ln);if(!F._featureFilter.filter(At,_n,C))continue;if(ln||(_n.geometry=dt(ns,C,M)),H&&ns.type!==1&&C.z<=5){const Rn=_n.geometry,rr=.98078528056,On=(Ar,or)=>ze(kY(Ar.x,Ar.y,C,1),kY(or.x,or.y,C,1)){if(!Rn.getLayoutProperty("icon-image"))return;const{iconPrimary:rr,iconSecondary:On}=this.getCombinedIconVariants(Rn,Xs,_n,C,ls,Pn,Te);rr&&(qt(rr),On&&(this.hasAnySecondaryIcon=!0,qt(On)))}),Un){const Rn=Y.evaluate(_n,{},C).join(","),rr=z.get("text-rotation-alignment")==="map"&&z.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.includes(O3.vertical);for(const On of Un.sections)if(On.image){const Ar=On.image.getPrimary().scaleSelf(this.pixelRatio*Ye),or=Ar.id.toString(),vr=vt.get(or)||[];vr.push(Ar),vt.set(or,vr)}else{const Ar=de(Un.toString()),or=On.fontStack||Rn,vr=kt[or]=kt[or]||{};this.calculateGlyphDependencies(On.text,vr,rr,this.allowVerticalPlacement,Ar)}}}z.get("symbol-placement")==="line"&&(this.features=function(ts){const ns={},Ps={},Ws=[];let mn=0;function ln(Xs){Ws.push(ts[Xs]),mn++}function _n(Xs,rn,In){const Pn=Ps[Xs];return delete Ps[Xs],Ps[rn]=Pn,Ws[Pn].geometry[0].pop(),Ws[Pn].geometry[0]=Ws[Pn].geometry[0].concat(In[0]),Pn}function Un(Xs,rn,In){const Pn=ns[rn];return delete ns[rn],ns[Xs]=Pn,Ws[Pn].geometry[0].shift(),Ws[Pn].geometry[0]=In[0].concat(Ws[Pn].geometry[0]),Pn}function Cs(Xs,rn,In){const Pn=In?rn[0].at(-1):rn[0][0];return`${Xs}:${Pn.x}:${Pn.y}`}for(let Xs=0;Xs1){ln(Xs);continue}const $n=Cs(Pn,In,!1),Rn=Cs(Pn,In,!0);if($n in Ps&&Rn in ns&&Ps[$n]!==ns[Rn]){const rr=Un($n,Rn,In),On=_n($n,Rn,Ws[rr].geometry);delete ns[$n],delete Ps[Rn],Ps[Cs(Pn,Ws[On].geometry,!0)]=On,Ws[rr].geometry=null}else $n in Ps?_n($n,Rn,In):Rn in ns?Un($n,Rn,In):(ln(Xs),ns[$n]=mn-1,Ps[Rn]=mn-1)}return Ws.filter(Xs=>Xs.geometry)}(this.features)),z.get("symbol-elevation-reference")==="hd-road-markup"?(this.elevationType="road",this.hdExt&&(this.hdExt.configureCrossSource(C,_.elevationParams,_.crossSourceElevationEnabled,_.terrainEnabled),_.elevationFeatures&&_.elevationFeatures.length>0&&this.hdExt.addElevationFeatures(_.elevationFeatures,C))):z.get("symbol-z-elevate")&&(this.elevationType="offset"),this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((ts,ns)=>ts.sortKey-ns.sortKey)}getCombinedIconVariants(p,_,C,M,F,z,H){let Y;if(p.hasLayoutProperty("icon-image")){const se=_.getAppearanceValueAndResolveTokens(p,"icon-image",C,M,F);Y=this.getResolvedImageFromTokens(se)}else{const se=_.getValueAndResolveTokens("icon-image",C,M,F);Y=this.getResolvedImageFromTokens(se)}if(Y){const se=p.hasLayoutProperty("icon-size")?p.getUnevaluatedLayoutProperty("icon-size"):_._unevaluatedLayout._values["icon-size"],me=z9(this.zoom,se,this.worldview,F),{iconPrimary:xe,iconSecondary:_e}=JFe(Y,me,se,M,this.zoom,z,this.pixelRatio,H,this.worldview,F);return{iconPrimary:xe,iconSecondary:_e}}return{iconPrimary:void 0,iconSecondary:void 0}}getCombinedIconPrimary(p,_,C,M,F,z,H){return this.getCombinedIconVariants(p,_,C,M,F,z,H).iconPrimary}updateSymbolInstanceIconVertices(p,_,C,M,F,z){const{canonical:H,availableImages:Y,globalProperties:se,layer:me,iconScaleFactor:xe,featureState:_e,layoutIconOffset:Te,layoutIconSize:De,layoutIconRotate:Ue}=z;if(p.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(_.activeAppearanceIndex===C)return{vertexOffsetDelta:p.numIconVertices,hasChanges:!1};const Ye=C>=0?me.appearances[C]:null;if(Ye){const nt={sortKey:void 0,text:void 0,icon:null,index:p.featureIndex,sourceLayerIndex:p.featureIndex,geometry:[],properties:_.properties,type:"Point",id:_.id},{iconPrimary:it,iconSecondary:ut}=this.getCombinedIconVariants(Ye,me,M,H,Y,nt,xe);if(!it)return{vertexOffsetDelta:0,hasChanges:!1};const ot=it.toString(),vt=this.iconAtlasPositions&&this.iconAtlasPositions.get(ot);if(vt){const{appearanceIconOffset:kt,appearanceIconRotate:ls}=pdt(Ye,me,M,H,Te,Ue,De,xe),At=me.layout.get("icon-anchor").evaluate(M,_e,H);let qt=mdt(vt,ut?this.iconAtlasPositions&&this.iconAtlasPositions.get(ut.toString()):void 0,kt,At);const ts=vt.sdf,ns=me.layout.get("icon-text-fit").constantOr("none");ns!=="none"&&_.textShaping&&_.iconTextFitPadding&&_.fontScale&&(qt=fdt(qt,_.textShaping,ns,_.iconTextFitPadding,kt,_.fontScale));const Ps=this.calculateEffectiveAppearanceIconSize(Ye,se.zoom,M,H,Y,xe,De),Ws=0,mn=1+(Math.min(Z6,Math.round(Ps*nM))<<1),ln=tut(qt,ls,ts,ns!=="none",xe),_n=this.icon.iconTransitioningVertexArray.length>0;_.isUsingAppearanceIconVertexData||(_.isUsingAppearanceIconVertexData=!0,_.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(F,p.numIconVertices),_n&&(_.layoutBasedIconTransitioningVertexData=this.icon.snapshotIconTransitioningVertexData(F,p.numIconVertices)));const Un=Math.floor(p.numIconVertices/4),Cs=Math.min(ln.length,Un);let Xs=F;const rn=_n?this.icon.iconTransitioningVertexArray.uint16:null;for(let Pn=0;Pn0||p.numVerticalGlyphVertices>0;if(!ot)return{vertexOffsetDelta:ot?p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices:0,hasChanges:!1};if(_.activeAppearanceIndex===C)return{vertexOffsetDelta:p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices,hasChanges:!1};const vt=C>=0?Y.appearances[C]:null;if(vt&&_.textShaping){const{appearanceTextOffset:kt,appearanceTextRotate:ls,appearanceTextSize:At}=gdt(vt,Y,M,H,_e,De,Te);_.fontScale=ydt(At,_.textScaleFactor);const qt=vt.getUnevaluatedLayoutProperty("text-size");let ts=this.textSizeData,ns=nt,Ps=it;vt.hasLayoutProperty("text-size")&&(ts=z9(this.zoom,qt,this.worldview,ut),ns=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Ps=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const Ws=_.textShaping.bottom-_e[1],mn=_.textShaping.left-_e[0],ln=_.textShaping.right-_e[0];_.textShaping.top=kt[1]+(_.textShaping.top-_e[1]),_.textShaping.bottom=kt[1]+Ws,_.textShaping.left=kt[0]+mn,_.textShaping.right=kt[0]+ln;const _n=rut(0,_.textShaping,kt,Y,!1,M,me,this.allowVerticalPlacement,ls),Un=At&&ts.kind==="composite"?qt.possiblyEvaluate(new Hn(ns,{}),H).evaluate(M,xe,H):Ue,Cs=At&&ts.kind==="composite"?qt.possiblyEvaluate(new Hn(Ps,{}),H).evaluate(M,xe,H):Ye,Xs=vdt(vt.name,ts,At,se,Un,Cs),rn=Array.isArray(Xs)?Xs[1]:At,In=0,Pn=1+(Math.min(Z6,Math.round(rn*nM))<<1);_.isUsingAppearanceTextVertexData||(_.isUsingAppearanceTextVertexData=!0,_.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(F,p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices));for(let $n=0;$n<_n.length&&$n<(p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices)/4;++$n){const Rn=_n[$n],rr=Rn.glyphOffset[1],On=p.tileAnchorX,Ar=p.tileAnchorY,or=F+4*$n;this.text.updateSymbolVertexData(or,On,Ar,Math.round(32*Rn.tl.x),Math.round(32*(rr+Rn.tl.y)),Rn.texPrimary.x,Rn.texPrimary.y,In,Pn,Rn.pixelOffsetTL.x,Rn.pixelOffsetTL.y,Rn.minFontScaleX,Rn.minFontScaleY),this.text.updateSymbolVertexData(or+1,On,Ar,Math.round(32*Rn.tr.x),Math.round(32*(rr+Rn.tr.y)),Rn.texPrimary.x+Rn.texPrimary.w,Rn.texPrimary.y,In,Pn,Rn.pixelOffsetBR.x,Rn.pixelOffsetTL.y,Rn.minFontScaleX,Rn.minFontScaleY),this.text.updateSymbolVertexData(or+2,On,Ar,Math.round(32*Rn.bl.x),Math.round(32*(rr+Rn.bl.y)),Rn.texPrimary.x,Rn.texPrimary.y+Rn.texPrimary.h,In,Pn,Rn.pixelOffsetTL.x,Rn.pixelOffsetBR.y,Rn.minFontScaleX,Rn.minFontScaleY),this.text.updateSymbolVertexData(or+3,On,Ar,Math.round(32*Rn.br.x),Math.round(32*(rr+Rn.br.y)),Rn.texPrimary.x+Rn.texPrimary.w,Rn.texPrimary.y+Rn.texPrimary.h,In,Pn,Rn.pixelOffsetBR.x,Rn.pixelOffsetBR.y,Rn.minFontScaleX,Rn.minFontScaleY)}return{vertexOffsetDelta:p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices,hasChanges:!0}}return _.isUsingAppearanceTextVertexData?(this.text.restoreSymbolVertexData(F,_.layoutBasedTextVertexData),_.isUsingAppearanceTextVertexData=!1,{vertexOffsetDelta:_.layoutBasedTextVertexData.length/V9,hasChanges:!0}):{vertexOffsetDelta:p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices,hasChanges:!1}}updateExpressions(p){this.text&&this.text.programConfigurations.updateExpressions(p),this.icon&&this.icon.programConfigurations.updateExpressions(p)}update(p,_,C,M,F,z,H,Y){if(this.text.uboBinder||this.text.programConfigurations.updatePaintArrays(p,_,F,C,M,z,H,this.worldview),this.icon.uboBinder||this.icon.programConfigurations.updatePaintArrays(p,_,F,C,M,z,H,this.worldview),Y){if(z)for(const se of[this.text.uboBinder,this.icon.uboBinder])se&&!se.isLightConstant&&se.updateDynamicExpressions(F[0],_,Y,C,p,H);else if(Object.keys(p).length>0){const se=F[0],me=[this.text.uboBinder,this.icon.uboBinder].filter(xe=>xe&&xe.hasStateDependentPaint(se));if(me.length>0){const xe=new Set(Object.keys(p).map(_e=>{const Te=Number(_e);return!isNaN(Te)&&Number.isSafeInteger(Te)&&String(Te)===_e?Te:_e}));for(const _e of me)_e.updateFeatures(xe,se,_,Y,C,p,H)}}}}updateZOffset(){const p=(F,z,H)=>{C+=z,C>F.length&&F.resize(C);for(let Y=-z;Y<0;Y++)F.emplace(Y+C,H)},_=(F,z,H)=>{M+=z,M>F.length&&F.resize(M);for(let Y=-z;Y<0;Y++)F.emplace(Y+M,H)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let C=0,M=0;for(let F=0;F0;if((H>0||Y>0)&&(p(this.text.zOffsetVertexArray,H,me),p(this.text.zOffsetVertexArray,Y,me)),xe){const{placedIconSymbolIndex:_e,verticalPlacedIconSymbolIndex:Te}=z;_e>=0&&_(this.icon.zOffsetVertexArray,se,me),Te>=0&&_(this.icon.zOffsetVertexArray,z.numVerticalIconVertices,me)}}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,_,C,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,_,C,M,F,z=!1){const H={hasLayoutChanges:!1,hasUboChanges:!1};if(!p||!C||!this.featureAppearanceData)return H;const Y=_||{},se=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,me=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!se&&!me)return H;const xe=this.layers[0],_e=xe.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===xe.appearancesVersion||(this.featureAppearances=new Jhs(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,nt=!1;if(se){const[ls,At]=_e.get("icon-size-scale-range");De=ea(1,ls,At)}let it=1,ut=0,ot=!1;if(me){const[ls,At]=_e.get("text-size-scale-range");it=ea(1,ls,At)}const vt=new Map;if(F&&C)for(const ls of C){const At=F.getImage(ls,xe.scope);if(At){const qt=new Ih(ls.toString());vt.set(qt.toString(),At)}}const kt=[this.text.uboBinder,this.icon.uboBinder];for(let ls=0;ls_n.isActive({globals:M,feature:Ps,canonical:p,featureState:ns})):-1;Ws=ln>=0?ln:-1}const mn=qt.activeAppearanceIndex!==Ws;if(me){const ln=_e.get("text-size"),_n=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Un=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Cs={canonical:p,layer:xe,featureState:ns,availableImages:C,textScaleFactor:it,imageMap:vt,layoutTextOffset:_e.get("text-offset").evaluate(Ps,ns,p).map(rn=>rn*O9),layoutTextSize:ln.evaluate(Ps,ns,p),layoutTextRotate:_e.get("text-rotate").evaluate(Ps,ns,p),layoutMinZoomSize:ln.evaluate(Ps,{zoom:_n},p),layoutMaxZoomSize:ln.evaluate(Ps,{zoom:Un},p),layoutTextSizeMinZoom:_n,layoutTextSizeMaxZoom:Un},Xs=this.updateSymbolInstanceTextVertices(At,qt,Ws,Ps,ut,Cs);ut+=Xs.vertexOffsetDelta,ot=ot||Xs.hasChanges}if(se){const ln={canonical:p,layer:xe,featureState:ns,availableImages:C,globalProperties:M,iconScaleFactor:De,layoutIconOffset:_e.get("icon-offset").evaluate(Ps,ns,p),layoutIconSize:_e.get("icon-size").evaluate(Ps,ns,p,C),layoutIconRotate:_e.get("icon-rotate").evaluate(Ps,ns,p)},_n=this.updateSymbolInstanceIconVertices(At,qt,Ws,Ps,Ue,ln);Ue+=_n.vertexOffsetDelta,Ye=Ye||_n.hasChanges}if(mn){const ln=At.featureIndex,_n=M?M.brightness:null,Un=ns||{},Cs=Ws>=0?xe.appearances[Ws]:null;for(const Xs of kt)Xs&&(Xs.layer=xe,nt=Xs.updateFeaturePaintForAppearance(ln,Ps,Un,p,C,_n,Cs)||nt)}qt.activeAppearanceIndex=Ws}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),ot&&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||ot,hasUboChanges:nt}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=Ooe(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(p,_){const C=this.lineVertexArray.length;if(p.segment!==void 0)for(const{x:M,y:F}of _)this.lineVertexArray.emplaceBack(M,F);return{lineStartIndex:C,lineLength:this.lineVertexArray.length-C}}addSymbols(p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye,nt,it){const ut=p.indexArray,ot=p.layoutVertexArray,vt=p.globeExtVertexArray,kt=it,ls=p.uboBinder?p.uboBinder.getCurrentBatchIndex():void 0,At=p.segments.prepareSegment(4*kt,ot,ut,this.canOverlap?z.sortKey:void 0,ls),qt=this.glyphOffsetArray.length,ts=At.vertexLength,ns=this.allowVerticalPlacement&&H===O3.vertical?Math.PI/2:0,Ps=z.text&&z.text.sections;let Ws=ot.length,mn=-1;for(let Un=0;Un<_.length;Un++){const{tl:Cs,tr:Xs,bl:rn,br:In,texPrimary:Pn,texSecondary:$n,pixelOffsetTL:Rn,pixelOffsetBR:rr,minFontScaleX:On,minFontScaleY:Ar,glyphOffset:or,isSDF:vr,sectionIndex:Ga}=_[Un],Wa=At.vertexLength,oi=or[1];if(DY(ot,se.x,se.y,Cs.x,oi+Cs.y,Pn.x,Pn.y,C,vr,Rn.x,Rn.y,On,Ar),DY(ot,se.x,se.y,Xs.x,oi+Xs.y,Pn.x+Pn.w,Pn.y,C,vr,rr.x,Rn.y,On,Ar),DY(ot,se.x,se.y,rn.x,oi+rn.y,Pn.x,Pn.y+Pn.h,C,vr,Rn.x,rr.y,On,Ar),DY(ot,se.x,se.y,In.x,oi+In.y,Pn.x+Pn.w,Pn.y+Pn.h,C,vr,rr.x,rr.y,On,Ar),Y){const{x:Fa,y:Ai,z:Ni}=Y.anchor,[Fo,rl,Bl]=Y.up;OY(vt,Fa,Ai,Ni,Fo,rl,Bl),OY(vt,Fa,Ai,Ni,Fo,rl,Bl),OY(vt,Fa,Ai,Ni,Fo,rl,Bl),OY(vt,Fa,Ai,Ni,Fo,rl,Bl),X6(p.dynamicLayoutVertexArray,Fa,Ai,Ni,ns)}else X6(p.dynamicLayoutVertexArray,se.x,se.y,se.z,ns);if(Ye){const Fa=$n||Pn;FY(p.iconTransitioningVertexArray,Fa.x,Fa.y),FY(p.iconTransitioningVertexArray,Fa.x+Fa.w,Fa.y),FY(p.iconTransitioningVertexArray,Fa.x,Fa.y+Fa.h),FY(p.iconTransitioningVertexArray,Fa.x+Fa.w,Fa.y+Fa.h)}if(ut.emplaceBack(Wa,Wa+1,Wa+2),ut.emplaceBack(Wa+1,Wa+2,Wa+3),At.vertexLength+=4,At.primitiveLength+=2,this.glyphOffsetArray.emplaceBack(or[0]),(Un===_.length-1||Ga!==_[Un+1].sectionIndex)&&(p.uboBinder||p.programConfigurations.populatePaintArrays(ot.length,z,z.index,{},Te,De,Ue,Ps&&Ps[Ga],this.worldview),p.uboBinder)){const Fa=p.uboBinder.populateUBO(z,z.index,De,Te,Ue,Ps&&Ps[Ga]);mn=Fa;const Ai=ot.length-Ws;for(let Ni=0;Ni=0)){const Un=4*ln;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,_,C,M){const F=this.defaultPlacedTextSymbolIndex(_,M),z=this.text.placedSymbolArray.get(F),H=Coe(this.textSizeData,p,z)/O9;return this.tilePixelRatio*H}getSymbolInstanceIconSize(p,_,C){const M=this.icon.placedSymbolArray.get(C),F=Coe(this.iconSizeData,p,M);return this.tilePixelRatio*F}_commitDebugCollisionVertexUpdate(p,_,C,M){p.emplaceBack(_,-C,-C,M),p.emplaceBack(_,C,-C,M),p.emplaceBack(_,C,C,M),p.emplaceBack(_,-C,C,M)}_updateTextDebugCollisionBoxes(p,_,C,M,F,z,H){for(let Y=M;Y0}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 C=p.placedSymbolArray.get(_),M=C.vertexStartIndex+4*C.numGlyphs;for(let F=C.vertexStartIndex;FM[H]-M[Y]||F[Y]-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 C=this.sortKeyRanges.at(-1);C&&C.sortKey===_?C.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 C=this.symbolInstances.get(_);this.featureSortOrder.push(C.featureIndex);const{rightJustifiedTextSymbolIndex:M,centerJustifiedTextSymbolIndex:F,leftJustifiedTextSymbolIndex:z,verticalPlacedTextSymbolIndex:H,placedIconSymbolIndex:Y,verticalPlacedIconSymbolIndex:se}=C;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),Y>=0&&this.addIndicesForPlacedSymbol(this.icon,Y),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(Qoe,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),Qoe.addDynamicAttributes=X6;class aut extends OFe{constructor(p,_,C){super(p,_,C),this.elevatedLayoutVertexArray=new Bs}upload(p){const _=this.uploaded;super.upload(p),!_&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=p.createVertexBuffer(this.elevatedLayoutVertexArray,Yh.members))}destroy(){this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),super.destroy()}}oa(aut,"ElevatedFillBufferData");class q3{constructor(){this.portals=[]}static isOnBorder(p,_){return p<=0&&_<=0||p>=Pr&&_>=Pr}static evaluate(p){if(p.length===0)return new q3;let _=[];for(const Y of p)_.push(...Y.portals);if(_.length===0)return new q3;for(const Y of _){const se=Y.va,me=Y.vb;(q3.isOnBorder(se.x,me.x)||q3.isOnBorder(se.y,me.y))&&(Y.type="border")}const C=_.filter(Y=>Y.type!=="unevaluated"),M=_.filter(Y=>Y.type==="unevaluated");if(M.length===0)return new q3;M.sort((Y,se)=>Y.hash===se.hash?Y.isTunnel===se.isTunnel?0:Y.isTunnel?-1:1:Y.hashY.hashF!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new Hk(_,{zoom:C,lut:M},F=>F!=="fill-bridge-guard-rail-color")}addVertices(p,_){const C=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||_e.x>=F.min.x&&_e.x<=F.max.x&&_e.y>=F.min.y&&_e.y<=F.max.y||R9(xe,_e,H))||this.isOnBorder(xe.x,_e.x)||this.isOnBorder(xe.y,_e.y))continue;const Te=V1.computeEdgeHash(this.unevalVertices[se],this.unevalVertices[me]);let De,Ue=this.vertexHashLookup.get(V1.computePosHash(xe));Ue!=null?De=Ue.next:(Ue=this.vertexHashLookup.get(V1.computePosHash(_e)),De=Ue!=null?Ue.prev:Te),this.unevalEdges.push({polygonIdx:p,a:se,b:me,hash:Te,portalHash:De,isTunnel:M,type:"unevaluated",featureInfo:z})}}addPortalCandidates(p,_,C,M,F){if(_.length!==0){this.vertexHashLookup.clear();for(const z of _){if(z.length===0)continue;const H=z[0];let Y=V1.computeEdgeHash(H[H.length-2],H.at(-1));for(let se=0;se({vertexOffset:0,primitiveOffset:this.indexArray.length}),C=_e=>{_e.primitiveLength=this.indexArray.length-_e.primitiveOffset},M=new rms(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(p.portals,this.unevalEdges);const F=_(),z=_(),H=_(),Y=(_e,Te)=>{_e.sort((Ue,Ye)=>Ue.type===Te&&Ye.type!==Te?-1:Ue.type!==Te&&Ye.type===Te?1:0);const De=_e.findIndex(Ue=>Ue.type!==Te);return De>=0?De:_e.length};let se=0;this.unevalEdges.length>0&&(se=Y(this.unevalEdges,"none"),this.constructBridgeStructures(M,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:se},this.tileToMeters)),C(H);const me=_(),xe=_();if(this.unevalEdges.length>0){const _e=this.unevalEdges.splice(se),Te=Y(_e,"tunnel")+se;this.unevalEdges.push(..._e),this.constructTunnelStructures(M,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:se},{min:se,max:Te})}C(me),M.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),C(xe),M.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),C(z),M.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights,4),C(F),this.maskSegments=Li.simpleSegment(0,xe.primitiveOffset,0,xe.primitiveLength),this.depthSegments=Li.simpleSegment(0,z.primitiveOffset,0,z.primitiveLength),this.renderableBridgeSegments=Li.simpleSegment(0,H.primitiveOffset,0,H.primitiveLength),this.renderableTunnelSegments=Li.simpleSegment(0,me.primitiveOffset,0,me.primitiveLength),this.shadowCasterSegments=Li.simpleSegment(0,F.primitiveOffset,0,F.primitiveLength)}update(p,_,C,M,F,z,H,Y){this.bridgeProgramConfigurations.updatePaintArrays(p,_,F,C,M,z,H,Y),this.tunnelProgramConfigurations.updatePaintArrays(p,_,F,C,M,z,H,Y)}upload(p){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=p.createVertexBuffer(this.vertexPositions,sx.members),this.vertexBufferNormal=p.createVertexBuffer(this.vertexNormals,Ku.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,_,C,M,F){const z=(H,Y)=>{for(let se=0;sefe(ln,_[_n].x,_[_n].y,C[_n]*Y),xe=te(),_e=te(),Te=te(),De=te(),Ue=te(),Ye=(ln,_n)=>{const Un=H.get(V1.computePosHash(_[_n])),Cs=Un.from,Xs=Un.to;if(!Cs||!Xs)return;me(xe,Cs),me(_e,_n),me(Te,Xs),Ke(De),Je(xe,_e)||(ft(Ue,_e,xe),qe(De,Ue)),Je(Te,_e)||(ft(Ue,Te,_e),ue(De,De,qe(Ue,Ue)));const rn=es(De);return rn>0?Fe(ln,De,1/rn):void 0};let nt=Number.POSITIVE_INFINITY;this.sortSubarray(M,F.min,F.max,(ln,_n)=>ln.featureInfo.featureIndex-_n.featureInfo.featureIndex);const it=te(),ut=te(),ot=te(),vt=te(),kt=te(),ls=te(),At=te(),qt=te(),ts=te(),ns=[te(),te(),te(),te()],Ps=[te(),te(),te(),te()],Ws=[{coord:new xs(0,0),height:0},{coord:new xs(0,0),height:0}],mn=(ln,_n)=>ln>_n;for(let ln=F.min;lnnt.featureInfo.featureIndex-it.featureInfo.featureIndex;this.sortSubarray(M,F.min,F.max,Y),this.sortSubarray(M,z.min,z.max,Y);const se=nt=>qe(nt,nt),me=[{coord:new xs(0,0),height:0},{coord:new xs(0,0),height:0}],xe=(nt,it)=>ntH.hash===Y.hash?Y.polygonIdx-H.polygonIdx:Y.hash>H.hash?1:-1);let C=0,M=0,F=0,z=_[C].polygonIdx;do M++,(M===_.length||_[C].hash!==_[M].hash)&&((M-C===1||_[M-1].polygonIdx!==z)&&(Fse.portalHashme.hash?H++:me.hash>se.portalHash?Y++:(se.type=me.type,H++)}}}isOnBorder(p,_){return p<=0&&_<=0||p>=Pr&&_>=Pr}addFeatureSection(p,_,C,M){return p!==_&&(_=p,C.push({featureIndex:p,vertexStart:M.getVertexCount()}),M.clearVertexLookup()),_}sortSubarray(p,_,C,M){const F=p.slice(_,C);F.sort(M),p.splice(_,F.length,...F)}static computeEdgeHash(p,_){return(p.y===_.y&&p.x>_.x||p.y>_.y)&&([p,_]=[_,p]),BigInt(V1.computePosHash(p))<<32n|BigInt(V1.computePosHash(_))}static computePosHash(p){return((65535&p.x)<<16|65535&p.y)>>>0}}class ams{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,_,C){return this.get(p,!0,_,C)}optional(p,_,C){return this.get(p,!1,_,C)}success(){return this._valid}get(p,_,C,M){const F=Object.hasOwn(this.feature.properties,p)?+this.feature.properties[p]:void 0;return this._valid&&F!==void 0&&!Number.isNaN(F)?C(M?M(F):F):_&&(this._valid=!1),this}}class iut{constructor(p,_){this.featureFunc=p,this.vertexFunc=_}parseFeature(p,_,C){return this.featureFunc(p,_,C)}parseVertex(p,_,C){return this.vertexFunc(p,_,C)}}const ims=new iut((N,p,_)=>N.reset(p).require(F3,C=>{_.id=C}).optional("fixed_height_relative",C=>{_.constantHeight=C},V3.decodeRelativeHeight).geometry(C=>{_.bounds=C},Fd).success(),(N,p,_)=>N.reset(p).require(F3,C=>{_.id=C}).require("elevation_idx",C=>{_.idx=C}).require("extent",C=>{_.extent=C}).require("height_relative",C=>{_.height=C},V3.decodeRelativeHeight).geometry(C=>{_.position=C},V3.getPoint).success()),oms=new iut((N,p,_)=>N.reset(p).require(F3,C=>{_.id=C}).optional("fixed_height",C=>{_.constantHeight=C},V3.decodeMetricHeight).geometry(C=>{_.bounds=C},Fd).success(),(N,p,_)=>N.reset(p).require(F3,C=>{_.id=C}).require("elevation_idx",C=>{_.idx=C}).require("extent",C=>{_.extent=C}).require("height",C=>{_.height=C},V3.decodeMetricHeight).geometry(C=>{_.position=C},V3.getPoint).success());class V3{static getPoint(p){return Cn(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"?oms:void 0:ims}static parse(p){const _=[],C=[],M=p.length,F=new ams;for(let z=0;z{return H.a0?Fe(Y,Y,1/se):fe(Y,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(p){if(this.edges.length===0)return;let _=0,C=Number.POSITIVE_INFINITY,M=0;const[F,z,H,Y,se,me,xe]=lms;Rr(xe,p.x,p.y);const _e=new whs(xe,null);for(let Te=0;Te0?Sn(Y,H)/ot:0,kt=ea(vt,0,1),ls=Math.abs((vt-kt)*this.edgeProps[Te].len);Hs(se,xe,Ye),Rr(me,Ue[1],-Ue[0]);const At=ls+Math.abs(Sn(se,me));At=0;--z){const H=this.edges[z].a,Y=this.edges[z].b,{position:se,height:me,extent:xe}=this.vertices[H],{position:_e,height:Te,extent:De}=this.vertices[Y],Ue=this.vertexProps[H].dir,Ye=this.vertexProps[Y].dir;if(fe(_,se[0]/p,se[1]/p,me),fe(C,_e[0]/p,_e[1]/p,Te),fe(M,Ue[1],-Ue[0],0),Fe(M,M,xe),fe(F,Ye[1],-Ye[0],0),Fe(F,F,De),this.distSqLines(ve(_[0]+.5*M[0],_[1]+.5*M[1],_[2]+.5*M[2]),ve(C[0]-.5*F[0],C[1]-.5*F[1],C[2]-.5*F[2]),ve(_[0]-.5*M[0],_[1]-.5*M[1],_[2]-.5*M[2]),ve(C[0]+.5*F[0],C[1]+.5*F[1],C[2]+.5*F[2]))<=.0025000000000000005)continue;const nt=this.vertices.length,it=ia(Ks(),se,_e);this.vertices.push({position:Br(it,it,.5),height:.5*(me+Te),extent:.5*(xe+De),index:.5*((this.vertices[H].index!==void 0?this.vertices[H].index:H)+(this.vertices[Y].index!==void 0?this.vertices[Y].index:Y))});const ut=ia(Ks(),Ue,Ye);this.vertexProps.push({dir:Wn(ut,ut)}),this.edges.splice(z,1),this.edgeProps.splice(z,1),this.edges.push({a:H,b:nt}),this.edges.push({a:nt,b:Y});const ot=Hs(Ks(),this.vertices[nt].position,se),vt=Ur(ot),kt={vec:ot,dir:Br(Ks(),ot,1/vt),len:vt};this.edgeProps.push(kt),this.edgeProps.push(kt)}}distSqLines(p,_,C,M){const F=be(te(),_,p),z=be(te(),M,C),H=be(te(),p,C),Y=ze(F,F),se=ze(F,z),me=ze(F,H),xe=ze(z,z),_e=ze(z,H),Te=Y*xe-se*se;if(Te===0)return Se(ht(F,C,M,ze(H,z)/ze(z,z)),p);const De=(Y*_e-se*me)/Te;return Se(ht(F,p,_,(se*_e-me*xe)/Te),ht(z,C,M,De))}static serialize(p,_){const C={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?(C.constantHeight=p.constantHeight,C):p.vertices.length===0?(C.vertices=[],C.vertexProps=[],C.edges=[],C.edgeProps=[],C):(C.vertices=p.vertices.map(F=>({position:Joe(F.position),height:F.height,extent:F.extent,index:F.index})),C.vertexProps=p.vertexProps.map(F=>({dir:Joe(F.dir)})),C.edges=p.edges.map(F=>({a:F.a,b:F.b})),C.edgeProps=p.edgeProps.map(F=>({vec:Joe(F.vec),dir:Joe(F.dir),len:F.len})),C)}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 H3(p.id,_,p.constantHeight);if(!p.vertices||p.vertices.length===0){const M=Object.create(H3.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 C=Object.create(H3.prototype);return C.id=p.id,C.constantHeight=void 0,C.heightRange={min:p.heightRange.min,max:p.heightRange.max},C.safeArea=_,C.vertices=p.vertices.map(M=>({position:ele(M.position),height:M.height,extent:M.extent,index:M.index})),C.vertexProps=(p.vertexProps||[]).map(M=>({dir:ele(M.dir)})),C.edges=(p.edges||[]).map(M=>({a:M.a,b:M.b})),C.edgeProps=(p.edgeProps||[]).map(M=>({vec:ele(M.vec),dir:ele(M.dir),len:M.len})),C}}class H9{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)*Pr,this.yOffset=(p.y*this.zScale-_.y)*Pr)}pointTransform(p){return Cn(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,_,C){const M=this.constantElevation(_,C);return M??(p.x=p.x*this.zScale+this.xOffset,p.y=p.y*this.zScale+this.yOffset,this.computeBiasedHeight(_.pointElevation(p),C))}computeBiasedHeight(p,_){return _<=0?p:p+_*pc(0,_,p>=0?p:Math.abs(.5*p))}}function cms(N){if(N===0)return[0,0,0];const p=ig(N);return[p(),p(),p()]}function lut(N,p){let _=0,C=N.length-1;for(;_<=C;){const M=_+C>>1;N[M].feature.idH.id===M);if(z&&C)return{tileId:C,feature:z}}if(!_||_.length===0)return;const F=lut(_,M);if(!(F<0)){if(C){for(let z=F;z<_.length&&_[z].feature.id===M;z++)if(_[z].tileId.key===C.key)return _[z]}return _[F]}}function dms(N,p){return N>p?1:N0))return _;_=_.left}}return null}contains(p){for(var _=this._root,C=this._compare;_;){var M=C(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 C=this.minNode(_.right);C.parent!==_&&(this.replace(C,C.right),C.right=_.right,C.right.parent=C),this.replace(_,C),C.left=_.left,C.left.parent=C}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 C=_.left,M=_.right,F=null;C&&(C.parent=null,F=this.maxNode(C),this.splay(F),this._root=F),M&&(C?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,C=[],M=!1,F=0;!M;)_?(C.push(_),_=_.left):C.length>0?(p(_=C.pop(),F++),_=_.right):M=!0;return this}range(p,_,C,M){const F=[],z=this._compare;let H,Y=this._root;for(;F.length!==0||Y;)if(Y)F.push(Y),Y=Y.left;else{if(Y=F.pop(),H=z(Y.key,_),H>0)break;if(z(Y.key,p)>=0&&C.call(M,Y))return this;Y=Y.right}return this}keys(){for(var p=this._root,_=[],C=[],M=!1;!M;)p?(_.push(p),p=p.left):_.length>0?(p=_.pop(),C.push(p.key),p=p.right):M=!0;return C}values(){for(var p=this._root,_=[],C=[],M=!1;!M;)p?(_.push(p),p=p.left):_.length>0?(p=_.pop(),C.push(p.data),p=p.right):M=!0;return C}at(p){for(var _=this._root,C=[],M=!1,F=0;!M;)if(_)C.push(_),_=_.left;else if(C.length>0){if(_=C.pop(),F===p)return _;F++,_=_.right}else M=!0;return null}load(p=[],_=[],C=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const M=p.length;return C&&EOe(p,_,0,M-1,this._compare),this._root=AOe(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,_,C,M,F){return new COe(C,F).load(p,_,M)}}function AOe(N,p,_,C,M){const F=M-C;if(F>0){const z=C+Math.floor(F/2),H={key:p[z],data:_[z],parent:N};return H.left=AOe(H,p,_,C,z),H.right=AOe(H,p,_,z+1,M),H}return null}function EOe(N,p,_,C,M){if(_>=C)return;const F=N[_+C>>1];let z=_-1,H=C+1;for(;;){do z++;while(M(N[z],F)<0);do H--;while(M(N[H],F)>0);if(z>=H)break;let Y=N[z];N[z]=N[H],N[H]=Y,Y=p[z],p[z]=p[H],p[H]=Y}EOe(N,p,_,H,M),EOe(N,p,H+1,C,M)}const cut=11102230246251565e-32,$b=134217729,ums=(3+8*cut)*cut;function TOe(N,p,_,C,M){let F,z,H,Y,se=p[0],me=C[0],xe=0,_e=0;me>se==me>-se?(F=se,se=p[++xe]):(F=me,me=C[++_e]);let Te=0;if(xese==me>-se?(z=se+F,H=F-(z-se),se=p[++xe]):(z=me+F,H=F-(z-me),me=C[++_e]),F=z,H!==0&&(M[Te++]=H);xese==me>-se?(z=F+se,Y=z-F,H=F-(z-Y)+(se-Y),se=p[++xe]):(z=F+me,Y=z-F,H=F-(z-Y)+(me-Y),me=C[++_e]),F=z,H!==0&&(M[Te++]=H);for(;xe0:(C[0]-p[0])*(_[1]-p[1])-(_[0]-p[0])*(C[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 W9(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 HC(N,p){return N[0]===p[0]&&N[1]===p[1]}function MOe(N,p,_){const C=function(M,F,z,H,Y,se){const me=(F-se)*(z-Y),xe=(M-Y)*(H-se),_e=me-xe;if(me===0||xe===0||me>0!=xe>0)return _e;const Te=Math.abs(me+xe);return Math.abs(_e)>=33306690738754716e-32*Te?_e:-function(De,Ue,Ye,nt,it,ut,ot){let vt,kt,ls,At,qt,ts,ns,Ps,Ws,mn,ln,_n,Un,Cs,Xs,rn,In,Pn;const $n=De-it,Rn=Ye-it,rr=Ue-ut,On=nt-ut;Cs=$n*On,ts=$b*$n,ns=ts-(ts-$n),Ps=$n-ns,ts=$b*On,Ws=ts-(ts-On),mn=On-Ws,Xs=Ps*mn-(Cs-ns*Ws-Ps*Ws-ns*mn),rn=rr*Rn,ts=$b*rr,ns=ts-(ts-rr),Ps=rr-ns,ts=$b*Rn,Ws=ts-(ts-Rn),mn=Rn-Ws,In=Ps*mn-(rn-ns*Ws-Ps*Ws-ns*mn),ln=Xs-In,qt=Xs-ln,G9[0]=Xs-(ln+qt)+(qt-In),_n=Cs+ln,qt=_n-Cs,Un=Cs-(_n-qt)+(ln-qt),ln=Un-rn,qt=Un-ln,G9[1]=Un-(ln+qt)+(qt-rn),Pn=_n+ln,qt=Pn-_n,G9[2]=_n-(Pn-qt)+(ln-qt),G9[3]=Pn;let Ar=function(oi,Fa){let Ai=Fa[0];for(let Ni=1;Ni<4;Ni++)Ai+=Fa[Ni];return Ai}(0,G9),or=22204460492503146e-32*ot;if(Ar>=or||-Ar>=or||(qt=De-$n,vt=De-($n+qt)+(qt-it),qt=Ye-Rn,ls=Ye-(Rn+qt)+(qt-it),qt=Ue-rr,kt=Ue-(rr+qt)+(qt-ut),qt=nt-On,At=nt-(On+qt)+(qt-ut),vt===0&&kt===0&&ls===0&&At===0)||(or=11093356479670487e-47*ot+ums*Math.abs(Ar),Ar+=$n*At+On*vt-(rr*ls+Rn*kt),Ar>=or||-Ar>=or))return Ar;Cs=vt*On,ts=$b*vt,ns=ts-(ts-vt),Ps=vt-ns,ts=$b*On,Ws=ts-(ts-On),mn=On-Ws,Xs=Ps*mn-(Cs-ns*Ws-Ps*Ws-ns*mn),rn=kt*Rn,ts=$b*kt,ns=ts-(ts-kt),Ps=kt-ns,ts=$b*Rn,Ws=ts-(ts-Rn),mn=Rn-Ws,In=Ps*mn-(rn-ns*Ws-Ps*Ws-ns*mn),ln=Xs-In,qt=Xs-ln,H1[0]=Xs-(ln+qt)+(qt-In),_n=Cs+ln,qt=_n-Cs,Un=Cs-(_n-qt)+(ln-qt),ln=Un-rn,qt=Un-ln,H1[1]=Un-(ln+qt)+(qt-rn),Pn=_n+ln,qt=Pn-_n,H1[2]=_n-(Pn-qt)+(ln-qt),H1[3]=Pn;const vr=TOe(4,G9,4,H1,dut);Cs=$n*At,ts=$b*$n,ns=ts-(ts-$n),Ps=$n-ns,ts=$b*At,Ws=ts-(ts-At),mn=At-Ws,Xs=Ps*mn-(Cs-ns*Ws-Ps*Ws-ns*mn),rn=rr*ls,ts=$b*rr,ns=ts-(ts-rr),Ps=rr-ns,ts=$b*ls,Ws=ts-(ts-ls),mn=ls-Ws,In=Ps*mn-(rn-ns*Ws-Ps*Ws-ns*mn),ln=Xs-In,qt=Xs-ln,H1[0]=Xs-(ln+qt)+(qt-In),_n=Cs+ln,qt=_n-Cs,Un=Cs-(_n-qt)+(ln-qt),ln=Un-rn,qt=Un-ln,H1[1]=Un-(ln+qt)+(qt-rn),Pn=_n+ln,qt=Pn-_n,H1[2]=_n-(Pn-qt)+(ln-qt),H1[3]=Pn;const Ga=TOe(vr,dut,4,H1,uut);Cs=vt*At,ts=$b*vt,ns=ts-(ts-vt),Ps=vt-ns,ts=$b*At,Ws=ts-(ts-At),mn=At-Ws,Xs=Ps*mn-(Cs-ns*Ws-Ps*Ws-ns*mn),rn=kt*ls,ts=$b*kt,ns=ts-(ts-kt),Ps=kt-ns,ts=$b*ls,Ws=ts-(ts-ls),mn=ls-Ws,In=Ps*mn-(rn-ns*Ws-Ps*Ws-ns*mn),ln=Xs-In,qt=Xs-ln,H1[0]=Xs-(ln+qt)+(qt-In),_n=Cs+ln,qt=_n-Cs,Un=Cs-(_n-qt)+(ln-qt),ln=Un-rn,qt=Un-ln,H1[1]=Un-(ln+qt)+(qt-rn),Pn=_n+ln,qt=Pn-_n,H1[2]=_n-(Pn-qt)+(ln-qt),H1[3]=Pn;const Wa=TOe(Ga,uut,4,H1,hut);return hut[Wa-1]}(M,F,z,H,Y,se,Te)}(N[0],N[1],p[0],p[1],_[0],_[1]);return C>0?-1:C<0?1:0}function oM(N,p){const _=N.point,C=p.point;return _[0]>C[0]?1:_[0]C[1]?1:-1:function(M,F,z){return M.left!==F.left?M.left?1:-1:MOe(z,M.otherEvent.point,F.otherEvent.point)!==0?M.isBelow(F.otherEvent.point)?-1:1:!M.isSubject&&F.isSubject?1:-1}(N,p,_)}function lM(N,p,_){const C=new W9(p,!1,N,N.isSubject),M=new W9(p,!0,N.otherEvent,N.isSubject);return HC(N.point,N.otherEvent.point)&&console.warn("what is that, a collapsed segment?",N),C.contourId=M.contourId=N.contourId,oM(M,N.otherEvent)>0&&(N.otherEvent.left=!0,M.left=!1),N.otherEvent.otherEvent=M,N.otherEvent=C,_.push(M),_.push(C),_}function tle(N,p){return N[0]*p[1]-N[1]*p[0]}function POe(N,p){return N[0]*p[0]+N[1]*p[1]}function IOe(N,p,_){const C=function(Y,se,me,xe){const _e=[se[0]-Y[0],se[1]-Y[1]],Te=[xe[0]-me[0],xe[1]-me[1]];function De(ls,At,qt){return[ls[0]+At*qt[0],ls[1]+At*qt[1]]}const Ue=[me[0]-Y[0],me[1]-Y[1]];let Ye=tle(_e,Te),nt=Ye*Ye;const it=POe(_e,_e);if(nt>0){const ls=tle(Ue,Te)/Ye;if(ls<0||ls>1)return null;const At=tle(Ue,_e)/Ye;return At<0||At>1?null:ls===0||ls===1?[De(Y,ls,_e)]:At===0||At===1?[De(me,At,Te)]:[De(Y,ls,_e)]}if(Ye=tle(Ue,_e),nt=Ye*Ye,nt>0)return null;const ut=POe(_e,Ue)/it,ot=ut+POe(_e,Te)/it,vt=Math.min(ut,ot),kt=Math.max(ut,ot);return vt<=1&&kt>=0?vt===1?[De(Y,vt>0?vt:0,_e)]:kt===0?[De(Y,kt<1?kt:1,_e)]:[De(Y,vt>0?vt:0,_e),De(Y,kt<1?kt:1,_e)]:null}(N.point,N.otherEvent.point,p.point,p.otherEvent.point),M=C?C.length:0;if(M===0||M===1&&(HC(N.point,p.point)||HC(N.otherEvent.point,p.otherEvent.point))||M===2&&N.isSubject===p.isSubject)return 0;if(M===1)return!HC(N.point,C[0])&&!HC(N.otherEvent.point,C[0])&&lM(N,C[0],_),!HC(p.point,C[0])&&!HC(p.otherEvent.point,C[0])&&lM(p,C[0],_),1;const F=[];let z=!1,H=!1;return HC(N.point,p.point)?z=!0:oM(N,p)===1?F.push(p,N):F.push(N,p),HC(N.otherEvent.point,p.otherEvent.point)?H=!0:oM(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&&lM(F[1].otherEvent,F[0].point,_),2):H?(lM(F[0],F[1].point,_),3):F[0]!==F[3].otherEvent?(lM(F[0],F[1].point,_),lM(F[1],F[2].point,_),3):(lM(F[0],F[1].point,_),lM(F[3].otherEvent,F[2].point,_),3)}function hms(N,p){if(N===p)return 0;if(MOe(N.point,N.otherEvent.point,p.point)!==0||MOe(N.point,N.otherEvent.point,p.otherEvent.point)!==0)return HC(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 oM(N,p)===1?1:-1}class mms{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function fms(N,p,_,C){let M,F=N+1,z=p[N].point;const H=p.length;for(FC;)F--;return F}function pms(N,p,_){const C=new mms;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(_),C.holeOf=H,C.depth=p[F].depth}else p[F].holeIds.push(_),C.holeOf=F,C.depth=p[F].depth+1}else C.holeOf=null,C.depth=p[F].depth}else C.holeOf=null,C.depth=0;return C}const fut=Math.max,put=Math.min;let sle=0;function gut(N,p,_,C,M,F){let z,H,Y,se,me,xe;for(z=0,H=N.length-1;z0?xe.left=!0:me.left=!0;const _e=Y[0],Te=Y[1];M[0]=put(M[0],_e),M[1]=put(M[1],Te),M[2]=fut(M[2],_e),M[3]=fut(M[3],Te),C.push(me),C.push(xe)}}const nle=[];function xut(N,p,_){let C=N,M=p;typeof N[0][0][0]=="number"&&(C=[N]),typeof p[0][0][0]=="number"&&(M=[p]);let F=function(_e,Te,De){let Ue=null;return _e.length*Te.length===0&&(De===0?Ue=nle:De===2?Ue=_e:(De===1||De===3)&&(Ue=_e.length===0?Te:_e)),Ue}(C,M,_);if(F)return F===nle?null:F;const z=[1/0,1/0,-1/0,-1/0],H=[1/0,1/0,-1/0,-1/0],Y=function(_e,Te,De,Ue,Ye){const nt=new Zw(void 0,oM);let it,ut,ot,vt,kt,ls;for(ot=0,vt=_e.length;otUe[2]||Ue[0]>De[2]||De[1]>Ue[3]||Ue[1]>De[3])&&(Ye===0?nt=nle:Ye===2?nt=_e:(Ye===1||Ye===3)&&(nt=_e.concat(Te))),nt}(C,M,z,H,_),F)return F===nle?null:F;const se=function(_e,Te,De,Ue,Ye,nt){const it=new COe(hms),ut=[],ot=Math.min(Ue[2],Ye[2]);let vt,kt,ls;for(;_e.length!==0;){let At=_e.pop();if(ut.push(At),nt===0&&At.point[0]>ot||nt===2&&At.point[0]>Ue[2])break;if(At.left){kt=vt=it.insert(At),ls=it.minNode(),vt=vt!==ls?it.prev(vt):null,kt=it.next(kt);const qt=vt?vt.key:null;let ts;if($Y(At,qt,nt),kt&&IOe(At,kt.key,_e)===2&&($Y(At,qt,nt),$Y(kt.key,At,nt)),vt&&IOe(vt.key,At,_e)===2){let ns=vt;ns=ns!==ls?it.prev(ns):null,ts=ns?ns.key:null,$Y(qt,ts,nt),$Y(At,qt,nt)}}else At=At.otherEvent,kt=vt=it.find(At),vt&&kt&&(vt=vt!==ls?it.prev(vt):null,kt=it.next(kt),it.remove(At),kt&&vt&&IOe(vt.key,kt.key,_e))}return ut}(Y,0,0,z,H,_),me=function(_e){let Te,De;const Ue=function(it){let ut,ot,vt,kt,ls;const At=[];for(ot=0,vt=it.length;ot{Ye[ls]=!0,ls=Ue.length)&&Ue[vt];);nt.push(ut)}return nt}(se),xe=[];for(let _e=0;_e0&&(M=xut(M,F,2)),vut(M,1/65536,.001)}function LOe(N,p=1){return[N.map(_=>_.map(C=>[C.x*p,C.y*p]))]}function yut(N,p){const _=Math.floor(N)+.5;return Math.abs(N-_)<=p?Math.round(_):Math.round(N)}class yms{constructor(p){this.xs=[],this.ys=[],this.ixs=[],this.iys=[],this.buckets=new Map,this.tolerance=p}canonicalize(p,_){const C=this.tolerance,M=Math.floor(p/C),F=Math.floor(_/C);for(let Y=-1;Y<=1;Y++){const se=this.buckets.get(M+Y);if(se)for(let me=-1;me<=1;me++){const xe=se.get(F+me);if(xe){for(const _e of xe)if(Math.abs(this.xs[_e]-p)<=C&&Math.abs(this.ys[_e]-_)<=C){const Te=this.ixs[_e],De=this.iys[_e];return this.xs[_e]===p&&this.ys[_e]===_||this.store(p,_,Te,De,M,F),[Te,De]}}}}const z=yut(p,C),H=yut(_,C);return this.store(p,_,z,H,M,F),[z,H]}store(p,_,C,M,F,z){const H=this.xs.length;this.xs.push(p),this.ys.push(_),this.ixs.push(C),this.iys.push(M);let Y=this.buckets.get(F);Y||(Y=new Map,this.buckets.set(F,Y));let se=Y.get(z);se||(se=[],Y.set(z,se)),se.push(H)}}function vut(N,p=1,_){const C=_!=null?new yms(_):null;return N.map(M=>M.map((F,z)=>{const H=F.map(Y=>{const se=Y[0]*p,me=Y[1]*p;if(C){const[xe,_e]=C.canonicalize(se,me);return new xs(xe,_e)}return new xs(Math.round(se),Math.round(me))});return z>0&&H.reverse(),H}))}class ROe{constructor(){this.frcCoverage=new Set,this.featureTriSegments=[],this.frcPerLevel=new Map,this.frcNonRoadSegments=new Li}empty(){return this.frcCoverage.size===0}}function but(N,p,_){if(N.frcCoverage.size===0||N.featureTriSegments.length===0)return;const C=_.get(),M=p.uint16,F=[];N.featureTriSegments.sort((xe,_e)=>xe.segIdx!==_e.segIdx?xe.segIdx-_e.segIdx:xe.frc===null&&_e.frc===null?0:xe.frc===null?-1:_e.frc===null?1:_e.frc-xe.frc);const z=new Map;let H=0,Y=N.featureTriSegments[0].frc,se={vertexOffset:C[H].vertexOffset,primitiveOffset:0,vertexLength:C[H].vertexLength,primitiveLength:0,vaos:{},sortKey:void 0};const me=()=>{se.primitiveLength>0&&(z.has(Y)||z.set(Y,[]),z.get(Y).push({...se}))};for(const xe of N.featureTriSegments){xe.segIdx!==H&&(me(),H=xe.segIdx,Y=xe.frc,se={vertexOffset:C[H].vertexOffset,primitiveOffset:F.length/3,vertexLength:C[H].vertexLength,primitiveLength:0,vaos:{},sortKey:void 0}),xe.frc!==Y&&(me(),Y=xe.frc,se={...se,primitiveOffset:F.length/3,primitiveLength:0});for(let _e=xe.start;_e0?F.length-1:0,frc:M})}buildFrcSegments(p){this.frcData&&!this.frcData.empty()&&but(this.frcData,p.bufferData.indexArray,p.bufferData.triangleSegments)}handleFeature(p,_,C,M,F,z){const H=new Array;if(!this.elevationMode)return!1;const Y=zY(p,F,void 0,M);if(!Y)return!1;{const me=this.clipPolygonsToTile(_,1);me.length>0&&H.push({polygons:me,elevationFeature:Y.feature,elevationTileID:Y.tileId})}const se={guardRailEnabled:z.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(p,{},M),featureIndex:C};for(const me of H)if(me.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new V1(me.elevationTileID,z.layers,z.zoom,z.lut));const _e=me.elevationFeature.isTunnel();let Te=0;Object.hasOwn(p.properties,idt)&&(Te=+p.properties[idt]),this.elevatedStructures.addPortalCandidates(me.elevationFeature.id,me.polygons,_e,me.elevationFeature,Te)}me.elevationFeature.constantHeight==null&&(me.polygons=this.prepareElevatedPolygons(me.polygons,me.elevationFeature,me.elevationTileID));const xe=new H9(M,me.elevationTileID);this.addElevatedGeometry(z,me.polygons,xe,me.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,C,se)}return!0}populatePaintArrays(p,_,C,M,F,z,H){this.elevationBufferData&&this.elevationBufferData.populatePaintArrays(p,_,C,M,F,z,H)}update(p,_,C,M,F,z,H,Y){this.elevationBufferData&&this.elevationBufferData.update(p,_,C,M,F,z,H,Y),this.elevatedStructures&&this.elevatedStructures.update(p,_,C,M,F,z,H,Y)}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,_,C,M,F,z){this.elevatedStructures&&(this.elevatedStructures.construct(p),this.elevatedStructures.populatePaintArrays(_,C,M,F,z))}addElevatedGeometry(p,_,C,M,F,z,H){const Y={elevation:M,elevationSampler:C,bias:F,index:z,featureInfo:H},[se,me]=p.addGeometry(_,this.elevationBufferData,Y,this.elevatedStructures);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:se,max:me}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,se),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,me))}prepareElevatedPolygons(p,_,C){const M=1/K(C),F=[];for(const z of p){const H=xms(z,new out(_,M),.1);F.push(...H)}return F}clipPolygonsToTile(p,_){const C=-_,M=-_,F=Pr+_,z=Pr+_;let H=0;const Y=[],se=[];for(;H=C&&Te.max.x<=F&&Te.min.y>=M&&Te.max.y<=z?Y:se).push(_e)}if(Y.length===p.length)return p;const me=[new xs(C,M),new xs(F,M),new xs(F,z),new xs(C,z),new xs(C,M)],xe=Y;for(const _e of se)xe.push(...gms(_e,me));return xe}}function bms(N,p){return N.nextPoint.sub(p.at(-2)).unit()}function _ms(N,p){return p[1].sub(N.prevPoint).unit()}oa(_ut,"FillHDExtension"),oa(V1,"ElevatedStructures");class wut{constructor(p,_){this.elevationEnabled=p,this.hasDeferredElevationFeatures=!1,_&&(this.frcData=new ROe)}isEmpty(){const p=!this.elevationEnabled||this.heightRange===void 0,_=!this.frcData||this.frcData.empty();return p&&_}trackFeatureFrc(p){if(!this.frcData)return null;const _=rle(p||{});return _!==null&&this.frcData.frcCoverage.add(_),_}recordFeatureRange(p,_,C,M){if(!this.frcData||C<=_)return;const F=p.segments.get();this.frcData.featureTriSegments.push({start:3*_,end:3*C,segIdx:F.length>0?F.length-1:0,frc:M})}buildFrcSegments(p){this.frcData&&!this.frcData.empty()&&but(this.frcData,p.indexArray,p.segments)}handleFeature(p,_,C,M,F,z,H,Y,se,me,xe){if(!this.elevationEnabled)return!1;if(!xe.terrainEnabled){const Ye=zY(p,M,F?F.registry:void 0,C),nt=p.properties!=null&&Object.hasOwn(p.properties,F3)&&!Number.isNaN(+p.properties[F3]);if(!Ye&&nt&&z&&(!F||!F.allProvidersReady))return this.hasDeferredElevationFeatures=!0,!0;if(Ye){let it=Ye.feature,ut=Ye.tileId;if(!Ye.tileId.equals(C)){const kt=this.mergedFeatureCache?this.mergedFeatureCache.get(it.id):void 0;if(kt)it=kt,ut=C;else{const ls=function(At,qt,ts){if(!At.properties||!qt||qt.length===0)return[];const ns=+At.properties[F3];if(Number.isNaN(ns))return[];const Ps=lut(qt,ns);if(Ps<0)return[];const Ws=[];for(let mn=Ps;mn1&&(it=function(At,qt){const ts=qt.slice().sort((Cs,Xs)=>Xs.tileId.z-Cs.tileId.z),ns=new xs(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),Ps=new xs(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY),Ws=[];for(const Cs of ts){const Xs=new H9(Cs.tileId,At);for(const In of Cs.feature.vertices)Ws.push({position:Xs.pointTransform(In.position),height:In.height,extent:In.extent,index:In.index});const rn=Cs.feature.safeArea;Q6[0]=rn.min.x,Q6[1]=rn.min.y,J6[0]=rn.max.x,J6[1]=rn.max.y,Xs.pointTransformInPlace(Q6),Xs.pointTransformInPlace(J6),ns.x=Math.min(ns.x,Q6[0],J6[0]),ns.y=Math.min(ns.y,Q6[1],J6[1]),Ps.x=Math.max(Ps.x,Q6[0],J6[0]),Ps.y=Math.max(Ps.y,Q6[1],J6[1])}const mn={min:ns,max:Ps};if(ts[0].feature.constantHeight!=null)return new H3(ts[0].feature.id,mn,ts[0].feature.constantHeight);Ws.sort((Cs,Xs)=>Cs.index-Xs.index);const ln=[];for(const Cs of Ws)ln.length!==0&&ln.at(-1).index===Cs.index||ln.push(Cs);const _n=[];for(let Cs=1;Cs>1,xe.layoutVertexArray.int16[6*ts+1]>>1),Ps=At.pointElevation(ns,it,.05);this.updateHeightRange(Ps),ts0?it.parentIndex:null)}return xe.fillNonElevatedRoadSegment(Te),!0}prepareElevatedLines(p,_,C,M){if(_.constantHeight!=null)return p;const F=[],z=1/K(M),H=C.equals(M)?null:new H9(C,M);for(const Y of p)Zus(Y,new out(_,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(wut,"LineHDExtension");class jut{constructor(){this.elevatedLayoutVertexArray=new Bs,this.hasElevation=!1}beginFeature(p,_,C){const M=zY(p,_,void 0,C);this.currentFeatureElevation=M?M.feature:void 0}writeVertexQuad(p,_){const C=this.currentFeatureElevation?this.currentFeatureElevation.pointElevation(new xs(p,_)):0;this.hasElevation=this.hasElevation||C!==0;for(let M=0;M<4;M++)this.elevatedLayoutVertexArray.emplaceBack(C)}finalize(){this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}upload(p){this.elevatedLayoutVertexArray&&!this.elevatedLayoutVertexBuffer&&(this.elevatedLayoutVertexBuffer=p.createVertexBuffer(this.elevatedLayoutVertexArray,ths.members))}destroy(){this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy()}}oa(jut,"CircleHDExtension");const ale=(N,p,_,C)=>{for(let M=0;M=this.elevationFeatures.length)return!1;const C=this.elevationFeatureTileIds[p];return C!=null&&!C.equals(_)}getRoadFeatureHeightAtAnchor(p,_,C){if(p===65535||p>=this.elevationFeatures.length)return null;const M=this.elevationFeatures[p],F=this.elevationFeatureTileIds[p];return F.equals(C)?M.pointElevation(_):this.getElevationFeatureSampler(C,F).pointElevation(new xs(_.x,_.y),M,0)}sampleRoadFeatureHeight(p,_,C){const M=this.getRoadFeatureHeightAtAnchor(p,_,C);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 C=!1;const M=K(_),F=1/M;let z=!1,H=!1;for(let Y=0;Y0||Te>0,nt=De>0,it=se.elevationFeatureIndex,ut=it=0&&ale(p.icon.orientationVertexArray,De,me,xe),vt>=0&&ale(p.icon.orientationVertexArray,Ue,me,xe)}}z||(p.text.orientationVertexArray=void 0),H||(p.icon.orientationVertexArray=void 0),C&&(p.zOffsetBuffersNeedUpload=!0,p.zOffsetSortDirty=!0)}getRoadFeatureHeightForPlacedSymbol(p,_,C,M,F){const z=p.symbolInstances.get(_.symbolInstanceIndices[C]);return this.getRoadFeatureHeightAtAnchor(z.elevationFeatureIndex,M,F)}getElevationFeatureForPlacedSymbol(p,_,C){const M=p.symbolInstances.get(_.symbolInstanceIndices[C]).elevationFeatureIndex;if(M{const De=this.getRoadFeatureHeightForPlacedSymbol(p,_,C,Te,M.canonical);return function(Ue,Ye,nt,it,ut,ot){const vt=it.upVector(Ye,nt.x,nt.y);return Fe(vt,vt,Ue*it.upVectorScale(Ye,ut,ot).metersToTile),[vt[0],vt[1],vt[2]]}(De!==null?De:0,M.canonical,Te,H,Y,se)},elevation:z,elevationFeature:null}:{getElevation:F,elevation:z,elevationFeature:xe}}}oa(Nut,"SymbolHDExtension",{omit:["consumerCanonical","elevationParams","crossSourceElevationEnabled","terrainEnabled","hasDeferredElevationFeatures","elevationFeatureIdToIndex"]});let Gk=null,ile=null,FOe=null,ole=null;const kut=5120,Sut=5121,Cut=5122,Aut=5123,Eut=5125,Tut=5126,K9={[kut]:Int8Array,[Sut]:Uint8Array,[Cut]:Int16Array,[Aut]:Uint16Array,[Eut]:Uint32Array,[Tut]:Float32Array},wms={[kut]:"DT_INT8",[Sut]:"DT_UINT8",[Cut]:"DT_INT16",[Aut]:"DT_UINT16",[Eut]:"DT_UINT32",[Tut]:"DT_FLOAT32"},Y9={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};function Mut(N,p,_){const C=_.json.bufferViews.length,M=_.buffers.length;p.bufferView=C,_.json.bufferViews[C]={buffer:M,byteLength:N.byteLength},_.buffers[M]=N}const OOe="KHR_draco_mesh_compression";function jms(N,p){const _=N.extensions&&N.extensions[OOe];if(!_)return;const C=new Gk.Decoder,M=Rut(p,_.bufferView),F=new Gk.Mesh;if(!C.DecodeArrayToMesh(M,M.byteLength,F))throw new Error("Failed to decode Draco mesh");const z=p.json.accessors[N.indices],H=K9[z.componentType],Y=z.count*H.BYTES_PER_ELEMENT,se=Gk._malloc(Y);H===Uint16Array?C.GetTrianglesUInt16Array(F,Y,se):C.GetTrianglesUInt32Array(F,Y,se),Mut(Gk.memory.buffer.slice(se,se+Y),z,p),Gk._free(se);for(const me of Object.keys(_.attributes)){const xe=C.GetAttributeByUniqueId(F,_.attributes[me]),_e=p.json.accessors[N.attributes[me]],Te=wms[_e.componentType],De=_e.count*Y9[_e.type]*K9[_e.componentType].BYTES_PER_ELEMENT,Ue=Gk._malloc(De);C.GetAttributeDataArrayForAllPoints(F,xe,Gk[Te],De,Ue),Mut(Gk.memory.buffer.slice(Ue,Ue+De),_e,p),Gk._free(Ue)}C.destroy(),F.destroy(),delete N.extensions[OOe]}const lle="EXT_meshopt_compression";function Nms(N,p){if(!N.extensions||!N.extensions[lle])return;const _=N.extensions[lle],C=new Uint8Array(p.buffers[_.buffer],_.byteOffset||0,_.byteLength||0),M=new Uint8Array(_.count*_.byteStride);FOe.decodeGltfBuffer(M,_.count,_.byteStride,C,_.mode,_.filter),N.buffer=p.buffers.length,N.byteOffset=0,p.buffers[N.buffer]=M.buffer,delete N.extensions[lle]}const Put=1179937895,Iut=new TextDecoder("utf8");function Lut(N,p){return new URL(N,p).href}async function kms(N,p,_,C,M){const F=await fetch(Lut(N.uri,C),{signal:M}),z=await F.arrayBuffer();p.buffers[_]=z}function Rut(N,p){const _=N.json.bufferViews[p];return new Uint8Array(N.buffers[_.buffer],_.byteOffset||0,_.byteLength)}async function Sms(N,p,_,C,M){if(N.uri){const F=Lut(N.uri,C),z=await fetch(F,{signal:M}),H=await z.blob(),Y=await createImageBitmap(H);p.images[_]=Y}else if(N.bufferView!==void 0){const F=Rut(p,N.bufferView),z=new Blob([F],{type:N.mimeType}),H=await createImageBitmap(z);p.images[_]=H}}async function Dut(N,p=0,_,C){const M={json:null,images:[],buffers:[]};if(new Uint32Array(N,p,1)[0]===Put){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(Iut.decode(Te.subarray(De,De+Ye))),De+=Ye,De>>0,Math.ceil(1.2*ut)),vt=Math.ceil((ot-ut)/65536);try{return Ue.grow(vt),Ye(),!0}catch{return!1}},b:nt}}).then(it=>{const{Rb:ut,Qb:ot,P:vt,T:kt,X:ls,Ja:At,La:qt,Qa:ts,Va:ns,Wa:Ps,eb:Ws,jb:mn,f:ln,e:_n,yb:Un,zb:Cs,Ab:Xs,Bb:rn,Db:In,Gb:Pn}=it.instance.exports;Ue=_n;const $n=(()=>{let Rn=0,rr=0,On=0,Ar=0;return or=>{On&&(ut(Ar),ut(Rn),rr+=On,On=Rn=0),Rn||(rr+=128,Rn=ot(rr));const vr=or.length+7&-8;let Ga=Rn;vr>=rr&&(On=vr,Ga=Ar=ot(vr));for(let Wa=0;Wa{Gk=Te,ile=null})),ile}()),_e&&me.push(function(){var Te;if(!FOe)return ole!=null||(ole=(Te=fetch(ct()),WebAssembly.instantiateStreaming(Te,{}).then(De=>{const{sbrk:Ue,memory:Ye,meshopt_decodeVertexBuffer:nt,meshopt_decodeIndexBuffer:it,meshopt_decodeIndexSequence:ut,meshopt_decodeFilterOct:ot,meshopt_decodeFilterQuat:vt,meshopt_decodeFilterExp:kt}=De.instance.exports,ls={ATTRIBUTES:nt,TRIANGLES:it,INDICES:ut},At={OCTAHEDRAL:ot,QUATERNION:vt,EXPONENTIAL:kt};return De.instance.exports.__wasm_call_ctors(),{decodeGltfBuffer(qt,ts,ns,Ps,Ws,mn){const ln=ts+3&-4,_n=Ue(ln*ns),Un=Ue(Ps.length),Cs=new Uint8Array(Ye.buffer);Cs.set(Ps,Un);const Xs=ls[Ws](_n,ts,ns,Un,Ps.length);if(Xs===0&&At[mn]&&At[mn](_n,ln,ns),qt.set(Cs.subarray(_n,_n+ts*ns)),Ue(_n-Ue(0)),Xs!==0)throw new Error(`Malformed buffer data: ${Xs}`)}}})).then(De=>{FOe=De,ole=null})),ole}()),z)for(let Te=0;Texe.cellIdx-_e.cellIdx||xe.triIdx-_e.triIdx);let me=0;for(;methis.max.x||this.min.x>p.x||p.y>this.max.y||this.min.y>p.y)return;const C=GC(p.x-this.min.x,this.xScale,this.cellsX),M=GC(p.y-this.min.y,this.yScale,this.cellsY),F=this.cells[M*this.cellsX+C];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=GC(p.x-this.min.x,this.xScale,this.cellsX),F=GC(_.x-this.min.x,this.xScale,this.cellsX),z=GC(p.y-this.min.y,this.yScale,this.cellsY),H=GC(_.y-this.min.y,this.yScale,this.cellsY);for(let Y=z;Y<=H;Y++)for(let se=M;se<=F;se++){const me=this.cells[Y*this.cellsX+se];if(me)for(let xe=0;xe0){const F=function(z,H){const Y=H.worldSize,se=Xd(1,0)*Y*T(H.center.lat,H.zoom)/oOe(Y),me=Xd(1,H.center.lat)*Y,xe=w([]);D(xe,xe,Yr(H.center.lng)),R(xe,xe,Yr(H.center.lat)),I(xe,xe,[0,0,pf]),P(xe,xe,[se,se,se*me]);const _e=H.point;return I(xe,xe,[-_e.x,-_e.y,0]),E(xe,xe,z),E(xe,H.globeMatrix,xe)}(N,p);return function(z,H,Y){const se=(De,Ue,Ye)=>{const nt=ce(De),it=ce(Ue),ut=$3(De,Ue,Ye);return Fe(ut,ut,1/ce(ut)*ya(nt,it,Ye))},me=se([z[0],z[1],z[2]],[H[0],H[1],H[2]],Y),xe=se([z[4],z[5],z[6]],[H[4],H[5],H[6]],Y),_e=se([z[8],z[9],z[10]],[H[8],H[9],H[10]],Y),Te=$3([z[12],z[13],z[14]],[H[12],H[13],H[14]],Y);return[me[0],me[1],me[2],0,xe[0],xe[1],xe[2],0,_e[0],_e[1],_e[2],0,Te[0],Te[1],Te[2],1]}(M,F,C)}return M}function BOe(N,p,_,C){const M=du.projectAabbCorners(C,_);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])&&(me=Te)}xe=me}while(xe!==se);return Y.length>0&&Y.push(Y[0]),Y}(M);if($Fe(N,z))return F}const eR=64,$Oe=["","wall","door","roof","window","lamp","logo"],Dms=[1,1,1];function hle(N,p,_,C,M,F,z,H,Y,se=!1){const me=_.zoom,xe=_.project(C),_e=T(C.lat,me),Te=1/_e;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 ot=0;_.elevation&&(ot=_.elevation.getAtPointOrZero(new Q(xe.x/Ye,xe.y/Ye),0));const vt=Ft([],[xe.x,xe.y,ot,1],_.projMatrix)[3]/_.cameraToCenterDistance;De=vt,Ue=vt*T(_.center.lat,me)}else if(_.projection.name==="globe"){const ot=ule(N,_),vt=[0,0,0,1];Ft(vt,vt,E([],_.projMatrix,ot));const kt=vt[3]/_.cameraToCenterDistance,ls=U3(me),At=_.projection.pixelsPerMeter(C.lat,Ye)*T(C.lat,me),qt=_.projection.pixelsPerMeter(_.center.lat,Ye)*T(_.center.lat,me);De=kt/ya(At,k(_.center.lat),ls),Ue=kt*_e/At,De*=qt,Ue*=qt}}else De=Te;P(N,N,[De,De,Ue]);const nt=[...N],it=p.orientation,ut=[];if($ut(ut,[it[0]+(M?M[0]:0),it[1]+(M?M[1]:0),it[2]+(M?M[2]:0)],F),E(N,nt,ut),H&&_.elevation){let ot=0;const vt=[];if(Y&&_.elevation){ot=function(ls,At,qt,ts,ns){const Ps=At.elevation;if(!Ps)return 0;const Ws=du.projectAabbCorners(qt,ts),mn=Xd(1,ns.lat)*At.worldSize,ln=function(On,Ar){const or=[0,0,1],vr=[{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 Ga of vr){const Wa=On[Ga.corners[0]],oi=On[Ga.corners[1]],Fa=On[Ga.corners[2]],Ai=[oi[0]-Wa[0],oi[1]-Wa[1],Ar*(oi[2]-Wa[2])],Ni=Ve(Ai,Ai,[Fa[0]-Wa[0],Fa[1]-Wa[1],Ar*(Fa[2]-Wa[2])]);qe(Ni,Ni),Ga.dotProductWithUp=ze(Ni,or)}return vr.sort((Ga,Wa)=>Ga.dotProductWithUp-Wa.dotProductWithUp),vr[0].corners}(Ws,mn),_n=Ws[ln[0]],Un=Ws[ln[1]],Cs=Ws[ln[2]],Xs=Ws[ln[3]],rn=Ps.getAtPointOrZero(new Q(_n[0]/At.worldSize,_n[1]/At.worldSize),0),In=Ps.getAtPointOrZero(new Q(Un[0]/At.worldSize,Un[1]/At.worldSize),0),Pn=Ps.getAtPointOrZero(new Q(Cs[0]/At.worldSize,Cs[1]/At.worldSize),0),$n=Ps.getAtPointOrZero(new Q(Xs[0]/At.worldSize,Xs[1]/At.worldSize),0),Rn=(rn+$n)/2,rr=(In+Pn)/2;return Rn>rr?In=p.gl.NEAREST_MIPMAP_NEAREST}),N.uploaded=!0,N.image=null)}function qut(N,p,_){N.indexBuffer=p.createIndexBuffer(N.indexArray,!1,!0),N.vertexBuffer=p.createVertexBuffer(N.vertexArray,Cms.members,!1,!0),N.normalArray&&(N.normalBuffer=p.createVertexBuffer(N.normalArray,Pms.members,!1,!0)),N.texcoordArray&&(N.texcoordBuffer=p.createVertexBuffer(N.texcoordArray,(N.texcoordArray.bytesPerElement===8?Tms:Mms).members,!1,!0)),N.colorArray&&(N.colorBuffer=p.createVertexBuffer(N.colorArray,(N.colorArray.bytesPerElement===12?Ams:Ems).members,!1,!0)),N.featureArray&&(N.featureBuffer=p.createVertexBuffer(N.featureArray,Lms.members,!1,!0)),N.segments=Li.simpleSegment(0,0,N.vertexArray.length,N.indexArray.length);const C=N.material;C.pbrMetallicRoughness.baseColorTexture&&qY(C.pbrMetallicRoughness.baseColorTexture,p),C.pbrMetallicRoughness.metallicRoughnessTexture&&qY(C.pbrMetallicRoughness.metallicRoughnessTexture,p),C.normalTexture&&qY(C.normalTexture,p),C.occlusionTexture&&qY(C.occlusionTexture,p,_),C.emissionTexture&&qY(C.emissionTexture,p)}function UOe(N,p,_){if(N.meshes)for(const C of N.meshes)qut(C,p,_);if(N.lodMeshes)for(const C of N.lodMeshes)qut(C,p,_);if(N.children)for(const C of N.children)UOe(C,p,_)}function Vut(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 mle(N){if(N.meshes)for(const p of N.meshes)Vut(p);if(N.lodMeshes)for(const p of N.lodMeshes)Vut(p);if(N.children)for(const p of N.children)mle(p)}function Hut(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 qOe(N){if(N.meshes)for(const p of N.meshes)Hut(p);if(N.lodMeshes)for(const p of N.lodMeshes)Hut(p);if(N.footprintDebugMesh&&(N.footprintDebugMesh.vertexBuffer.destroy(),N.footprintDebugMesh.indexBuffer.destroy(),N.footprintDebugMesh.segments.destroy()),N.children)for(const p of N.children)qOe(p)}function VOe(N,p,_,C){return N[0]<=C[0]&&p[0]>=_[0]&&N[1]<=C[1]&&p[1]>=_[1]&&N[2]<=C[2]&&p[2]>=_[2]}function Fms(N,p,_,C,M,F,z,H,Y,se,me){const xe=.5*(se[0]+me[0]),_e=.5*(se[1]+me[1]),Te=.5*(se[2]+me[2]),De=.5*(me[0]-se[0]),Ue=.5*(me[1]-se[1]),Ye=.5*(me[2]-se[2]),nt=N-xe,it=p-_e,ut=_-Te,ot=C-xe,vt=M-_e,kt=F-Te,ls=z-xe,At=H-_e,qt=Y-Te,ts=ot-nt,ns=vt-it,Ps=kt-ut,Ws=ls-ot,mn=At-vt,ln=qt-kt,_n=nt-ls,Un=it-At,Cs=ut-qt;let Xs,rn,In,Pn,$n,Rn;if(Xs=ut*ns-it*Ps,rn=kt*ns-vt*Ps,In=qt*ns-At*Ps,Pn=Math.min(Xs,rn,In),$n=Math.max(Xs,rn,In),Rn=Math.abs(Ps)*Ue+Math.abs(ns)*Ye,Pn>Rn||$n<-Rn||(Xs=ut*mn-it*ln,rn=kt*mn-vt*ln,In=qt*mn-At*ln,Pn=Math.min(Xs,rn,In),$n=Math.max(Xs,rn,In),Rn=Math.abs(ln)*Ue+Math.abs(mn)*Ye,Pn>Rn||$n<-Rn)||(Xs=ut*Un-it*Cs,rn=kt*Un-vt*Cs,In=qt*Un-At*Cs,Pn=Math.min(Xs,rn,In),$n=Math.max(Xs,rn,In),Rn=Math.abs(Cs)*Ue+Math.abs(Un)*Ye,Pn>Rn||$n<-Rn)||(Xs=nt*Ps-ut*ts,rn=ot*Ps-kt*ts,In=ls*Ps-qt*ts,Pn=Math.min(Xs,rn,In),$n=Math.max(Xs,rn,In),Rn=Math.abs(Ps)*De+Math.abs(ts)*Ye,Pn>Rn||$n<-Rn)||(Xs=nt*ln-ut*Ws,rn=ot*ln-kt*Ws,In=ls*ln-qt*Ws,Pn=Math.min(Xs,rn,In),$n=Math.max(Xs,rn,In),Rn=Math.abs(ln)*De+Math.abs(Ws)*Ye,Pn>Rn||$n<-Rn)||(Xs=nt*Cs-ut*_n,rn=ot*Cs-kt*_n,In=ls*Cs-qt*_n,Pn=Math.min(Xs,rn,In),$n=Math.max(Xs,rn,In),Rn=Math.abs(Cs)*De+Math.abs(_n)*Ye,Pn>Rn||$n<-Rn)||(Xs=it*ts-nt*ns,rn=vt*ts-ot*ns,In=At*ts-ls*ns,Pn=Math.min(Xs,rn,In),$n=Math.max(Xs,rn,In),Rn=Math.abs(ns)*De+Math.abs(ts)*Ue,Pn>Rn||$n<-Rn)||(Xs=it*Ws-nt*mn,rn=vt*Ws-ot*mn,In=At*Ws-ls*mn,Pn=Math.min(Xs,rn,In),$n=Math.max(Xs,rn,In),Rn=Math.abs(mn)*De+Math.abs(Ws)*Ue,Pn>Rn||$n<-Rn)||(Xs=it*_n-nt*Un,rn=vt*_n-ot*Un,In=At*_n-ls*Un,Pn=Math.min(Xs,rn,In),$n=Math.max(Xs,rn,In),Rn=Math.abs(Un)*De+Math.abs(_n)*Ue,Pn>Rn||$n<-Rn)||(Pn=Math.min(nt,ot,ls),$n=Math.max(nt,ot,ls),Pn>De||$n<-De)||(Pn=Math.min(it,vt,At),$n=Math.max(it,vt,At),Pn>Ue||$n<-Ue)||(Pn=Math.min(ut,kt,qt),$n=Math.max(ut,kt,qt),Pn>Ye||$n<-Ye))return!1;const rr=ns*ln-Ps*mn,On=Ps*Ws-ts*ln,Ar=ts*mn-ns*Ws,or=-(rr*nt+On*it+Ar*ut);return Rn=De*Math.abs(rr)+Ue*Math.abs(On)+Ye*Math.abs(Ar),!(Math.abs(or)>Rn)}const Oms=[];class Gut{serializeFromGltf(p,_,C,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 Y=0;for(let me=0;me0;){const F=C.pop(),z=this._nodes[F];if(z.aabbMax[2]<=M)continue;if(z.backChild===65535){for(let Te=0;Te=0?M:null}}function Wut(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 Z9(N,p){const _=N.json.bufferViews[p.bufferView],C=K9[p.componentType];return new C(N.buffers[_.buffer],(p.byteOffset||0)+(_.byteOffset||0),p.count*(_.byteStride&&_.byteStride!==Y9[p.type]*C.BYTES_PER_ELEMENT?_.byteStride/C.BYTES_PER_ELEMENT:Y9[p.type]))}function Kut(N,p,_,C){const M=Z9(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 Y=0;Y>>16|F[Y]<<16:F[Y],me=65535&se,xe=se>>>16;H=H<0&&(15&xe)==2?me:H,z.emplaceBack(me,xe)}C.featureArray=z,H>=0&&(C.doorVertexColor=H)}function HOe(N,p,_,C,M=!0){const F=K9[p.componentType],z=Y9[p.type],H=M?Wut(F):1,Y=N.json.bufferViews[p.bufferView],se=Y.byteStride?Y.byteStride/F.BYTES_PER_ELEMENT:z,me=p.count*se;for(let xe=0,_e=0;xe0){const it=p.json.accessors[M.TEXCOORD_0],ut=Z9(p,it);it.normalized&&K9[it.componentType]===Uint16Array?(F.texcoordArray=new si,F.texcoordArray.resizeExact(it.count),HOe(p,it,F.texcoordArray.uint16,ut,!1)):(F.texcoordArray=new Ko,F.texcoordArray.resizeExact(it.count),HOe(p,it,F.texcoordArray.float32,ut))}const Ye=!(!p.json.extensionsUsed||!p.json.extensionsUsed.includes("EXT_meshopt_compression"));M._FEATURE_ID_RGBA4444!==void 0&&Ye&&Kut(p,p.json.accessors[M._FEATURE_ID_RGBA4444],!1,F),M._FEATURE_RGBA4444!==void 0&&Kut(p,p.json.accessors[M._FEATURE_RGBA4444],!Ye,F),F.hasFeatureData=!!F.featureArray;const nt=N.material;return F.material=function(it,ut){const{emissiveFactor:ot=[0,0,0],alphaMode:vt="OPAQUE",alphaCutoff:kt=.5,normalTexture:ls,occlusionTexture:At,emissiveTexture:qt,doubleSided:ts,name:ns}=it,{baseColorFactor:Ps=[1,1,1,1],metallicFactor:Ws=1,roughnessFactor:mn=1,baseColorTexture:ln,metallicRoughnessTexture:_n}=it.pbrMetallicRoughness||{},Un=At?ut[At.index]:void 0;if(At&&At.extensions&&At.extensions.KHR_texture_transform&&Un){const Cs=At.extensions.KHR_texture_transform;Un.offsetScale=[Cs.offset[0],Cs.offset[1],Cs.scale[0],Cs.scale[1]]}return{name:ns,pbrMetallicRoughness:{baseColorFactor:new Ci(...Ps),metallicFactor:Ws,roughnessFactor:mn,baseColorTexture:ln?ut[ln.index]:void 0,metallicRoughnessTexture:_n?ut[_n.index]:void 0},doubleSided:ts,emissiveFactor:new Ci(...ot),alphaMode:vt,alphaCutoff:kt,normalTexture:ls?ut[ls.index]:void 0,occlusionTexture:Un,emissionTexture:qt?ut[qt.index]:void 0,defined:it.defined===void 0}}(nt!==void 0?p.json.materials[nt]:{defined:!1},_),F}function GOe(N,p,_){const{matrix:C,rotation:M,translation:F,scale:z,mesh:H,extras:Y,children:se,name:me}=N,xe={};if(xe.name=me,xe.localMatrix=C||function(_e,Te,De,Ue){var Ye=Te[0],nt=Te[1],it=Te[2],ut=Te[3],ot=Ye+Ye,vt=nt+nt,kt=it+it,ls=Ye*ot,At=Ye*vt,qt=Ye*kt,ts=nt*vt,ns=nt*kt,Ps=it*kt,Ws=ut*ot,mn=ut*vt,ln=ut*kt,_n=Ue[0],Un=Ue[1],Cs=Ue[2];return _e[0]=(1-(ts+Ps))*_n,_e[1]=(At+ln)*_n,_e[2]=(qt-mn)*_n,_e[3]=0,_e[4]=(At-ln)*Un,_e[5]=(1-(ls+Ps))*Un,_e[6]=(ns+Ws)*Un,_e[7]=0,_e[8]=(qt+mn)*Cs,_e[9]=(ns-Ws)*Cs,_e[10]=(1-(ls+ts))*Cs,_e[11]=0,_e[12]=De[0],_e[13]=De[1],_e[14]=De[2],_e[15]=1,_e}([],M||[0,0,0,1],F||[0,0,0],z||[1,1,1]),xe.globalMatrix=y(xe.localMatrix),H!==void 0){xe.meshes=_[H];const _e=xe.anchor=[0,0];for(const Te of xe.meshes){const{min:De,max:Ue}=Te.aabb;_e[0]+=De[0]+Ue[0],_e[1]+=De[1]+Ue[1]}_e[0]=Math.floor(_e[0]/xe.meshes.length/2),_e[1]=Math.floor(_e[1]/xe.meshes.length/2)}if(Y&&(Y.id&&(xe.id=Y.id),Y.lights&&(xe.lights=function(_e){if(!_e.length)return[];const Te=function(it){const ut=atob(it),ot=new Uint8Array(ut.length);for(let vt=0;vt=ut.length||Ye>=ut.length||nt>=ut.length||it>=ut.length)return null;const ot=ut[Ue],vt=ut[Ye],kt=ut[nt],ls=ut[it];if(ot.bufferView===void 0||vt.bufferView===void 0||kt.bufferView===void 0||ls.bufferView===void 0)return null;const At=_e.json.bufferViews;if(ot.bufferView>=At.length||vt.bufferView>=At.length||kt.bufferView>=At.length||ls.bufferView>=At.length)return null;const qt=At[ot.bufferView],ts=At[vt.bufferView],ns=At[kt.bufferView],Ps=At[ls.bufferView];if(qt.buffer>=_e.buffers.length||ts.buffer>=_e.buffers.length||ns.buffer>=_e.buffers.length||Ps.buffer>=_e.buffers.length)return null;const Ws=($n,Rn,rr)=>$n>=0&&$n<=rr&&Rn<=rr-$n,mn=ot.byteOffset||0,ln=vt.byteOffset||0,_n=kt.byteOffset||0,Un=ls.byteOffset||0;if(!(Ws(mn,0,qt.byteLength)&&Ws(ln,3*vt.count*4,ts.byteLength)&&Ws(_n,3*kt.count*4,ns.byteLength)&&Ws(Un,4*ls.count,Ps.byteLength)))return null;const Cs=new Uint8Array(_e.buffers[qt.buffer],(qt.byteOffset||0)+mn,qt.byteLength-mn),Xs=new Float32Array(_e.buffers[ts.buffer],(ts.byteOffset||0)+ln,3*vt.count),rn=new Float32Array(_e.buffers[ns.buffer],(ns.byteOffset||0)+_n,3*kt.count),In=new Uint32Array(_e.buffers[Ps.buffer],(Ps.byteOffset||0)+Un,ls.count),Pn=new Gut;if(Pn.serializeFromGltf(Cs,Xs,rn,In),De!==void 0&&_e.json.meshes&&_e.json.meshes[De]){const $n=_e.json.meshes[De].primitives[0];if($n&&$n.attributes.POSITION!==void 0&&$n.attributes.POSITION1&&C.at(-1).equals(C[0])&&C.pop();let M=0;for(let z=0;z0&&C.reverse();const F=ZT(C.flatMap(z=>[z.x,z.y]),[]);return F.length===0?null:{vertices:C,indices:F}}function Ums(N,p){const _=[],C=[];let M=0;const F=[];for(const z of N){M=_.length;const H=z.vertexArray.float32,Y=z.indexArray.uint16;for(let se=0;se0&&([C[z+1],C[z+2]]=[C[z+2],C[z+1]])}return{vertices:_,indices:C}}function Yut(N,p){for(let _=0;_0){const Ue=Array.from(De.values()).sort((Ye,nt)=>Ye-nt);for(let Ye=Ue.length-1;Ye>=0;Ye--)me.splice(Ue[Ye],1)}})(Y,H,N.json.nodes);const se=C?Yut(C,"LOD"):-1;if(se>=0){const me=C[se].nodes,xe=new Map;for(const _e of me){const Te=GOe(F[_e],N,_);Te.id&&xe.set(Te.id,Te)}for(const _e of Y)if(_e.id){const Te=xe.get(_e.id);Te&&Te.meshes&&(_e.lodMeshes=Te.meshes,Te.meshBVH&&(_e.meshBVH=Te.meshBVH))}}return Y}function qms(N){N.heightmap=new Float32Array(4096),N.heightmap.fill(-1);const p=N.vertexArray.float32,_=N.aabb.min[0]-1,C=N.aabb.min[1]-1,M=eR/(N.aabb.max[0]-_+2),F=eR/(N.aabb.max[1]-C+2);for(let z=0;zN.heightmap[se*eR+Y]&&(N.heightmap[se*eR+Y]=H)}}function Zut(N,p,_,C,M){_.reserve(_.length+4*N.length),C.reserve(C.length+10*N.length),M.reserve(M.length+10*N.length);let F=C.length;for(const z of N){const H=Math.min(10,Math.max(4,1.3*z.height))*p,Y=[-z.normal[1],z.normal[0],0],se=Math.min(.29,.1*z.width/z.depth),me=z.width-2*z.depth*p*(se+.01),xe=Ne([],z.pos,Y,me/2),_e=Ne([],z.pos,Y,-me/2),Te=[xe[0],xe[1],xe[2]+z.height],De=[_e[0],_e[1],_e[2]+z.height],Ue=Ne([],z.normal,Y,se);Fe(Ue,Ue,H);const Ye=Ne([],z.normal,Y,-se);Fe(Ye,Ye,H),ue(Ue,xe,Ue),ue(Ye,_e,Ye),xe[2]+=.1,_e[2]+=.1,C.emplaceBack(Ue[0],Ue[1],Ue[2]),C.emplaceBack(Ye[0],Ye[1],Ye[2]),C.emplaceBack(xe[0],xe[1],xe[2]),C.emplaceBack(_e[0],_e[1],_e[2]),C.emplaceBack(Te[0],Te[1],Te[2]),C.emplaceBack(De[0],De[1],De[2]),C.emplaceBack(xe[0],xe[1],xe[2]),C.emplaceBack(_e[0],_e[1],_e[2]),C.emplaceBack(Ue[0],Ue[1],Ue[2]),C.emplaceBack(Ye[0],Ye[1],Ye[2]);const nt=me/H/2;M.emplaceBack(-nt-se,-1,nt,.8),M.emplaceBack(nt+se,-1,nt,.8),M.emplaceBack(-nt,0,nt,1.3),M.emplaceBack(nt,0,nt,1.3),M.emplaceBack(nt+se,-.8,nt,.7),M.emplaceBack(nt+se,-.8,nt,.7),M.emplaceBack(0,0,nt,1.3),M.emplaceBack(0,0,nt,1.3),M.emplaceBack(nt+se,-1.2,nt,.8),M.emplaceBack(nt+se,-1.2,nt,.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 Vms(N,p,_){const C={};C.indexArray=new $r,C.vertexArray=new Dn,C.colorArray=new qr,C.indexArray.reserveExact(4*N.length),C.vertexArray.reserveExact(10*N.length),C.colorArray.reserveExact(10*N.length),Zut(N,p,C.indexArray,C.vertexArray,C.colorArray),C.featureArray=new si,C.featureArray.reserveExact(C.vertexArray.length);for(let z=0;z{z.push(new xs(xe,Y+(xe-H)/(se-H)*(me-Y)))}:(z,H,Y,se,me,xe)=>{z.push(new xs(H+(xe-Y)/(me-Y)*(se-H),xe))};for(const z of N){const H=[];for(const Y of z){if(Y.length<=2)continue;const se=[];for(let _e=0;_ep&&F(se,Te,De,Ue,Ye,p):nt>_?it<_&&F(se,Te,De,Ue,Ye,_):se.push(Y[_e]),it=p&&F(se,Te,De,Ue,Ye,p),it>_&&nt<=_&&F(se,Te,De,Ue,Ye,_)}let me=Y.at(-1);const xe=C===0?me.x:me.y;xe>=p&&xe<=_&&se.push(me),se.length&&(me=se.at(-1),se[0].x===me.x&&se[0].y===me.y||se.push(se[0]),H.push(se))}H.length&&M.push(H)}return M}const KOe=[new xs(0,0),new xs(Pr,0),new xs(Pr,Pr),new xs(0,Pr)];function Jut(N,p){const _=[];let C=[];if(!p||N.length<2)return[N];if(N.length===2)return R9(N[0],N[1],KOe)?[N]:[];for(let M=0;M0&&(C.length>1&&_.push(C),C=[])}return C.length>1&&_.push(C),_}const YOe=eM.types,ifs=["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"],ofs=["fill-extrusion-flood-light-ground-radius"],lfs=Math.pow(2,13),cfs=Math.pow(2,15)-1,ple=new xs(0,1),G3=2147483648,gle=1073741824;function VY(N,p,_,C,M,F,z,H){N.emplaceBack((p<<1)+z,(_<<1)+F,(Math.floor(C*lfs)<<1)+M,Math.round(H))}function HY(N,p,_){N.emplaceBack(p.x*Pr,p.y*Pr,_?1:0)}function xle(N,p,_,C,M,F){N.emplaceBack(p.x,p.y,(_.x<<1)+C,(_.y<<1)+M,F)}function GY(N,p,_){N.emplaceBack(p.x,p.y,p.z,_[0]*16384,_[1]*16384,_[2]*16384)}class eht{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class yle{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 C=p.data.length,M=new Uint32Array(4*C),F=[];F.length=C;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===Pr)&&_.x===C.x)!=((_.y===0||_.y===Pr)&&_.y===C.y)&&this.processBorderOverlap(_,C),M&&this.checkBorderIntersection(_,C)}checkBorderIntersection(p,_){_.x<0!=p.x<0&&this.addBorderIntersection(0,ya(_.y,p.y,(0-_.x)/(p.x-_.x))),_.x>Pr!=p.x>Pr&&this.addBorderIntersection(1,ya(_.y,p.y,(Pr-_.x)/(p.x-_.x))),_.y<0!=p.y<0&&this.addBorderIntersection(2,ya(_.x,p.x,(0-_.y)/(p.y-_.y))),_.y>Pr!=p.y>Pr&&this.addBorderIntersection(3,ya(_.x,p.x,(Pr-_.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 C=this.borders[p];_C[1]&&(C[1]=_)}processBorderOverlap(p,_){if(p.x===_.x){if(p.y===_.y)return;const C=p.x===0?0:1;this.addBorderIntersection(C,_.y),this.addBorderIntersection(C,p.y)}else{const C=p.y===0?2:3;this.addBorderIntersection(C,_.x),this.addBorderIntersection(C,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 tht(N,p){const _=N.add(p)._unit(),C=ea(N.x*_.x+N.y*_.y,-1,1);var M,F,z;return z=Math.acos(C),Math.min(4,Math.max(-4,Math.tan(z)))/4*cfs*((M=N).x*(F=p).y-M.y*F.x<0?-1:1)}const dfs=[N=>N.x<0,N=>N.x>Pr,N=>N.y<0,N=>N.y>Pr];function ufs(N,p,_,C){const M=[4];if(C===0)return M;_._mult(C);const F=N.sub(_),z=p.sub(_),H=[N,p,F,z];for(let Y=0;Y<4;Y++)for(const se of H)if(dfs[Y](se)){M.push(Y);break}return M}class XOe{constructor(p){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new Gn,this.indexArray=new $r,this.programConfigurations=new Hk(p.layers,{zoom:p.zoom,lut:p.lut},_=>ofs.includes(_)),this._segments=new Li,this.hiddenByLandmarkVertexArray=new mm,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Li}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(p,_,C,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 Y;z!==this._segments.get().length-1&&(z++,this._segmentToGroundQuads[z]=[],this._segmentToRegionTriCounts[z]=[0,0,0,0,0]);{const se=p[0],me=p[1];Y=tht(se.sub(p[F-1])._perp()._unit(),me.sub(se)._perp()._unit())}for(let se=0;seM.region-F.region);for(let C=0;C<_;C++){const M=this._segmentToGroundQuads[C],F=p[C],z=this._segmentToRegionTriCounts[C];z.reduce((Y,se)=>Y+se,0);let H=0;for(let Y=0;Y<=4;Y++){const se=z[Y];if(se!==0){let me=this.regionSegments[Y];me||(me=this.regionSegments[Y]=new Li);const xe={vertexOffset:F.vertexOffset,primitiveOffset:F.primitiveOffset+H,vertexLength:F.vertexLength,primitiveLength:se};me.get().push(xe)}H+=se}for(let Y=0;Y0?this.hiddenByLandmarkVertexBuffer=p.createVertexBuffer(this.hiddenByLandmarkVertexArray,nfs.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 _le{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 ble,this.footprintIndices=new $r,this.footprintVertices=new Gs,this.footprintSegments=new yle,this.layoutVertexArray=new Tn,this.centroidVertexArray=new nj,this.wallVertexArray=new id,this.indexArray=new $r,this.programConfigurations=new Hk(p.layers,{zoom:p.zoom,lut:p.lut},_=>ifs.includes(_)),this.segments=new Li,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.groundEffect=new XOe(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,_,C,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,C,M){this.features=[],this.hasPattern=V6("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(C),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:Y}of p){const se=this.layers[0]._featureFilter.needGeometry,me=_t(F,se);if(!this.layers[0]._featureFilter.filter(new Hn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),me,C))continue;const xe={id:z,sourceLayerIndex:Y,index:H,geometry:se?me.geometry:dt(F,C,M),properties:F.properties,type:F.type,patterns:{}},_e=this.layoutVertexArray.length,Te=YOe[xe.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:F.id,feature:xY("fill-extrusion",this.layers,xe,this.zoom,this.pixelRatio,_)});else if(this.wallMode)for(const De of xe.geometry)for(const Ue of Jut(De,Te))this.addFeature(F.id,xe,[Ue],H,C,{},_.availableImages,M,_.brightness);else this.addFeature(F.id,xe,xe.geometry,H,C,{},_.availableImages,M,_.brightness);_.featureIndex.insert(F,xe.geometry,H,Y,this.index,_e)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(p,_,C,M,F,z){for(const{featureId:H,feature:Y}of this.features){const se=YOe[Y.type]==="Polygon",{geometry:me}=Y;if(this.wallMode)for(const xe of me)for(const _e of Jut(xe,se))this.addFeature(H,Y,[_e],Y.index,_,C,M,F,z);else this.addFeature(H,Y,me,Y.index,_,C,M,F,z)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(p,_,C,M,F,z,H){this.programConfigurations.updatePaintArrays(p,_,F,C,M,z,H,this.worldview),this.groundEffect.update(p,_,F,C,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,afs),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.wallVertexBuffer=p.createVertexBuffer(this.wallVertexArray,sfs.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=p.createVertexBuffer(this.layoutVertexExtArray,rfs.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,tfs.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,_,C,M,F,z,H,Y,se){const me=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(_,{})/this.tileToMeter,xe=[new xs(0,0),new xs(Pr,Pr)],_e=Y.projection,Te=_e.name==="globe",De=this.wallMode||YOe[_.type]==="Polygon",Ue=new ZOe;Ue.centroidDataIndex=this.centroidData.length;const Ye=new vle;Ye.buildingId=p,_.properties&&Object.hasOwn(_.properties,"building_id")&&(Ye.buildingId=Number(_.properties.building_id)),Ue.buildingId=Ye.buildingId;const nt=this.layers[0].paint.get("fill-extrusion-base").evaluate(_,{},F)<=0,it=this.layers[0].paint.get("fill-extrusion-height").evaluate(_,{},F);let ut;if(Ye.height=it,Ye.vertexArrayOffset=this.layoutVertexArray.length,Ye.groundVertexArrayOffset=this.groundEffect.vertexArray.length,Te&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new pr),this.wallMode){if(Te)return void Yo("Non zero fill-extrusion-line-width is not yet supported on globe.");if(C.length!==1)return;ut=function(ts){const ns=ts[0].x===ts.at(-1).x&&ts[0].y===ts.at(-1).y;(function(rr){let On=0;const Ar=rr.length;for(let or=0;or=0})(ts)||(ts=ts.reverse());const Ws={geometry:[],joinNormals:[],indices:[]},mn=[],ln=[],_n=[];let Un=ts.length;for(;Un>=2&&ts[Un-1].equals(ts[Un-2]);)Un--;if(Un<(ns?3:2))return Ws;let Cs,Xs,rn,In,Pn,$n=0;for(;$n0;let Ga="miter";const Wa=2;Ga==="miter"&&or>Wa&&(Ga="bevel"),Ga==="bevel"&&(or>100&&(Ga="flipbevel"),or{const rl=new xs(Fa.x,Fa.y),Bl=new xs(Fa.x,Fa.y);rl.x+=Ai.x*Fo,rl.y+=Ai.y*Fo,Bl.x-=Ai.x*Math.max(Ni,1),Bl.y-=Ai.y*Math.max(Ni,1),_n.push(Ai),mn.push(rl),ln.push(Bl)};if(Ga==="miter")On._mult(or),oi(Cs,On,0,0);else if(Ga==="flipbevel")On=Pn.mult(-1),oi(Cs,On,0,0),oi(Cs,On.mult(-1),0,0);else{const Fa=-Math.sqrt(or*or-1),Ai=vr?Fa:0,Ni=vr?0:Fa;Xs&&oi(Cs,In,Ai,Ni),rn&&oi(Cs,Pn,Ai,Ni)}}Ws.geometry=[...mn,...ln.reverse(),mn[0]],Ws.joinNormals=[..._n,..._n.reverse(),_n.at(-1)];const Rn=Ws.geometry.length-1;for(let rr=0;rrts<(ns.length-1)/2||ts===ns.length-1,vt=this.wallMode?[C]:Pa(C,500);for(let ts=vt.length-1;ts>=0;ts--){const ns=vt[ts];(ns.length===0||ffs(ns[0]))&&vt.splice(ts,1)}let kt;if(Te)kt=lht(vt,xe,F);else{kt=[];for(const ts of vt)kt.push({polygon:ts,bounds:xe})}const ls=De?this.edgeRadius:0,At=ls>0&&this.zoom<17,qt=(ts,ns)=>{if(ts.length===0)return!1;const Ps=ts.at(-1);return ns.x===Ps.x&&ns.y===Ps.y};for(const{polygon:ts,bounds:ns}of kt){let Ps=0,Ws=0;for(const Un of ts)De&&!Un[0].equals(Un.at(-1))&&Un.push(Un[0]),Ws+=De?Un.length-1:Un.length;const mn=this.segments.prepareSegment((De?5:4)*Ws,this.layoutVertexArray,this.indexArray);Ye.footprintSegIdx<0&&(Ye.footprintSegIdx=this.footprintSegments.length),Ye.polygonSegIdx<0&&(Ye.polygonSegIdx=this.polygonSegments.length);const ln={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},_n=new eht;if(_n.vertexOffset=this.footprintVertices.length,_n.indexOffset=3*this.footprintIndices.length,_n.ringIndices=[],De){const Un=[],Cs=[];Ps=mn.vertexLength;for(let rn=0;rn4&&aht(Cs[Cs.length-2],Cs[0],Cs[1]),rn=ls?mfs(Cs[Cs.length-2],Cs[0],Cs[1],ls):0;const In=[];let Pn,$n,Rn;$n=Cs[1].sub(Cs[0])._perp()._unit();let rr=!0;for(let On=1,Ar=0;On0?1:0,Ai=or.dist(vr);if(Ar+Ai>32768&&(Ar=0),ls){Rn=wle(vr,Ga,$n);let Bl=nht(or,vr,Ga,QOe($n,Rn),ls);isNaN(Bl)&&(Bl=0);const bc=hfs(or,vr,new xs(0,0));or=or.add(bc.mult(rn))._round(),vr=vr.add(bc.mult(-Bl))._round(),rn=Bl,$n=Rn,nt&&this.zoom>=17&&(qt(In,or)||In.push(or),qt(In,vr)||In.push(vr))}const Ni=mn.vertexLength,Fo=Cs.length>4&&aht(or,vr,Ga);let rl=iht(Ar,Xs,rr);if(VY(this.layoutVertexArray,or.x,or.y,oi,Fa,0,0,rl),VY(this.layoutVertexArray,or.x,or.y,oi,Fa,0,1,rl),this.wallMode){const Bl=ot(On-1,Cs),bc=ut.joinNormals[On-1];HY(this.wallVertexArray,bc,Bl),HY(this.wallVertexArray,bc,Bl)}if(Ar+=Ai,rl=iht(Ar,Fo,!rr),Xs=Fo,VY(this.layoutVertexArray,vr.x,vr.y,oi,Fa,0,0,rl),VY(this.layoutVertexArray,vr.x,vr.y,oi,Fa,0,1,rl),this.wallMode){const Bl=ot(On,Cs),bc=ut.joinNormals[On];HY(this.wallVertexArray,bc,Bl),HY(this.wallVertexArray,bc,Bl)}if(mn.vertexLength+=4,this.indexArray.emplaceBack(Ni+0,Ni+1,Ni+2),this.indexArray.emplaceBack(Ni+1,Ni+3,Ni+2),mn.primitiveLength+=2,ls){const Bl=Ps+(On===1?Cs.length-2:On-2),bc=On===1?Ps:Bl+1;if(this.indexArray.emplaceBack(Ni+1,Bl,Ni+3),this.indexArray.emplaceBack(Bl,bc,Ni+3),mn.primitiveLength+=2,Pn===void 0&&(Pn=Ni),!JOe(Ga,Cs[On],ns)){const qm=On===Cs.length-1?Pn:mn.vertexLength;this.indexArray.emplaceBack(Ni+2,Ni+3,qm),this.indexArray.emplaceBack(Ni+3,qm+1,qm),this.indexArray.emplaceBack(Ni+3,bc,qm+1),mn.primitiveLength+=3}rr=!rr}if(Te){const Bl=this.layoutVertexExtArray,bc=_e.projectTilePoint(or.x,or.y,F),qm=_e.projectTilePoint(vr.x,vr.y,F),W0=_e.upVector(F,or.x,or.y),Zh=_e.upVector(F,vr.x,vr.y);GY(Bl,bc,W0),GY(Bl,bc,W0),GY(Bl,qm,Zh),GY(Bl,qm,Zh)}}De&&(Ps+=Cs.length-1),nt&&ls&&this.zoom>=17&&(In.length!==0&&qt(In,In[0])&&In.pop(),this.groundEffect.addData(In,ns,me,ls>0))}this.footprintSegments.push(_n),ln.triangleCount=this.indexArray.length-ln.triangleArrayOffset,this.polygonSegments.push(ln),++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?ple:this.encodeCentroid(Ue,Ye),_.properties&&Object.hasOwn(_.properties,"building_id")){const ts=Ye.buildingId;let ns=this.buildingGroups.get(ts);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(ts,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 ts=this.featuresOnBorder.length-1;for(let ns=0;nsthis.featuresOnBorder[_].borders[p][0]-this.featuresOnBorder[C].borders[p][0])}splitToSubtiles(){const p=[];for(let H=0;HPr),me=2*se+(+(Y.min.x+Y.max.x>Pr)^se);for(let xe=0;xeH.triangleSegmentIdx===Y.triangleSegmentIdx?H.subtile-Y.subtile:H.triangleSegmentIdx-Y.triangleSegmentIdx);let C=0,M=0,F=0;for(const H of p){if(H.triangleSegmentIdx!==C)break;F++}const z=p.length;for(;M!==p.length;){C=p[M].triangleSegmentIdx;let H=0,Y=M,se=M;for(let me=Y;me0&&this.triangleSubSegments.push({segment:Te,min:xe,max:_e}),Y=se;for(let De=Y;De[ya(Ue[0],Ye[0],nt[0]),ya(Ue[1],Ye[1],nt[1])],Te=[],De=[];for(const Ue of this.triangleSubSegments){Te[0]=Ue.min.x/Pr,Te[1]=Ue.min.y/Pr,De[0]=Ue.max.x/Pr,De[1]=Ue.max.y/Pr;const Ye=_e(me,xe,Te),nt=_e(me,xe,De);if(new du([Ye[0],Ye[1],F],[nt[0],nt[1],z]).intersectsPrecise(C)===0){se&&(M.segments.push(se),se=void 0);continue}const it=Ue.segment;se&&se.vertexOffset!==it.vertexOffset&&(M.segments.push(se),se=void 0),se?(se.vertexLength+=it.vertexLength,se.primitiveLength+=it.primitiveLength):se={vertexOffset:it.vertexOffset,primitiveLength:it.primitiveLength,vertexLength:it.vertexLength,primitiveOffset:it.primitiveOffset,sortKey:void 0,vaos:{}}}return se&&M.segments.push(se),M}encodeCentroid(p,_){const C=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(ea(C.x,1,8191)<<3|F,ea(C.y,1,8191)<<3|z)}encodeBorderCentroid(p){if(!p.borders)return new xs(0,0);const _=p.borders,C=Number.MAX_VALUE;if(_[0][0]!==C||_[1][0]!==C){const M=_[0][0]!==C?0:1;return new xs(6|(_[0][0]!==C?0:65528),(_[M][0]+_[M][1])/2<<3|6)}{const M=_[2][0]!==C?2:3;return new xs((_[M][0]+_[M][1])/2<<3|6,6|(_[2][0]!==C?0:65528))}}showCentroid(p,_){const C=this.centroidData.get(p.centroidDataIndex);if(C.flags&=G3,_!=="keep"||7&~C.centroidXY.y){if(C.groupCentroidPos.x!==0||C.groupCentroidPos.y!==0){const M=C.span(),F=Math.min(7,Math.round(M.x*this.tileToMeter/10)),z=Math.min(6,Math.round(M.y*this.tileToMeter/10));C.centroidXY=new xs(ea(C.groupCentroidPos.x,1,8191)<<3|F,ea(C.groupCentroidPos.y,1,8191)<<3|z)}else C.centroidXY=new xs(0,0);this.writeCentroidToBuffer(C)}else this.writeCentroidToBuffer(C)}writeCentroidToBuffer(p){this.groundEffect.updateHiddenByLandmark(p);const _=p.vertexArrayOffset,C=p.vertexCount+p.vertexArrayOffset,M=-1073741824&p.flags?ple:p.centroidXY,F=this.centroidVertexArray.geta_centroid_pos0(_);if(this.centroidVertexArray.geta_centroid_pos1(_)!==M.y||F!==M.x){for(let z=_;zY.max.x||Y.min.x>z.max.x||z.min.y>Y.max.y||Y.min.y>z.max.y||z.footprint.buildingIds.has(Y.buildingId)&&(Y.flags|=z.clipMask!==MY.None?-1073741824:G3);else for(const Y of this.centroidData)if(!(Y.flags&G3||Y.flags&gle||z.min.x>Y.max.x||Y.min.x>z.max.x||z.min.y>Y.max.y||Y.min.y>z.max.y))for(let se=0;se_!=Te>_&&p<(this.footprintVertices.int16[2*(me+z.vertexOffset)+0]-xe)*(_-_e)/(Te-_e)+xe&&(M=!M)}H=Y}}return M}getHeightAtTileCoord(p,_){let C=Number.NEGATIVE_INFINITY,M=!0;const F=4*(p+Pr)*Pr+(_+Pr);if(Object.hasOwn(this.partLookup,F)){const Y=this.partLookup[F];return Y?{height:Y.height,hidden:!!(Y.flags&G3)}:void 0}const z=this.centroidData.buffer,H=this.centroidData.length;for(let Y=0;Yz[se+4]||z[se+2]>p||_>z[se+5]||z[se+3]>_)continue;const me=z[se+13];if(me<=C)continue;const xe=this.centroidData.get(Y);this.footprintContainsPoint(p,_,xe)&&(C=me,this.partLookup[F]=xe,M=!!(xe.flags&G3))}if(C!==Number.NEGATIVE_INFINITY)return{height:C,hidden:M};this.partLookup[F]=void 0}}function hfs(N,p,_){return N.equals(p)?_:p.sub(N)._unit()}function wle(N,p,_){return N.equals(p)?_:p.sub(N)._perp()._unit()}function sht(N,p){const _=N.add(p),C=_.mag();return C===0?N:_.div(C)}function QOe(N,p){const _=sht(N,p);return N.x*_.x+N.y*_.y}function mfs(N,p,_,C){let M,F;return N.equals(p)?(F=wle(p,_,new xs(0,0)),M=F):(M=p.sub(N)._perp()._unit(),F=wle(p,_,M)),nht(N,p,_,QOe(M,F),C)}function nht(N,p,_,C,M){const F=Math.sqrt(1-C*C);return Math.min(N.dist(p)/3,p.dist(_)/3,M*F/C)}function JOe(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 rht(N,p){return N.xp[1].x||N.yp[1].y}function ffs(N){return N.every(p=>p.x<=0)||N.every(p=>p.x>=Pr)||N.every(p=>p.y<=0)||N.every(p=>p.y>=Pr)}function aht(N,p,_){if(N.x<0||N.x>=Pr||p.x<0||p.x>=Pr||_.x<0||_.x>=Pr)return!1;const C=_.sub(p),M=C.perp(),F=N.sub(p);return(C.x*F.x+C.y*F.y)/Math.sqrt((C.x*C.x+C.y*C.y)*(F.x*F.x+F.y*F.y))>-.866&&M.x*F.x+M.y*F.y<0}function iht(N,p,_){const C=p?2|N:-3&N;return _?1|C:-2&C}function oht(){const N=Math.PI/32,p=Math.tan(N),_=JT;return _*Math.sqrt(1+2*p*p)-_}function lht(N,p,_){const C=1<<_.z,M=Rx(_.x/C),F=Rx((_.x+1)/C),z=$d(_.y/C),H=$d((_.y+1)/C);return function(Y,se,me,xe,_e=0,Te){const De=[];if(!Y.length||!me||!xe)return De;const Ue=(kt,ls)=>{for(const At of kt)De.push({polygon:At,bounds:ls})},Ye=Math.ceil(Math.log2(me)),nt=Math.ceil(Math.log2(xe)),it=Ye-nt,ut=[];for(let kt=0;kt0?0:1);for(let kt=0;ktls+1?vt.push({polygons:mn,bounds:_n,depth:ls+1}):Ue(mn,_n)}if(ln.length){const _n=[new xs(At===0?Ws:qt.x,At===1?Ws:qt.y),ts];ut.length>ls+1?vt.push({polygons:ln,bounds:_n,depth:ls+1}):Ue(ln,_n)}}return De}(N,p,Math.ceil((F-M)/11.25),Math.ceil((z-H)/11.25),1,(Y,se,me)=>{if(Y===0)return .5*(se+me);{const xe=$d((_.y+se/Pr)/C);return(rp(.5*($d((_.y+me/Pr)/C)+xe))*C-_.y)*Pr}})}function pfs(N,p,_,C,M,F){const z=Math.pow(2,C.z-M.z);for(let H=0;H<_;H++){let Y=N.int16[2*(H+p)+0],se=N.int16[2*(H+p)+1];Y=(Y+M.x*Pr)*z-C.x*Pr,se=(se+M.y*Pr)*z-C.y*Pr,F.push(new xs(Y,se))}}oa(_le,"FillExtrusionBucket",{omit:["layers","features"]}),oa(vle,"PartData"),oa(ble,"PartDataArray"),oa(yle,"FootprintSegmentArray"),oa(ZOe,"BorderCentroidData"),oa(XOe,"GroundEffect");const e8e=4096;class gfs{constructor(p){this.module=p,this.memoryStack=this.module.malloc(e8e),this.memoryStackNextFree=this.memoryStack}createIntArray(p){const _=this.memoryStackNextFree;return this.memoryStackNextFree+=p.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>e8e?-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>e8e?-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,_,C){this.module.setFauxFacadeOptions(p?1:0,_?1:0,C)}setFacadeClassifierOptions(p){this.module.setFacadeClassifierOptions(p)}generateMesh(p,_){this.memoryStackNextFree=this.memoryStack;for(const H of p){const Y=this.createIntArray(H.ringIndices),se=this.createFloatArray(H.coordinates);if(Y===-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,Y,H.ringIndices.length-1)}for(const H of _){let Y;Y=H.entrances?JSON.parse(H.entrances):[];const se=this.createFloatArray(Y),me=this.createFloatArray(H.coordinates);if(se===-1||me===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(H.sourceId,H.crossPerc,H.distanceToRoad,se,Y.length,me,H.coordinates.length)}if(!this.module.generateMesh()){const H=this.module.getLastError();return this.readStringBuffer(H)}const C=this.module.getMeshCount(),M=new Array(C);for(let H=0;H_||M.y<-p||M.y>_)return!1;return!0}function yfs(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 dht,uht,X9=null,hht=null,oj=null;class t8e{constructor(){this.layoutVertexArray=new Dn,this.layoutAttenuationArray=new qr,this.layoutColorArray=new si,this.indexArray=new $r,this.indexArrayForConflation=new $r,this.segmentsBucket=new Li}}class s8e{constructor(p){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Li,this.entranceBloom=new t8e;const _=66560;this.layoutVertexArray=new Dn,this.layoutVertexArray.reserve(_),this.layoutNormalArray=new Ls,this.layoutNormalArray.reserve(_),this.layoutCentroidArray=new Ls,this.layoutCentroidArray.reserve(_),this.layoutColorArray=new si,this.layoutColorArray.reserve(_),this.layoutFloodLightDataArray=new Vl,this.layoutFloodLightDataArray.reserve(_),this.layoutAOArray=new mm,this.layoutAOArray.reserve(_),this.indexArray=new $r,this.indexArray.reserve(66560),this.indexArrayForConflation=new $r,this.segmentsBucket=new Li,this.entranceBloom=new t8e,p&&(this.layoutFacadePaintArray=new si,this.layoutFacadeDataArray=new kn,this.layoutFacadeVerticalRangeArray=new si)}reserve(p,_,C){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(_),C&&(this.layoutFacadePaintArray.reserveForAdditional(p),this.layoutFacadeDataArray.reserveForAdditional(p),this.layoutFacadeVerticalRangeArray.reserveForAdditional(p))}}class mht{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 _d,this.footprintsMin=new xs(1/0,1/0),this.footprintsMax=new xs(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new s8e(!1),this.buildingWithFacade=new s8e(!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 Hk(p.layers,{zoom:p.zoom,lut:p.lut}),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.projection=p.projection,this.groundEffect=new XOe(p),this.groundEffect.groundRadiusArray=new Bs,this.hasAppearances=null}updateFootprints(p,_){const C=new cle([],[],1),M={vertices:[],indices:new Uint32Array(0),grid:C,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};_.push({footprint:M,id:p})}updateAppearances(p,_,C,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,C,M){if(!oj)return;const F=K(C);this.tileToMeter=F,this.brightness=_.brightness,oj.setStyle({normalScale:[1,-1,F],tileToMeters:F}),oj.setAOOptions(!1,.3),oj.setMetricOptions(!1,16),oj.setStructuralOptions(!0),oj.setFacadeClassifierOptions(3);const z=new Map,H=new Map;let Y=0;for(const{feature:Ye}of p){if(cht[Ye.type]!=="LineString"){z.set(Ye.id,Ye.properties.source_id);continue}const nt=this.layers[0]._featureFilter.needGeometry;if(nt&&!this.layers[0]._featureFilter.filter(new Hn(this.zoom),Ye,C))continue;const it=_t(Ye,nt);if(!nt&&!this.layers[0]._featureFilter.filter(new Hn(this.zoom),it,C))continue;const ut=nt?it.geometry:dt(Ye,C,M),ot=[];for(const At of ut)for(const qt of At)ot.push(qt.x),ot.push(qt.y);const vt={coordinates:ot,crossPerc:Ye.properties.cross_perc,distanceToRoad:Ye.properties.distance_to_road,entrances:Ye.properties.entrances,sourceId:0},kt=Ye.properties.source_id;let ls=H.get(kt);ls||(ls=[],H.set(kt,ls)),ls.push(vt),++Y}this.maxHeight=0;const se=new Array,me=new Set,xe=Ye=>{Ye!=null&&me.add(Ye)},_e=(Ye,nt)=>{Ye!=null&&se.push({buildingId:Ye,footprintIndex:nt})},Te=64*(p.length-Y),De=Te/2;this.buildingWithFacade.reserve(Te,De,!0),this.buildingWithoutFacade.reserve(2*Te,2*De,!1),this.footprintsIndices.reserve(16*(p.length-Y)),this.footprintsVertices.reserve(8*(p.length-Y));for(const{feature:Ye,id:nt,index:it,sourceLayerIndex:ut}of p){if(cht[Ye.type]==="LineString")continue;const ot=this.layers[0]._featureFilter.needGeometry;if(ot&&!this.layers[0]._featureFilter.filter(new Hn(this.zoom),Ye,C))continue;let vt=null;if(Ye.properties&&Object.hasOwn(Ye.properties,"building_id")&&(vt=Number(Ye.properties.building_id),me.has(vt)))continue;const kt=_t(Ye,ot);if(!ot&&!this.layers[0]._featureFilter.filter(new Hn(this.zoom),kt,C))continue;const ls=ot?kt.geometry:dt(Ye,C,M),At=Pa(ls,500);let qt=!1;for(const wo of At)if(wo.length!==1){qt=!0;break}if(qt){xe(vt);continue}if(!xfs(ls,163)){xe(vt);continue}const ts=this.layers[0],ns=yfs(ts.layout.get("building-roof-shape").evaluate(Ye,{},C)),Ps=ts.layout.get("building-base").evaluate(Ye,{},C),Ws=ts.layout.get("building-height").evaluate(Ye,{},C),mn=ts.layout.get("building-flood-light-ground-radius").evaluate(Ye,{},C),ln=ts.paint.get("building-ambient-occlusion-intensity"),_n=mn/this.tileToMeter;Ye.properties["building-part"]="roof";const Un=ts.paint.get("building-color").evaluate(Ye,{},this.canonical).toPremultipliedRenderColor(this.lut),Cs=ts.paint.get("building-emissive-strength").evaluate(Ye,{},this.canonical);Ye.properties["building-part"]="wall";const Xs=ts.paint.get("building-color").evaluate(Ye,{},this.canonical).toPremultipliedRenderColor(this.lut),rn=ts.paint.get("building-emissive-strength").evaluate(Ye,{},this.canonical);Ye.properties["building-part"]="window";const In=ts.paint.get("building-color").evaluate(Ye,{},this.canonical).toPremultipliedRenderColor(this.lut),Pn=ts.paint.get("building-emissive-strength").evaluate(Ye,{},this.canonical);Ye.properties["building-part"]="door";const $n=ts.paint.get("building-color").evaluate(Ye,{},this.canonical).toPremultipliedRenderColor(this.lut),Rn=ts.paint.get("building-emissive-strength").evaluate(Ye,{},this.canonical);let rr=ts.layout.get("building-flood-light-wall-radius").evaluate(Ye,{},C);rr=ea(rr,0,2048);const On=rr/2048*jle,Ar=z.get(nt),or=H.get(Ar)||[],vr=or.length!==0&&ts.layout.get("building-facade").evaluate(Ye,{},C);oj.setFacadeOptions(4,!0),oj.setFauxFacadeOptions(vr,!1,1);let Ga=0,Wa=0,oi=0,Fa=0,Ai=0,Ni=0,Fo=0,rl=0,Bl=0,bc=0,qm=0;if(vr){let wo=Math.round(ts.layout.get("building-facade-floors").evaluate(Ye,{},C));if(Ps===0){wo=Math.max(1,wo-(or.length>0?1:0));let Tu=4;if(Ws>100){const Hm=[10,13,15];Tu=Hm[Ye.id?Ye.id%Hm.length:0]}else Ws<=10&&(Tu=3);oj.setFacadeOptions(Tu,!0),Ai=(Ws<15?1.3:1.61803)*Tu/F}else Ai=Ps/F;Ni=Ws/F,Ai=Math.min(Ai,Ni),oi=ts.layout.get("building-facade-unit-width").evaluate(Ye,{},C)/F,Fa=(Ni-Ai)/wo,oj.setFauxFacadeOptions(!0,!0,oi);const mg=ts.layout.get("building-facade-window").evaluate(Ye,{},C);Ga=mg[0],Wa=mg[1],Fo=Math.floor(65535*Math.min(1,Ai/Pr)),rl=Math.floor(65535*Math.min(1,Ni/Pr)),Bl=Math.floor(255*Ga)<<8|Math.floor(255*Wa),bc=Math.floor(65535*Math.min(1,oi/Pr)),qm=Math.floor(65535*Math.min(1,Fa/Pr))}const W0=Array(At.length),Zh={x:1/0,y:1/0},_l={x:-1/0,y:-1/0},qd={x:0,y:0};let hh=0;for(let wo=0;wo0){const Tu=[],Hm=Array(mg.length+1);Hm[0]=0;for(let K_=0;K_Pr||Zh.y<0||_l.y>Pr)&&this.featuresOnBorder.push({featureId:Ye.id,footprintIndex:this.footprints.length});{const wo=ZT(Yk,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+wo.length),this.footprintsIndices.uint16.set(wo,Vb),this.buildingIds.add(vt??Ye.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,W_.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,W_.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,K0.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,K0.y);const mg={footprintVertexOffset:hg,footprintVertexLength:this.footprintsVertices.length-hg,footprintIndexOffset:Vb,footprintIndexLength:this.footprintsIndices.length-Vb,min:W_,max:K0,hiddenFlags:0,indicesOffset:wy,indicesLength:qb,bloomIndicesOffset:Ux,bloomIndicesLength:Ub,groundEffectVertexOffset:YC,groundEffectVertexLength:rR,hasFauxFacade:vr,height:Gv,promoteId:nt,feature:kt,parts:gf,buildingBloom:$x},Tu=this.footprints.length;Ye.id!==void 0&&this.featureFootprintLookup.set(Ye.id,Tu),_e(vt,Tu),this.footprints.push(mg)}this.programConfigurations.populatePaintArrays(ho.layoutVertexArray.length,Ye,it,{},_.availableImages,C,_.brightness),this.groundEffect.addPaintPropertiesData(Ye,it,{},_.availableImages,C,_.brightness),_.featureIndex.insert(Ye,ls,it,ut,this.index,_y)}se.forEach(({buildingId:Ye,footprintIndex:nt})=>{me.has(Ye)&&(this.footprints[nt].hiddenFlags|=4)});const Ue=new Set;this.buildingIds.forEach((Ye,nt,it)=>{me.has(Ye)||Ue.add(Ye)}),this.buildingIds=Ue,this.groundEffect.prepareBorderSegments()}update(p,_,C,M,F,z,H){this.programConfigurations.updatePaintArrays(p,_,F,C,M,z,H),this.groundEffect.update(p,_,F,C,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 _=C=>{C.layoutVertexBuffer=p.createVertexBuffer(C.layoutVertexArray,Xut.members),C.layoutNormalBuffer=p.createVertexBuffer(C.layoutNormalArray,Hms.members),C.layoutCentroidBuffer=p.createVertexBuffer(C.layoutCentroidArray,Gms.members),C.layoutFloodLightDataBuffer=p.createVertexBuffer(C.layoutFloodLightDataArray,Xms.members),C.layoutFacadeDataArray&&C.layoutFacadeDataArray.length&&(C.layoutFacadeDataBuffer=p.createVertexBuffer(C.layoutFacadeDataArray,Kms.members)),C.layoutFacadeVerticalRangeArray&&C.layoutFacadeVerticalRangeArray.length&&(C.layoutFacadeVerticalRangeBuffer=p.createVertexBuffer(C.layoutFacadeVerticalRangeArray,Yms.members)),C.entranceBloom.layoutVertexArray.length&&(C.entranceBloom.layoutVertexBuffer=p.createVertexBuffer(C.entranceBloom.layoutVertexArray,Xut.members),C.entranceBloom.layoutAttenuationBuffer=p.createVertexBuffer(C.entranceBloom.layoutAttenuationArray,Zms.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,_,C=!0){let M=!1;const F=C?_:0,z=0|(C?-1:~_);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const H of p){const Y=this.footprints[H],se=Y.hiddenFlags&z|F;Y.hiddenFlags!==se&&(Y.hiddenFlags=se,M=!0,this.groundEffect.updateHiddenByLandmarkRange(Y.groundEffectVertexOffset,Y.groundEffectVertexLength,Y.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 Y=M.indicesOffset;Y{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))};C(this.buildingWithoutFacade),C(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(p){const _=C=>{C.layoutColorBuffer?C.layoutColorBuffer.updateData(C.layoutColorArray):C.layoutColorBuffer=p.createVertexBuffer(C.layoutColorArray,Qut.members,!0),C.layoutFacadePaintArray&&(C.layoutFacadePaintBuffer?C.layoutFacadePaintBuffer.updateData(C.layoutFacadePaintArray):C.layoutFacadePaintBuffer=p.createVertexBuffer(C.layoutFacadePaintArray,Wms.members,!0)),C.entranceBloom.layoutColorBuffer?C.entranceBloom.layoutColorBuffer.updateData(C.entranceBloom.layoutColorArray):C.entranceBloom.layoutColorBuffer=p.createVertexBuffer(C.entranceBloom.layoutColorArray,Qut.members,!0)};_(this.buildingWithoutFacade),_(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(p,_){const C=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),Y=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),me=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),_e=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 nt of M.parts){let it,ut=H;nt.part===1?(ut=H,it=Y):nt.part===0?(ut=se,it=me):nt.part===2?(ut=xe,it=_e):nt.part===3&&(ut=Te,it=De),it=ea(it,0,1);for(let ot=0;otz.max.x||Y.max.xz.max.y||Y.max.yH.max.x||H.min.x>p||_>H.max.y||H.min.y>_||H.height<=C||vfs(z,this.footprintsVertices.float32.subarray(2*H.footprintVertexOffset,2*(H.footprintVertexOffset+H.footprintVertexLength)),this.footprintsIndices.uint16.subarray(H.footprintIndexOffset,H.footprintIndexOffset+H.footprintIndexLength))&&(C=H.height,this.footprintLookup[F]=H,M=H.hiddenFlags!==0);if(C!==Number.NEGATIVE_INFINITY)return{height:C,hidden:M};this.footprintLookup[F]=void 0}}function vfs(N,p,_){for(let C=0;C<_.length;C+=3){const M=_[C],F=_[C+1],z=_[C+2],H=p[2*M+0],Y=p[2*M+1],se=p[2*F+0],me=p[2*F+1],xe=p[2*z+0],_e=p[2*z+1],Te=(H-xe)*(N.y-_e)-(Y-_e)*(N.x-xe),De=(se-H)*(N.y-Y)-(me-Y)*(N.x-H);if(Te<0!=De<0&&Te!==0&&De!==0)continue;const Ue=(xe-se)*(N.y-me)-(_e-me)*(N.x-se);if(Ue===0||Ue<0==Te+De<=0)return!0}return!1}function bfs(N,p,_,C,M,F){const z=Math.pow(2,C.z-M.z);for(let H=0;H<_;H++){let Y=N.float32[2*(H+p)+0],se=N.float32[2*(H+p)+1];Y=(Y+M.x*Pr)*z-C.x*Pr,se=(se+M.y*Pr)*z-C.y*Pr,F.push(new xs(Y,se))}}oa(mht,"BuildingBucket",{omit:["layers"]}),oa(s8e,"BuildingGeometry"),oa(t8e,"BuildingBloomGeometry");class fht{constructor(p=0,_=[]){this.frcMask=p,this.rings=_}hasGeometry(){return this.rings.length>0&&this.rings[0].length>0}}async function Nle(){}function Q9(N,p,_){const C=p.paint.get(N).value;return C.kind==="constant"?C.value:_.programConfigurations.get(p.id).getMaxValue(N)}function kle(N){return Math.sqrt(N[0]*N[0]+N[1]*N[1])}function pht(N,p,_,C,M){if(!p[0]&&!p[1])return N;const F=xs.convert(p)._mult(M);_==="viewport"&&F._rotate(-C);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 yht(N,p,_,C,M,F,z,H,Y){if(F&&N.queryGeometry.isAboveHorizon)return!1;F&&(Y*=N.pixelToTileUnitsFactor);const se=N.tileID.canonical,me=_.projection.upVectorScale(se,_.center.lat,_.worldSize).metersToTile;for(const xe of p)for(const _e of xe){const Te=_e.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 ut=_.projection.upVector(se,Te.x,Te.y);Ue.x+=ut[0]*me*De,Ue.y+=ut[1]*me*De,Ue.z+=ut[2]*me*De}const Ye=F?Te:wfs(Ue.x,Ue.y,Ue.z,C),nt=F?N.tilespaceRays.map(ut=>Nfs(ut,De)):N.queryGeometry.screenGeometry,it=Ft([],[Ue.x,Ue.y,Ue.z,1],C);if(!z&&F?Y*=it[3]/_.cameraToCenterDistance:z&&!F&&(Y*=_.cameraToCenterDistance/it[3]),F){const ut=$d((_e.y/Pr+se.y)/(1<ya(p,_,C==="log"?(Math.pow(10,N)-1)/9:N);function WY(N){const{expression:p,evaluationKey:_,resolution:C=256,clips:M,scale:F="linear",lut:z=null}=N,H=M?M.length:1,Y=N.image||new e0({width:C,height:H}),se={},me=(xe,_e,Te)=>{se[_]=Te;const De=p.evaluate(se),Ue=(De==null?void 0:De.toNonPremultipliedRenderColor(z))??null;Ue&&(Y.data[xe+_e+0]=Math.floor(255*Ue.r),Y.data[xe+_e+1]=Math.floor(255*Ue.g),Y.data[xe+_e+2]=Math.floor(255*Ue.b),Y.data[xe+_e+3]=Math.floor(255*Ue.a))};for(let xe=0,_e=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 C of this.footprints)_.push({footprint:C,id:p})}updateAppearances(p,_,C,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,C,M){const F=[];for(const{feature:z,id:H,index:Y,sourceLayerIndex:se}of p){const me=this.layers[0]._featureFilter.needGeometry,xe=_t(z,me);if(!this.layers[0]._featureFilter.filter(new Hn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),xe,C))continue;const _e={id:H,properties:z.properties,type:z.type,sourceLayerIndex:se,index:Y,geometry:me?xe.geometry:dt(z,C,M),patterns:{}};F.push(_e)}for(const z of F){const{geometry:H,index:Y,sourceLayerIndex:se}=z;this.addFeature(z,H,Y,C,{},_.availableImages,_.brightness),_.featureIndex.insert(p[Y].feature,H,Y,se,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(p){}update(p,_,C,M,F,z,H){}destroy(){}addFeature(p,_,C,M,F,z=[],H){for(const Y of Pa(_,2)){const se=[],me=[],xe=[],_e=new xs(1/0,1/0),Te=new xs(-1/0,-1/0);for(const Ye of Y)if(Ye.length!==0){Ye!==Y[0]&&xe.push(me.length/2);for(let nt=0;nt{Ws[0]=mn,Ws[1]=ln,Ws[2]=_n,Ws[3]=1},Ps=oht();Te>0&&(Te+=Ps),De+=Ps;for(const Ws of _e){const mn=[],ln=[];for(const _n of Ws){const Un=_n.x+Ue.x,Cs=_n.y+Ue.y,Xs=xe.projection.projectTilePoint(Un,Cs,vt),rn=xe.projection.upVector(vt,_n.x,_n.y);let In=Te,Pn=De;if(nt){const $n=zht(Un,Cs,Te,De,nt,it,ut,ot);In+=$n.base,Pn+=$n.top}Te!==0?ns(qt,Xs.x+rn[0]*At*In,Xs.y+rn[1]*At*In,Xs.z+rn[2]*At*In):ns(qt,Xs.x,Xs.y,Xs.z),ns(ts,Xs.x+rn[0]*At*Pn,Xs.y+rn[1]*At*Pn,Xs.z+rn[2]*At*Pn),Qe(qt,qt,Ye),Qe(ts,ts,Ye),mn.push(new Y6(qt[0],qt[1],qt[2])),ln.push(new Y6(ts[0],ts[1],ts[2]))}kt.push(mn),ls.push(ln)}return[kt,ls]}(N,p,_,C,M,F,z,H,Y,se,me):z?function(xe,_e,Te,De,Ue,Ye,nt,it,ut){const ot=[],vt=[],kt=[0,0,0,1];for(const ls of xe){const At=[],qt=[];for(const ts of ls){const ns=ts.x+De.x,Ps=ts.y+De.y,Ws=zht(ns,Ps,_e,Te,Ye,nt,it,ut);kt[0]=ns,kt[1]=Ps,kt[2]=Ws.base,kt[3]=1,Ft(kt,kt,Ue),kt[3]=Math.max(kt[3],1e-5);const mn=new Y6(kt[0]/kt[3],kt[1]/kt[3],kt[2]/kt[3]);kt[0]=ns,kt[1]=Ps,kt[2]=Ws.top,kt[3]=1,Ft(kt,kt,Ue),kt[3]=Math.max(kt[3],1e-5);const ln=new Y6(kt[0]/kt[3],kt[1]/kt[3],kt[2]/kt[3]);At.push(mn),qt.push(ln)}ot.push(At),vt.push(qt)}return[ot,vt]}(p,_,C,M,F,z,H,Y,se):function(xe,_e,Te,De,Ue){const Ye=[],nt=[],it=Ue[8]*_e,ut=Ue[9]*_e,ot=Ue[10]*_e,vt=Ue[11]*_e,kt=Ue[8]*Te,ls=Ue[9]*Te,At=Ue[10]*Te,qt=Ue[11]*Te;for(const ts of xe){const ns=[],Ps=[];for(const Ws of ts){const mn=Ws.x+De.x,ln=Ws.y+De.y,_n=Ue[0]*mn+Ue[4]*ln+Ue[12],Un=Ue[1]*mn+Ue[5]*ln+Ue[13],Cs=Ue[2]*mn+Ue[6]*ln+Ue[14],Xs=Ue[3]*mn+Ue[7]*ln+Ue[15],rn=_n+it,In=Un+ut,Pn=Cs+ot,$n=Math.max(Xs+vt,1e-5),Rn=_n+kt,rr=Un+ls,On=Cs+At,Ar=Math.max(Xs+qt,1e-5);ns.push(new Y6(rn/$n,In/$n,Pn/$n)),Ps.push(new Y6(Rn/Ar,rr/Ar,On/Ar))}Ye.push(ns),nt.push(Ps)}return[Ye,nt]}(p,_,C,M,F)}function zht(N,p,_,C,M,F,z,H){const Y=z*M.getElevationAt(N,p,!0,!0),se=F[0]!==0,me=se?F[1]===0?z*(F[0]/7-450):z*function(xe,_e,Te){const De=Math.floor(_e[0]/8),Ue=Math.floor(_e[1]/8),Ye=10*(_e[0]-8*De),nt=10*(_e[1]-8*Ue),it=xe.getElevationAt(De,Ue,!0,!0),ut=xe.getMeterToDEM(Te),ot=Math.floor(.5*(Ye*ut-1)),vt=Math.floor(.5*(nt*ut-1)),kt=xe.tileCoordToPixel(De,Ue),ls=2*ot+1,At=2*vt+1,qt=function(ln,_n,Un,Cs,Xs){return[ln.getElevationAtPixel(_n,Un,!0),ln.getElevationAtPixel(_n+Xs,Un,!0),ln.getElevationAtPixel(_n,Un+Xs,!0),ln.getElevationAtPixel(_n+Cs,Un+Xs,!0)]}(xe,kt.x-ot,kt.y-vt,ls,At),ts=Math.abs(qt[0]-qt[1]),ns=Math.abs(qt[2]-qt[3]),Ps=Math.abs(qt[0]-qt[2])+Math.abs(qt[1]-qt[3]),Ws=Math.min(.25,.5*ut*(ts+ns)/ls),mn=Math.min(.25,.5*ut*Ps/At);return it+Math.max(Ws*Ye,mn*nt)}(M,F,H):Y;return{base:Y+(_===0?-1:_),top:se?Math.max(me+C,Y+_+2):Y+C}}function YY(N,p,_){return p*(Pr/(N.tileSize*Math.pow(2,_-N.tileID.overscaledZ)))}function Bht(N,p){return 1/YY(N,1,p.tileZoom)}function $ht(N,p,_,C){return N.translatePosMatrix(C||p.tileID.projMatrix,p,_.paint.get("line-translate"),_.paint.get("line-translate-anchor"))}oa(Rht,"ClipBucket",{omit:["layers"]});const Uht=N=>{const p=[];qht(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 C=N.paint.get("line-border-width").constantOr(1)!==0;C&&p.push("RENDER_LINE_BORDER"),C&&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 qht(N){const p=N.paint.get("line-dasharray").value;return p.kind!=="constant"||p.value}let n8e;const Vht=()=>n8e||(n8e={layout:Iht||(Iht=new Wu({"line-cap":new kr(Zs.layout_line["line-cap"]),"line-join":new kr(Zs.layout_line["line-join"]),"line-miter-limit":new fr(Zs.layout_line["line-miter-limit"]),"line-round-limit":new fr(Zs.layout_line["line-round-limit"]),"line-sort-key":new kr(Zs.layout_line["line-sort-key"]),"line-z-offset":new kr(Zs.layout_line["line-z-offset"]),"line-elevation-reference":new fr(Zs.layout_line["line-elevation-reference"]),"line-cross-slope":new fr(Zs.layout_line["line-cross-slope"]),visibility:new fr(Zs.layout_line.visibility),"line-width-unit":new fr(Zs.layout_line["line-width-unit"]),"line-elevation-ground-scale":new kr(Zs.layout_line["line-elevation-ground-scale"])})),paint:Lht||(Lht=new Wu({"line-opacity":new kr(Zs.paint_line["line-opacity"]),"line-color":new kr(Zs.paint_line["line-color"]),"line-translate":new fr(Zs.paint_line["line-translate"]),"line-translate-anchor":new fr(Zs.paint_line["line-translate-anchor"]),"line-width":new kr(Zs.paint_line["line-width"]),"line-gap-width":new kr(Zs.paint_line["line-gap-width"]),"line-offset":new kr(Zs.paint_line["line-offset"]),"line-blur":new kr(Zs.paint_line["line-blur"]),"line-dasharray":new kr(Zs.paint_line["line-dasharray"]),"line-pattern":new kr(Zs.paint_line["line-pattern"]),"line-pattern-cross-fade":new fr(Zs.paint_line["line-pattern-cross-fade"]),"line-gradient":new P3(Zs.paint_line["line-gradient"]),"line-trim-offset":new fr(Zs.paint_line["line-trim-offset"]),"line-trim-fade-range":new fr(Zs.paint_line["line-trim-fade-range"]),"line-trim-color":new fr(Zs.paint_line["line-trim-color"]),"line-emissive-strength":new kr(Zs.paint_line["line-emissive-strength"]),"line-border-width":new kr(Zs.paint_line["line-border-width"]),"line-border-color":new kr(Zs.paint_line["line-border-color"]),"line-border-gradient":new P3(Zs.paint_line["line-border-gradient"]),"line-occlusion-opacity":new fr(Zs.paint_line["line-occlusion-opacity"]),"line-blend-mode":new fr(Zs.paint_line["line-blend-mode"]),"line-blend-additive-clamp":new fr(Zs.paint_line["line-blend-additive-clamp"]),"line-cutout-depth":new fr(Zs.paint_line["line-cutout-depth"]),"line-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"line-border-gradient-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},n8e);class Sfs extends kr{possiblyEvaluate(p,_){return _=new Hn(Math.floor(_.zoom),{now:_.now,fadeDuration:_.fadeDuration,transition:_.transition,worldview:_.worldview}),super.possiblyEvaluate(p,_)}evaluate(p,_,C,M){return _={..._,zoom:Math.floor(_.zoom)},super.evaluate(p,_,C,M)}}let ZY,Hht,Ght,r8e;function Wht(N,p){return p>0?p+2*N:N}function Kht(N,p){return p.replace(/{([^{}]+)}/g,(_,C)=>C in N?String(N[C]):"")}class Yht{constructor(p){this.type=p.property.overrides?p.property.overrides.runtimeType:pu,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(Yht,"FormatSectionOverride",{omit:["defaultValue"]});const Cfs={};function Zht(N){return N.value.kind!=="constant"&&N.value.isStateDependent}const a8e=()=>r8e||(r8e={layout:Hht||(Hht=new Wu({"symbol-placement":new fr(Zs.layout_symbol["symbol-placement"]),"symbol-spacing":new fr(Zs.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new fr(Zs.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new kr(Zs.layout_symbol["symbol-sort-key"]),"symbol-z-order":new fr(Zs.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new fr(Zs.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new fr(Zs.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new fr(Zs.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new fr(Zs.layout_symbol["icon-ignore-placement"]),"icon-optional":new fr(Zs.layout_symbol["icon-optional"]),"icon-rotation-alignment":new fr(Zs.layout_symbol["icon-rotation-alignment"]),"icon-size":new kr(Zs.layout_symbol["icon-size"]),"icon-size-scale-range":new fr(Zs.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new kr(Zs.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new kr(Zs.layout_symbol["icon-text-fit-padding"]),"icon-image":new kr(Zs.layout_symbol["icon-image"]),"icon-image-use-theme":new fr({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new kr(Zs.layout_symbol["icon-rotate"]),"icon-padding":new fr(Zs.layout_symbol["icon-padding"]),"icon-keep-upright":new fr(Zs.layout_symbol["icon-keep-upright"]),"icon-offset":new kr(Zs.layout_symbol["icon-offset"]),"icon-anchor":new kr(Zs.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new fr(Zs.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new fr(Zs.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new fr(Zs.layout_symbol["text-rotation-alignment"]),"text-field":new kr(Zs.layout_symbol["text-field"]),"text-font":new kr(Zs.layout_symbol["text-font"]),"text-size":new kr(Zs.layout_symbol["text-size"]),"text-size-scale-range":new fr(Zs.layout_symbol["text-size-scale-range"]),"text-max-width":new kr(Zs.layout_symbol["text-max-width"]),"text-line-height":new kr(Zs.layout_symbol["text-line-height"]),"text-letter-spacing":new kr(Zs.layout_symbol["text-letter-spacing"]),"text-justify":new kr(Zs.layout_symbol["text-justify"]),"text-radial-offset":new kr(Zs.layout_symbol["text-radial-offset"]),"text-variable-anchor":new fr(Zs.layout_symbol["text-variable-anchor"]),"text-anchor":new kr(Zs.layout_symbol["text-anchor"]),"text-max-angle":new fr(Zs.layout_symbol["text-max-angle"]),"text-writing-mode":new fr(Zs.layout_symbol["text-writing-mode"]),"text-rotate":new kr(Zs.layout_symbol["text-rotate"]),"text-padding":new fr(Zs.layout_symbol["text-padding"]),"text-keep-upright":new fr(Zs.layout_symbol["text-keep-upright"]),"text-transform":new kr(Zs.layout_symbol["text-transform"]),"text-offset":new kr(Zs.layout_symbol["text-offset"]),"text-allow-overlap":new fr(Zs.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new fr(Zs.layout_symbol["text-ignore-placement"]),"text-optional":new fr(Zs.layout_symbol["text-optional"]),visibility:new fr(Zs.layout_symbol.visibility)})),paint:Ght||(Ght=new Wu({"icon-opacity":new kr(Zs.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new kr(Zs.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new kr(Zs.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new kr(Zs.paint_symbol["text-emissive-strength"]),"icon-color":new kr(Zs.paint_symbol["icon-color"]),"icon-halo-color":new kr(Zs.paint_symbol["icon-halo-color"]),"icon-halo-width":new kr(Zs.paint_symbol["icon-halo-width"]),"icon-halo-blur":new kr(Zs.paint_symbol["icon-halo-blur"]),"icon-translate":new fr(Zs.paint_symbol["icon-translate"]),"icon-translate-anchor":new fr(Zs.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new fr(Zs.paint_symbol["icon-image-cross-fade"]),"text-opacity":new kr(Zs.paint_symbol["text-opacity"]),"text-occlusion-opacity":new kr(Zs.paint_symbol["text-occlusion-opacity"]),"text-color":new kr(Zs.paint_symbol["text-color"],{runtimeType:Qc,getOverride:N=>N.textColor,hasOverride:N=>!!N.textColor}),"text-halo-color":new kr(Zs.paint_symbol["text-halo-color"]),"text-halo-width":new kr(Zs.paint_symbol["text-halo-width"]),"text-halo-blur":new kr(Zs.paint_symbol["text-halo-blur"]),"text-translate":new fr(Zs.paint_symbol["text-translate"]),"text-translate-anchor":new fr(Zs.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new fr(Zs.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new fr(Zs.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new fr(Zs.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new fr(Zs.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new kr(Zs.paint_symbol["symbol-z-offset"]),"placement-priority":new kr(Zs.paint_symbol["placement-priority"]),"placement-group":new kr(Zs.paint_symbol["placement-group"]),"icon-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},r8e);class Sle extends Qy{constructor(p,_,C,M){super(p,a8e(),_,C,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 C=this.layout.get("text-writing-mode");if(C){const M=[];for(const F of C)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,_,C,M){return this._saturation===p&&this._contrast===_&&this._brightnessMin===C&&this._brightnessMax===M||(this._colorAdjustmentMatrix=function(F,z,H,Y){F=cm(F),z=qi(z);const se=v(),me=F/3,xe=1-2*me,_e=[xe,me,me,0,me,xe,me,0,me,me,xe,0,0,0,0,1],Te=.5-.5*z,De=Y-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,_e),se}(p,_,C,M),this._saturation=p,this._contrast=_,this._brightnessMin=C,this._brightnessMax=M),this._colorAdjustmentMatrix}getValueAndResolveTokens(p,_,C,M){const F=this.layout.get(p).evaluate(_,{},C,M),z=this._unevaluatedLayout._values[p];return z.isDataDriven()||$v(z.value)||!F?F:Kht(_.properties,F)}getAppearanceValueAndResolveTokens(p,_,C,M,F){const z=p.getLayoutProperty(_);if(!z)return;const H=z.evaluate(C,{},M,F),Y=p.getUnevaluatedLayoutProperties()._values[_];return Y.isDataDriven()||$v(Y.value)||!H||typeof H!="string"?H:Kht(C.properties,H)}createBucket(p){return new Qoe(p)}placeSymbols(p,_,C,M,F){const{globalPlacement:z,idRangeAllocator:H,transform:Y,buildingIndex:se,fogState:me,groupOrders:xe,replacementSource:_e}=p,Te=this.runtimeLayerUID,De=Zht(this.paint.get("placement-group"))||Zht(this.paint.get("placement-priority"))?M._state.getState(this.sourceLayer||"_geojsonTileLayer"):Cfs;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 nt=$dt(Ue.tileID,Ye.getProjection(),Y,Y.projection.name);Ye.addToPlacement(z,H,Te,nt,Y,Ue.tileSize/Pr,Ue,me,xe,C,De,F?_e:null),z.finishSourceProcessing()}}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const p of a8e().paint.overridableProperties){if(!Sle.hasPaintOverride(this.layout,p))continue;const _=this.paint.get(p),C=new Yht(_),M=new Bv(C,_.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let F=null;F=_.value.kind==="constant"||_.value.kind==="source"?new $_("source",M):new og("composite",M,_.value.zoomStops,_.value.interpolationType),this.paint._values[p]=new bh(_.property,F,_.parameters)}}_handleOverridablePaintPropertyUpdate(p,_,C){return!(!this.layout||_.isDataDriven()||C.isDataDriven())&&Sle.hasPaintOverride(this.layout,p)}static hasPaintOverride(p,_){const C=p.get("text-field"),M=a8e().paint.properties[_];let F=!1;const z=H=>{for(const Y of H)if(M.overrides&&M.overrides.hasOverride(Y))return void(F=!0)};if(C.value.kind==="constant"&&C.value.value instanceof xu)z(C.value.value.sections);else if(C.value.kind==="source"){const H=se=>{F||(se instanceof Kg&&oh(se.value)===xh?z(se.value.sections):se instanceof P1?z(se.sections):se.eachChild(H))},Y=C.value;Y._styleExpression&&H(Y._styleExpression.expression)}return F}getProgramIds(){return["symbol"]}getDefaultProgramParams(p,_,C){return{config:new K6(this,{zoom:_,lut:C}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}mayUse(p){return p==="HD"&&A9(this,"symbol-elevation-reference",_=>_==="hd-road-markup")}prepare(){return this.mayUse("HD")?Nle():Promise.resolve()}}let Xht,Qht,Jht,emt;const i8e=1024,Afs=(Math.pow(i8e,2)-1)/268170240;class tmt extends Qy{constructor(p,_,C,M){super(p,{layout:Jht||(Jht=new Wu({visibility:new fr(Zs.layout_raster.visibility)})),paint:emt||(emt=new Wu({"raster-opacity":new fr(Zs.paint_raster["raster-opacity"]),"raster-color":new P3(Zs.paint_raster["raster-color"]),"raster-color-mix":new fr(Zs.paint_raster["raster-color-mix"]),"raster-color-range":new fr(Zs.paint_raster["raster-color-range"]),"raster-color-scale":new fr(Zs.paint_raster["raster-color-scale"]),"raster-hue-rotate":new fr(Zs.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new fr(Zs.paint_raster["raster-brightness-min"]),"raster-brightness-max":new fr(Zs.paint_raster["raster-brightness-max"]),"raster-saturation":new fr(Zs.paint_raster["raster-saturation"]),"raster-contrast":new fr(Zs.paint_raster["raster-contrast"]),"raster-resampling":new fr(Zs.paint_raster["raster-resampling"]),"raster-fade-duration":new fr(Zs.paint_raster["raster-fade-duration"]),"raster-emissive-strength":new fr(Zs.paint_raster["raster-emissive-strength"]),"raster-array-band":new fr(Zs.paint_raster["raster-array-band"]),"raster-elevation":new fr(Zs.paint_raster["raster-elevation"]),"raster-elevation-reference":new fr(Zs.paint_raster["raster-elevation-reference"]),"raster-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},_,C,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,[C,M]=p||this._transitionablePaint._values["raster-color-range"].value.expression.evaluate({zoom:0})||[NaN,NaN];if(isNaN(C)&&isNaN(M)||C===this._curRampRange[0]&&M===this._curRampRange[1])return;const F=this._transitionablePaint._values["raster-color-scale"].value.expression.evaluate({zoom:0});this.colorRamp=WY({expression:_,evaluationKey:"rasterValue",image:this.colorRamp,clips:[{start:C,end:M}],resolution:i8e,scale:F}),this.colorRampTexture=null,this._curRampRange=[C,M]}is3D(p){return this.paint.get("raster-elevation")>0}}let smt,nmt,rmt,amt,imt,omt,lmt,cmt;class dmt extends Qy{constructor(p,_,C,M){super(p,{layout:smt||(smt=new Wu({visibility:new fr(Zs["layout_raster-particle"].visibility)})),paint:nmt||(nmt=new Wu({"raster-particle-array-band":new fr(Zs["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new fr(Zs["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new P3(Zs["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new fr(Zs["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new fr(Zs["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new fr(Zs["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new fr(Zs["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new fr(Zs["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},_,C,M),this._updateColorRamp(),this.lastInvalidatedAt=ah.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=WY({expression:p,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:_}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=ah.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class Efs extends Qy{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 o8e(N,p,_){const C=[0,0,1],M=jt([]);return gs(M,M,_?-Yr(N)+Math.PI:Yr(N)),yt(M,M,-Yr(p)),rt(C,C,M),qe(C,C)}class umt{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 hmt{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new _h,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(p){const _=16*p,C=this.instancedDataArray.float32;let M=Math.floor(C[_+2]);const F=1.05*(C[_+2]-M);return M/=100,[C[_]%1*1.05,C[_+1]%1*1.05,F,M]}tileCoordinatesForInstance(p){const _=16*p,C=this.instancedDataArray.float32;let M=C[_+0];return M=M>Pr?M-Pr:M,new xs(Math.trunc(M),Math.trunc(C[_+1]))}translationForInstance(p){const _=16*p,C=this.instancedDataArray.float32;return[C[_+4],C[_+5],C[_+6]]}rotationScaleForInstance(p){const _=16*p,C=this.instancedDataArray.float32;return[C[_+7],C[_+8],C[_+9],C[_+10],C[_+11],C[_+12],C[_+13],C[_+14],C[_+15]]}transformForInstance(p){const _=16*p,C=this.instancedDataArray.float32;return[C[_+7],C[_+8],C[_+9],C[_+4],C[_+10],C[_+11],C[_+12],C[_+5],C[_+13],C[_+14],C[_+15],C[_+6],0,0,0,1]}}class l8e{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,_,C,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,C,M){this.tileToMeter=K(C);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:Y,index:se,sourceLayerIndex:me}of p){const xe=Y??(H.properties&&Object.hasOwn(H.properties,"id")?H.properties.id:void 0),_e=_t(H,F);if(!this.layers[0]._featureFilter.filter(new Hn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),_e,C))continue;const Te={id:xe,sourceLayerIndex:me,index:se,geometry:F?_e.geometry:dt(H,C,M),properties:H.properties,type:H.type,patterns:{}},De=this.addFeature(Te,Te.geometry,_e,z,C);De&&_.featureIndex.insert(H,Te.geometry,se,me,this.index,this.instancesPerModel[De].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const p=this.layers[0].modelManager,_=this.layers[0].scope;let C=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*Be(F.aabb.max,F.aabb.min)*z.maxScale+z.maxXYTranslationDistance,Y=Math.min(Pr,Math.max(H/this.tileToMeter,256));C=Math.max(Y,C)}}return C}update(p,_,C,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 C=this.instancesPerModel[_];for(const M of C.features){const F=this.layers[0],z=M.feature,H=this.canonical,Y=F.paint.get("model-rotation").evaluate(z,{},H),se=F.paint.get("model-scale").evaluate(z,{},H),me=F.paint.get("model-translation").evaluate(z,{},H);Je(M.rotation,Y)&&Je(M.scale,se)&&Je(M.translation,me)||(this.evaluate(M,M.featureStates,C,!0),p=!0)}}return p}updateReplacement(p,_,C,M){if(_.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=_.updateTime;const F=_.getReplacementRegionsForTile(p.toUnwrapped(),!0);if(Boe(this.activeReplacements,F))return!1;this.activeReplacements=F;let z=!1;for(const H in this.instancesPerModel){const Y=this.instancesPerModel[H],se=Y.instancedDataArray;for(const me of Y.features){const xe=me.instancedDataOffset,_e=me.instancedDataCount;for(let Te=0;Te<_e;Te++){const De=16*(Te+xe);let Ue=se.float32[De+0];const Ye=Ue>Pr;Ue=Ye?Ue-Pr:Ue;const nt=Math.floor(Ue),it=Math.floor(se.float32[De+1]);let ut=!1;for(const ot of this.activeReplacements)if(!dOe(ot,C,MY.Model,M)&&!(ot.min.x>nt||nt>ot.max.x||ot.min.y>it||it>ot.max.y)&&(ut=$oe(mOe(nt,it,p.canonical,ot.footprintTileId.canonical),ot.footprint),ut))break;se.float32[De]=ut?Ue+Pr:Ue,z=z||ut!==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 C=this.instancesPerModel[_];C.instancedDataArray.length<0||C.instancedDataArray.length===0||(C.instancedDataBuffer?C.instancedDataBuffer.updateData(C.instancedDataArray):C.instancedDataBuffer=p.createVertexBuffer(C.instancedDataArray,Ims.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(p){for(const C in this.instancesPerModel){const M=this.instancesPerModel[C];M.instancedDataArray.length!==0&&M.instancedDataBuffer&&M.instancedDataBuffer.destroy()}const _=this.layers[0].modelManager;if(p&&_&&this.modelUris&&this.modelsRequested)for(const C of this.modelUris)_.removeModel(C,"",!0)}addFeature(p,_,C,M,F){const z=this.layers[0],H=z.layout.get("model-id"),Y=z.layout.get("model-allow-density-reduction"),se=H.evaluate(C,{},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 hmt);const me=this.instancesPerModel[se],xe=me.instancedDataArray,_e=new umt(C,xe.length);let Te;if(M){const De=zY(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>=Pr||Ue.y<0||Ue.y>=Pr)continue;if(this.lookupDim!==0&&Y){const nt=(this.lookupDim-1)/Pr,it=this.lookupDim*(Ue.y*nt|0)+Ue.x*nt|0;if(this.lookup){if(this.lookup[it]!==0)continue;this.lookup[it]=1}}this.instanceCount++;const Ye=xe.length;if(xe.resize(Ye+1),M){me.instancesRoadElevation||(me.instancesRoadElevation=[]);const nt=Te?Te.pointElevation(new xs(Ue.x,Ue.y)):0;me.instancesRoadElevation.push(nt)}me.instancesEvaluatedElevation.push(0),xe.float32[16*Ye]=Ue.x,xe.float32[16*Ye+1]=Ue.y}return _e.instancedDataCount=me.instancedDataArray.length-_e.instancedDataOffset,_e.instancedDataCount>0&&(p.id&&(me.idToFeaturesIndex[p.id]=me.features.length),me.features.push(_e),this.evaluate(_e,{},me,!1)),se}getModelUris(){return this.modelUris}evaluate(p,_,C,M){const F=this.layers[0],z=p.feature,H=this.canonical,Y=p.rotation=F.paint.get("model-rotation").evaluate(z,_,H),se=p.scale=F.paint.get("model-scale").evaluate(z,_,H),me=p.translation=F.paint.get("model-translation").evaluate(z,_,H),{r:xe,g:_e,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;C.maxScale=Math.max(Math.max(C.maxScale,se[0]),Math.max(se[1],se[2])),C.maxXYTranslationDistance=Math.max(C.maxXYTranslationDistance,nt),this.maxScale=Math.max(Math.max(this.maxScale,se[0]),Math.max(se[1],se[2])),$ut(Ue,Y,se);const it=Math.round(100*De)+Te/1.05;for(let ut=0;ut10?this.tileToMeter:K(H,At)),kt[vt+4]=me[0],kt[vt+5]=me[1],kt[vt+6]=me[2]+(C.instancesRoadElevation?C.instancesRoadElevation[ot]:0)+ls,kt[vt+7]=Ue[0],kt[vt+8]=Ue[1],kt[vt+9]=Ue[2],kt[vt+10]=Ue[4],kt[vt+11]=Ue[5],kt[vt+12]=Ue[6],kt[vt+13]=Ue[8],kt[vt+14]=Ue[9],kt[vt+15]=Ue[10],C.instancesEvaluatedElevation[ot]=me[2]}}}oa(l8e,"ModelBucket",{omit:["layers"]}),oa(hmt,"PerModelAttributes"),oa(umt,"ModelFeature");const mmt=new WeakMap;class Tfs{constructor(p,_){const C=p.gl;if(this.context=p,this.buffer=C.createBuffer(),!this.buffer)throw new Error("Failed to create model part style UBO buffer");C.bindBuffer(C.UNIFORM_BUFFER,this.buffer),C.bufferData(C.UNIFORM_BUFFER,_,C.DYNAMIC_DRAW),C.bindBuffer(C.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 C=mmt.get(_);if(C===void 0){const F=p.gl,z=F.getUniformBlockIndex(_,"ModelPartStyleUniform");C=z!==F.INVALID_INDEX,C&&F.uniformBlockBinding(_,z,0),mmt.set(_,C)}if(!C)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 c8e=new Float32Array(262144),tR=new Uint8Array(262144),Cle=[0,0,0],Ale=[0,0,0];function fmt(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,fmt(_));return p}function pmt(N,p,_){if(N.meshes)for(const C of N.meshes){if(C.aabb.min[0]===1/0)continue;const M=du.applyTransform(C.aabb,N.globalMatrix);_.insert(p,M.min[0],M.min[1],M.max[0],M.max[1])}if(N.children)for(const C of N.children)pmt(C,p,_)}class gmt{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:fmt(p)}},this.aabb=this._getLocalBounds(),this.state=null}_getLocalBounds(){if(!this.node.meshes)return new du([1/0,1/0,1/0],[-1/0,-1/0,-1/0]);if(!this.aabb){let p=0;const _=new du([1/0,1/0,1/0],[-1/0,-1/0,-1/0]);for(const C of this.node.meshes)this.node.lightMeshIndex!==p&&(C.transformedAabb=du.applyTransformFast(C.aabb,this.node.globalMatrix),_.encapsulate(C.transformedAabb)),p++;this.aabb=_}return this.aabb}}class xmt{constructor(p,_,C,M,F,z,H,Y){this.requiresStandardRuntime=!0,this.isTiled3dModelBucket=!0,this.id=C,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=Y,this.dirty=!0,this.needsPartStyleUBOs=!1,this.filter=null,this.nodesInfo=[];for(const se of _)this.nodesInfo.push(new gmt(se)),pmt(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 C of this.getNodesInfo()){const M=C.node;M.footprint&&_.push({footprint:M.footprint,id:p})}}updateAppearances(p,_,C,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(p){const _=Object.keys(p).length!==0;if(_&&!this.stateDependentLayers.length)return;const C=_?this.stateDependentLayers:this.layers;if(!Tr(p,this.states))for(const M of C)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 C of _)UOe(C.node,p,!0);for(const C of _)mle(C.node);this.uploaded=!0}}createPartStyleUBOs(p){for(const _ of this.getNodesInfo())_.needsPartStyleUBO&&(_.partStyleUBO=new Tfs(p,_.partStyle),_.needsPartStyleUBO=!1)}needsReEvaluation(p,_,C){const M=p.transform.projectionOptions,F=p.style.getBrightness(),z=this.brightness!==F;if(!this.uploaded||this.dirty||M.name!==this.projection.name||XY(C.paint.get("model-color").value,z)||XY(C.paint.get("model-color-mix-intensity").value,z)||XY(C.paint.get("model-roughness").value,z)||XY(C.paint.get("model-emissive-strength").value,z)||XY(C.paint.get("model-height-based-emissive-strength-multiplier").value,z)){this.projection=M,this.brightness=F;const H=this.getNodesInfo();for(const Y of H)Y.state=null;return!0}return!1}evaluateTransform(p,_){if(p.transform.zoom===this.zoom)return;this.zoom=p.transform.zoom;const C=this.getNodesInfo(),M=this.id.canonical;for(const F of C){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 C=this.getNodesInfo();for(const M of C){if(!M.node.meshes)continue;const F=M.feature,z=_&&_[F.id];if(Tr(z,M.state))continue;M.state=structuredClone(z);const H=M.node.meshes&&M.node.meshes[0].hasFeatureData,Y=this.id.canonical;if(M.hasTranslucentParts=!1,H){for(let se=0;se<$Oe.length;se++){const me=$Oe[se];me.length&&(F.properties.part=me);const xe=p.paint.get("model-color").evaluate(F,z,Y).toPremultipliedRenderColor(null),_e=p.paint.get("model-color-mix-intensity").evaluate(F,z,Y);M.evaluatedColor[se]=[xe.r,xe.g,xe.b,_e],M.evaluatedRMEA[se][0]=p.paint.get("model-roughness").evaluate(F,z,Y),M.evaluatedRMEA[se][2]=p.paint.get("model-emissive-strength").evaluate(F,z,Y),M.evaluatedRMEA[se][3]=xe.a,M.emissionHeightBasedParams[se]=p.paint.get("model-height-based-emissive-strength-multiplier").evaluate(F,z,Y),!M.hasTranslucentParts&&xe.a<1&&(M.hasTranslucentParts=!0)}delete F.properties.part}else M.evaluatedRMEA[0][2]=p.paint.get("model-emissive-strength").evaluate(F,z,Y);M.evaluatedTranslation=p.paint.get("model-translation").evaluate(F,z,Y),M.evaluatedScale=p.paint.get("model-scale").evaluate(F,z,Y),H&&(Pfs(M),M.partStyleUBO?M.partStyleUBO.update(M.partStyle):(M.needsPartStyleUBO=!0,this.needsPartStyleUBOs=!0))}this.dirty=!1}elevationUpdate(p,_,C,M){const F=p.findDEMTileFor(C);if(F&&(F.tileID.canonical!==this.terrainTile||_!==this.terrainExaggeration)){if(F.dem&&F.tileID.overscaledZ!==this.elevationReadFromZ){this.elevationReadFromZ=F.tileID.overscaledZ;const z=U9.create(p,C,F);if(!z)return;4&this.modelTraits&&this.updateDEM(p,z,C,M);for(const H of this.getNodesInfo()){const Y=H.node;if(!Y.footprint||!Y.footprint.vertices||!Y.footprint.vertices.length)continue;const se=Y.footprint.vertices;let me=z.getElevationAt(se[0].x,se[0].y,!0,!0);for(let xe=1;xe=kt)continue;const Un=c8e[_n],Cs=Math.abs(Un);Cs>ns&&(ts=Un,ns=Cs,Ps=ln,Ws=mn)}if(ns>.1){const mn=1-(kt+.5*Math.abs(Ps*Ws))/De;let ln=_._dem.get(At,ls)+ts*mn;const _n=_._dem.get(At+Ps,ls+Ws),Un=_._dem.get(At-Ps,ls-Ws,!0);(ln-_n)*(ln-Un)>0&&(ln=(_n+Un)/2),c8e[qt]=_._dem.set(At,ls,ln),tR[qt]=kt}}}}}H&&(_._demTile.needsDEMTextureUpload=!0,_._dem._timestamp=ah.now())}setFilter(p){this.filter=p?dY(p):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(p=>this.filter.filter(new Hn(this.id.overscaledZ,{worldview:this.worldview}),p.feature,this.id.canonical)):this.nodesInfo}destroy(){const p=this.getNodesInfo();for(const _ of p)mle(_.node),qOe(_.node),_.partStyleUBO&&(_.partStyleUBO.destroy(),_.partStyleUBO=null)}isEmpty(){return!this.nodesInfo.length}updateReplacement(p,_){if(_.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=_.updateTime;const C=_.getReplacementRegionsForTile(p.toUnwrapped());for(const M of this.getNodesInfo()){const F=M.node.footprint;M.hiddenByReplacement=!!F&&!C.some(z=>z.footprint===F)}}getHeightAtTileCoord(p,_){const C=[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(A(M,F.node.globalMatrix),C[0]=p,C[1]=_,C[2]=0,Qe(C,C,M),F.node.meshBVH){const xe=C[0],_e=C[1];Cle[0]=xe-1,Cle[1]=_e-1,Cle[2]=-1e3,Ale[0]=xe+1,Ale[1]=_e+1,Ale[2]=1e3;const Te=F.node.meshBVH.findHighestPoint(Cle,Ale);if(Te!==null)return{height:Te,maxHeight:F.feature.properties.height,hidden:F.hiddenByReplacement,verticalScale:F.evaluatedScale[2]};continue}if(!z.heightmap)continue;const Y=(C[0]-z.aabb.min[0])/(z.aabb.max[0]-z.aabb.min[0])*eR|0,se=Math.min(63,(C[1]-z.aabb.min[1])/(z.aabb.max[1]-z.aabb.min[1])*eR|0)*eR+Math.min(63,Y),me=z.heightmap[se];if(me<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:me,maxHeight:F.feature.properties.height,hidden:!1,verticalScale:F.evaluatedScale[2]}}}}function XY(N,p){return N instanceof $_&&!N.isLightConstant&&p}function Mfs(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,C=Math.floor(255*(N[p+10]+N[p+11]))/256;N[p+10]=_,N[p+11]=C-_}function Pfs(N){const p=N.partStyle;for(let _=0;_<$Oe.length;_++){const C=N.evaluatedColor[_],M=N.evaluatedRMEA[_],F=N.emissionHeightBasedParams[_],z=ea(F[0],0,1),H=ea(F[1],0,1),Y=16*_;p[Y]=C[0],p[Y+1]=C[1],p[Y+2]=C[2],p[Y+3]=ea(C[3],0,1),p[Y+4]=M[0],p[Y+5]=M[1],p[Y+6]=ea(M[2],0,2),p[Y+7]=M[3],z!==H?(p[Y+8]=z,p[Y+9]=H,p[Y+10]=ea(F[2],0,1),p[Y+11]=ea(F[3],0,1)-p[Y+10],p[Y+12]=Math.pow(10,ea(F[4],-1,1))):(p[Y+8]=0,p[Y+9]=1,p[Y+10]=1,p[Y+11]=0,p[Y+12]=1),Mfs(p,Y)}}oa(xmt,"Tiled3dModelBucket",{omit:["layers"]}),oa(gmt,"Tiled3dModelFeature",{omit:["partStyleUBO"]});class ymt{constructor(p){this._stringToNumber={},this._numberToString=[];for(let _=0;_{let ut=vmt,ot=0,vt=vmt;if(!it){const qt=M.style.light,ts=qt.properties.get("position");if(ut=[-ts.x,-ts.y,ts.z],qt.properties.get("anchor")==="viewport"){const Ps=f();x(Ps,-M.transform.angle),at(ut,ut,Ps)}const ns=qt.properties.get("color").toNonPremultipliedRenderColor(null);ot=qt.properties.get("intensity"),vt=[ns.r,ns.g,ns.b]}const kt=me.alphaMode==="MASK",ls=_e.paint.get("model-ambient-occlusion-intensity"),At=_e.paint.get("model-color").constantOr(Ci.white).toNonPremultipliedRenderColor(null);return At.a=_e.paint.get("model-color-mix-intensity").constantOr(0),Ye&&(At.r=Ye[0],At.g=Ye[1],At.b=Ye[2],At.a=Ye[3]),Ue&&(At.r=Ue.color.r,At.g=Ue.color.g,At.b=Ue.color.b,At.a=Ue.colorMix,xe=Ue.emissionStrength,F*=Ue.opacity),{u_matrix:N,u_lighting_matrix:p,u_normal_matrix:_,u_node_matrix:C||d8e,u_lightpos:ut,u_lightintensity:ot,u_lightcolor:vt,u_camera_pos:Te,u_opacity:F,u_baseTextureIsAlpha:0,u_alphaMask:+kt,u_alphaCutoff:me.alphaCutoff,u_baseColorFactor:z.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:H.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:Y,u_roughnessFactor:se,u_baseColorTexture:Hv.BaseColor,u_metallicRoughnessTexture:Hv.MetallicRoughness,u_normalTexture:Hv.Normal,u_occlusionTexture:Hv.Occlusion,u_emissionTexture:Hv.Emission,u_lutTexture:Hv.LUT,u_color_mix:At.toArray01(),u_aoIntensity:ls,u_emissive_strength:xe,u_occlusionTextureTransform:De||[0,0,0,0],u_dithered_discard_threshold:nt,u_model_mesh_params:[0,1,0,0]}},bmt=(N,p=d8e,_=d8e)=>({u_matrix:N,u_instance:p,u_node_matrix:_}),h8e=7680;class lj{constructor(p,_,C,M,F,z){this.test=p,this.ref=_,this.mask=C,this.fail=M,this.depthFail=F,this.pass=z}}lj.disabled=new lj({func:519,mask:0},0,0,h8e,h8e,h8e);const Ele=770,J9=771;class wh{constructor(p,_,C,M){this.blendFunction=p,this.blendColor=_.toNonPremultipliedRenderColor(null),this.mask=C,this.blendEquation=M}}wh.Replace=[1,0,1,0],wh.disabled=new wh(wh.Replace,Ci.transparent,[!1,!1,!1,!1]),wh.unblended=new wh(wh.Replace,Ci.transparent,[!0,!0,!0,!0]),wh.alphaBlended=new wh([1,J9,1,J9],Ci.transparent,[!0,!0,!0,!0]),wh.alphaBlendedNonPremultiplied=new wh([Ele,J9,Ele,J9],Ci.transparent,[!0,!0,!0,!0]),wh.multiply=new wh([774,0,774,0],Ci.transparent,[!0,!0,!0,!0]),wh.multiplyAccumulateAlpha=new wh([774,0,1,J9],Ci.transparent,[!0,!0,!0,!0]),wh.additive=new wh([1,1,1,1],Ci.transparent,[!0,!0,!0,!0]),wh.additiveAlphaWeighted=new wh([Ele,1,773,1],Ci.transparent,[!0,!0,!0,!0]),wh.additiveAlphaWeightedUnboundedAlpha=new wh([Ele,1,1,1],Ci.transparent,[!0,!0,!0,!0]);class vy{constructor(p,_,C){this.func=p,this.mask=_,this.range=C}}vy.ReadOnly=!1,vy.ReadWrite=!0,vy.disabled=new vy(519,vy.ReadOnly,[0,1]);const m8e=1029,f8e=2305;class by{constructor(p,_,C){this.enable=p,this.mode=_,this.frontFace=C}}by.disabled=new by(!1,m8e,f8e),by.backCCW=new by(!0,m8e,f8e),by.backCW=new by(!0,m8e,2304),by.frontCW=new by(!0,1028,2304),by.frontCCW=new by(!0,1028,f8e);class p8e{constructor(p=0,_=0,C=0,M=0){if(isNaN(p)||p<0||isNaN(_)||_<0||isNaN(C)||C<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=C,this.right=M}interpolate(p,_,C){return _.top!=null&&p.top!=null&&(this.top=ya(p.top,_.top,C)),_.bottom!=null&&p.bottom!=null&&(this.bottom=ya(p.bottom,_.bottom,C)),_.left!=null&&p.left!=null&&(this.left=ya(p.left,_.left,C)),_.right!=null&&p.right!=null&&(this.right=ya(p.right,_.right,C)),this}getCenter(p,_){return new xs(ea((this.left+p-this.right)/2,0,p),ea((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 p8e(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function _mt(N,p){const _=Ba(N,3);X(N,p),ao(N,3,_)}function g8e(N,p){const _=jt([]);return Ss(_,_,-p),yt(_,_,-N),_}function wmt(N,p){const _=[N[0],N[1],0],C=[p[0],p[1],0];if(ce(_)>=1e-15){const z=qe([],_);Fe(C,z,ze(C,z)),p[0]=C[0],p[1]=C[1]}const M=Ve([],p,N);if(es(M)<1e-15)return null;const F=Math.atan2(-M[1],M[0]);return g8e(Math.atan2(Math.sqrt(N[0]*N[0]+N[1]*N[1]),-N[2]),F)}class jmt{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=ml(_.x,0,1)),this._position=_}else this._position=null}lookAtPoint(p,_,C){if(this.orientation=null,!this.position)return;const M=this.position,F=C||(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=wmt(H,_)}setPitchBearing(p,_){this.orientation=g8e(Yr(p),Yr(-_))}}class Tle{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&&ao(this._transform,3,[(_=p)[0],_[1],_[2],1])}get orientation(){return this._orientation}set orientation(p){this._orientation=p||jt([]),p&&_mt(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=g8e(p,_),_mt(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 C=new Float64Array(16);return A(C,this.getWorldToCamera(p,_)),C}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(p,_,C){const M=this.position;Fe(M,M,-p);const F=new Float64Array(16);return W(F,[C,C,C]),I(F,F,M),F[10]*=_,F}getWorldToCamera(p,_){const C=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(C,M),I(C,C,F),C[1]*=-1,C[5]*=-1,C[9]*=-1,C[13]*=-1,C[8]*=_,C[9]*=_,C[10]*=_,C[11]*=_,C}getCameraToClipPerspective(p,_,C,M){const F=new Float64Array(16);return ae(F,p,_,C,M),F}getCameraToClipOrthographic(p,_,C,M,F,z){const H=new Float64Array(16);return le(H,p,_,C,M,F,z),H}getDistanceToElevation(p,_=!1){const C=p===0?0:Xd(p,_?$d(this.position[1]):this.position[1]),M=this.forward();return(C-this.position[2])/M[2]}clone(){return new Tle([...this.position],[...this.orientation])}}const Lfs=Math.tan(85*Math.PI/180);function x8e(N,p,_,C,M,F,z){const H=v();if(_)if(F.name==="globe"){const Y=function(se,me){const{x:xe,y:_e}=se.point,Te=Sdt(xe,_e,se.worldSize/se._pixelsPerMercatorPixel,0,0);return E(Te,Te,iOe(VC(me)))}(M,p);E(H,H,Y)}else{const Y=m([],z);H[0]=Y[0],H[1]=Y[1],H[4]=Y[2],H[5]=Y[3],C||O(H,H,M.angle)}else E(H,M.labelPlaneMatrix,N);return H}function dM(N,p,_,C){const M=[N,p,_,1];_?Ft(M,M,C):fOe(M,M,C);const F=M[3];return M[0]/=F,M[1]/=F,M[2]/=F,M}function Nmt(N,p){return Math.min(.5+N/p*.5,1.5)}function Rfs(N,p){const _=N[0]/N[3],C=N[1]/N[3];return _>=-p[0]&&_<=p[0]&&C>=-p[1]&&C<=p[1]}function kmt(N,p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye,nt){const{lineStartIndex:it,glyphStartIndex:ut,segment:ot}=H,vt=ut+H.numGlyphs,kt=it+H.lineLength,ls=p.getoffsetX(ut),At=p.getoffsetX(vt-1),qt=Mle(N*ls,_,C,M,F,z,ot,it,kt,Y,se,me,xe,_e,!0,Te,De,Ue,Ye,nt);if(!qt)return null;const ts=Mle(N*At,_,C,M,F,z,ot,it,kt,Y,se,me,xe,_e,!0,Te,De,Ue,Ye,nt);return ts?{first:qt,last:ts}:null}function Smt(N,p,_,C){return N===O3.horizontal&&Math.abs(C)>Math.abs(_)?{useVertical:!0}:N===O3.vertical?C>0?{needsFlipping:!0}:null:p!==0&&function(M,F){return M===0||Math.abs(F/M)>Lfs}(_,C)?p===1?{needsFlipping:!0}:null:_<0?{needsFlipping:!0}:null}function Cmt(N,p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye,nt,it,ut,ot){const vt=p/24,kt=N.lineOffsetX*vt,ls=N.lineOffsetY*vt,{lineStartIndex:At,glyphStartIndex:qt,numGlyphs:ts,segment:ns,writingMode:Ps,flipState:Ws}=N,mn=At+N.lineLength,ln=_n=>{if(me){const[rn,In,Pn]=_n.up,$n=se.length;Xoe(me,$n+0,rn,In,Pn),Xoe(me,$n+1,rn,In,Pn),Xoe(me,$n+2,rn,In,Pn),Xoe(me,$n+3,rn,In,Pn)}const[Un,Cs,Xs]=_n.point;X6(se,Un,Cs,Xs,_n.angle)};if(ts>1){const _n=kmt(vt,H,kt,ls,_,xe,_e,N,Y,F,Te,Ue,!1,Ye,nt,it,ut,ot);if(!_n)return{notEnoughRoom:!0};if(C&&!_){let[Un,Cs,Xs]=_n.first.point,[rn,In,Pn]=_n.last.point;[Un,Cs]=dM(Un,Cs,Xs,z),[rn,In]=dM(rn,In,Pn,z);const $n=Smt(Ps,Ws,(rn-Un)*De,In-Cs);if(N.flipState=$n&&$n.needsFlipping?1:2,$n)return $n}ln(_n.first);for(let Un=qt+1;Un0?rn:Tmt(_e,Xs,Un,1,M,void 0,Ye,nt.canonical),Pn=Smt(Ps,Ws,(In[0]-Un[0])*De,In[1]-Un[1]);if(N.flipState=Pn&&Pn.needsFlipping?1:2,Pn)return Pn}const _n=Mle(vt*H.getoffsetX(qt),kt,ls,_,xe,_e,ns,At,mn,Y,F,Te,Ue,!1,!1,Ye,nt,it,ut,ot);if(!_n)return{notEnoughRoom:!0};ln(_n)}return{}}function Amt(N,p,_){const C=1<0?1:-1,kt=0;C&&(vt*=-1,kt=Math.PI),vt<0&&(kt+=Math.PI);let ls=H+z+(vt>0?0:1)|0,At=M,qt=M,ts=0,ns=0;const Ps=Math.abs(ot),Ws=[],mn=[];let ln=F,_n=ln,Un=Ke([]);const Cs=()=>Tmt(_n,ln,qt,Ps-ts+1,me,_e,Ue,Ye.canonical,ut);for(;ts+ns<=Ps;){if(ls+=vt,ls=Y)return null;if(qt=At,_n=ln,Ws.push(qt),Te&&mn.push(_n),ln=new xs(se.getx(ls),se.gety(ls)),At=xe[ls],!At){const or=Emt(ln,Ye.canonical,me,Ue,_e,ut);At=or[3]>0?xe[ls]=or:Cs()}ts+=ns;const On=ft([],At,qt),Ar=Be(qt,At);if(_&&Ar>0&&ns>0&&ze(Un,On)/(ns*Ar)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 C=this._elevation;_||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&C.exaggeration()&&this._centerAltitudeValidForExaggeration!==C.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*C.exaggeration(),this._centerAltitudeValidForExaggeration=C.exaggeration()):(this._centerAltitude=p||0,this._centerAltitudeValidForExaggeration=C.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]],C=this.horizonLineFromTop();let M=0,F=0;for(let z=0;z<_.length;z++){const H=new xs(_[z][0]*this.width,C+_[z][1]*(this.height-C)),Y=p.pointCoordinate(H);if(!Y)continue;const se=1/Math.hypot(Y[0]-this._camera.position[0],Y[1]-this._camera.position[1]);M+=Y[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)),C=this.pixelsPerMeter/this.worldSize*_,M=this._mercatorZfromZoom(p),F=this._mercatorZfromZoom(this._maxZoom),z=Math.max(M-C,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,C=p.elevation,M=_!=null!=(C!=null)||_&&C&&_.exaggeration()!==C.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 C;C=p.z{const Ye=aM(_e,xe,Te,De,Ue);Y.has(Ye)||(F.push(new ug(xe,_e,Te,De,Ue)),Y.add(Ye))};for(let xe=0;xe_e.canonical.z)continue;const Te=_e.canonical,De=_e.overscaledZ,Ue=_e.wrap,Ye=1<0,ut=Te.y+10,vt=_e.wrap-(it?0:1),kt=_e.wrap+(nt?0:1),ls=it?Te.x-1:Ye-1,At=nt?Te.x+1:0;if(z)C[0]<0?(se(De,kt,Te.z,At,Te.y),C[1]<0&&ut&&(se(De,Ue,Te.z,Te.x,Te.y+1),se(De,kt,Te.z,At,Te.y+1)),C[1]>0&&ot&&(se(De,Ue,Te.z,Te.x,Te.y-1),se(De,kt,Te.z,At,Te.y-1))):C[0]>0?(se(De,vt,Te.z,ls,Te.y),C[1]<0&&ut&&(se(De,Ue,Te.z,Te.x,Te.y+1),se(De,vt,Te.z,ls,Te.y+1)),C[1]>0&&ot&&(se(De,Ue,Te.z,Te.x,Te.y-1),se(De,vt,Te.z,ls,Te.y-1))):C[1]<0&&ut?se(De,Ue,Te.z,Te.x,Te.y+1):ot&&se(De,Ue,Te.z,Te.x,Te.y-1);else{const qt=_e.visibleQuadrants;1&qt&&(se(De,vt,Te.z,ls,Te.y),ot&&(se(De,Ue,Te.z,Te.x,Te.y-1),se(De,vt,Te.z,ls,Te.y-1))),2&qt&&(se(De,kt,Te.z,At,Te.y),ot&&(se(De,Ue,Te.z,Te.x,Te.y-1),se(De,kt,Te.z,At,Te.y-1))),4&qt&&(se(De,vt,Te.z,ls,Te.y),ut&&(se(De,Ue,Te.z,Te.x,Te.y+1),se(De,vt,Te.z,ls,Te.y+1))),8&qt&&(se(De,kt,Te.z,At,Te.y),ut&&(se(De,Ue,Te.z,Te.x,Te.y+1),se(De,kt,Te.z,At,Te.y+1)))}}const me=[];for(const xe of F)F.some(_e=>xe.isChildOf(_e))||me.push(xe);if(F=me.filter(xe=>!p.some(_e=>!!(xe.overscaledZ<_&&_e.isChildOf(xe))||xe.equals(_e)||xe.isChildOf(_e))),H){const xe=1<<_,_e=this.projection.name==="globe"?this._camera.mercatorPosition:this.pointCoordinate(this.getCameraPoint()),Te=[xe*_e.x,xe*_e.y],De=4,Ue=De*De;F=F.filter(Ye=>{const nt=Ye.canonical.x+.5-Te[0],it=Ye.canonical.y+.5-Te[1];return nt*nt+it*it{const ls=aM(ut,it,ot,vt,kt);F.has(ls)||(M.push(new ug(it,ut,ot,vt,kt)),F.add(ls))},H=p.reduce((it,ut)=>Math.max(it,ut.overscaledZ),C),Y=1<{const ot=Math.floor(it[0]),vt=Math.floor(it[1]),kt=(it[0]-ot)*Pr,ls=(it[1]-vt)*Pr,At=Math.floor(ut[0]),qt=Math.floor(ut[1]),ts=(ut[0]-At)*Pr,ns=(ut[1]-qt)*Pr;for(let Ps=-1;Ps<=1;Ps++){const Ws=ot+Ps;if(!(Ws<0||Ws>=Y)){me.x=kt-Ps*Pr,xe.x=ts-(Ws-At)*Pr;for(let mn=-1;mn<=1;mn++){const ln=vt+mn;me.y=ls-mn*Pr,xe.y=ns-(ln-qt)*Pr,R9(me,xe,se)&&z(H,0,C,Ws,ln)}}}},Te=_.points,De=Te[3],Ue=Te[2],Ye=this._projectToGround(De,Te[7]),nt=this._projectToGround(Ue,Te[6]);return _e(De,Ye),_e(Ue,nt),M}_projectToGround(p,_){return ht(te(),p,_,p[2]/(p[2]-_[2]))}_projectToZ(p,_,C){const M=p[2]-_[2];return Math.abs(M)<1e-6?J(p):ht(te(),p,_,(p[2]-C)/M)}extendTileCoverForTunnels(p,_,C,M){if(C<18)return[];const F=_.points,z=F[0],H=F[1],Y=F[4],se=F[5];if(Y[2]>=0&&se[2]>=0||z[2]<=0||H[2]<=0)return[];const me=Y[2]<0?this._projectToZ(z,Y,0):Y,xe=se[2]<0?this._projectToZ(H,se,0):se,_e=-M,Te=Y[2]<_e?this._projectToZ(z,Y,_e):Y,De=se[2]<_e?this._projectToZ(H,se,_e):se,Ue=this._findExtensionTilesInQuad(p,C,[De,Te,xe,me],[.5*(me[0]+xe[0]),.5*(me[1]+xe[1])]);return Ue.length>3&&(Ue.length=3),Ue}_findExtensionTilesInQuad(p,_,C,M){const F=[],z=new Set;for(const At of p)z.add(At.key);const H=p.reduce((At,qt)=>Math.max(At,qt.overscaledZ),_),Y=1<<_,se=[new xs(C[0][0],C[0][1]),new xs(C[1][0],C[1][1]),new xs(C[3][0],C[3][1]),new xs(C[2][0],C[2][1]),new xs(C[0][0],C[0][1])],me=C[0][0],xe=C[1][0],_e=C[2][0],Te=C[3][0],De=C[0][1],Ue=C[1][1],Ye=C[2][1],nt=C[3][1],it=Math.max(0,Math.floor(Math.min(me,xe,_e,Te))),ut=Math.min(Y-1,Math.ceil(Math.max(me,xe,_e,Te))-1),ot=Math.max(0,Math.floor(Math.min(De,Ue,Ye,nt))),vt=Math.min(Y-1,Math.ceil(Math.max(De,Ue,Ye,nt))-1);for(let At=ot;At<=vt;At++)for(let qt=it;qt<=ut;qt++){if(!GFe(se,qt,At,qt+1,At+1))continue;const ts=aM(0,H,_,qt,At);z.has(ts)||(F.push(new ug(H,0,_,qt,At)),z.add(ts))}const kt=M[0],ls=M[1];return F.sort((At,qt)=>{const ts=At.canonical.x+.5-kt,ns=At.canonical.y+.5-ls,Ps=qt.canonical.x+.5-kt,Ws=qt.canonical.y+.5-ls;return ts*ts+ns*ns-(Ps*Ps+Ws*Ws)||At.canonical.x-qt.canonical.x||At.canonical.y-qt.canonical.y}),F}coveringTiles(p){let _=this.coveringZoomLevel(p);const C=_,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),Y=this.center.lat,se=1<<_,me=[se*H.x,se*H.y,0],xe=this.projection.name==="globe",_e=!xe,Te=B3.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,_,_e),De=xe?this._camera.mercatorPosition:this.pointCoordinate(this.getCameraPoint()),Ue=se*Xd(1,this.center.lat),Ye=this._camera.position[2]/Xd(1,this.center.lat),nt=[se*De.x,se*De.y,Ye*(_e?1:Ue)],it=xe||M,ut=this.cameraToCenterDistance/p.tileSize*(p.roundZoom?1:.502),ot=this.isLODDisabled(!0)?_:0;let vt;if(this._elevation&&p.isTerrainDEM)vt=1e4*this._elevation.exaggeration();else if(this._elevation){const Cs=this._elevation.getMinMaxForVisibleTiles();vt=Cs?Cs.max:this._centerAltitude}else vt=this._centerAltitude;const kt=p.isTerrainDEM?-vt:this._elevation?this._elevation.getMinElevationBelowMSL():0,ls=this.projection.isReprojectedInTileSpace?zut(this):1,At=Cs=>{const rn=new Q(Cs.x+25e-6,Cs.y,Cs.z),In=new Q(Cs.x,Cs.y+25e-6,Cs.z),Pn=Cs.toLngLat(),$n=rn.toLngLat(),Rn=In.toLngLat(),rr=this.locationCoordinate(Pn),On=this.locationCoordinate($n),Ar=this.locationCoordinate(Rn),or=Math.hypot(On.x-rr.x,On.y-rr.y),vr=Math.hypot(Ar.x-rr.x,Ar.y-rr.y);return Math.sqrt(or*vr)*ls/25e-6},qt=Cs=>{const Xs=vt,rn=kt;return{aabb:Mdt(this,se,0,0,0,Cs,rn,Xs,this.projection),zoom:0,x:0,y:0,minZ:rn,maxZ:Xs,wrap:Cs,fullyVisible:!1}},ts=[];let ns=[];const Ps=_,Ws=p.reparseOverscaled?C:_,mn=(Ye-this._centerAltitude)*Ue,ln=Cs=>{if(!this._elevation||!Cs.tileID||!z)return;const Xs=this._elevation.getMinMaxForTile(Cs.tileID),rn=Cs.aabb;Xs?(rn.min[2]=Xs.min,rn.max[2]=Xs.max,rn.center[2]=(rn.min[2]+rn.max[2])/2):(Cs.shouldSplit=Un(Cs),Cs.shouldSplit||(rn.min[2]=rn.max[2]=rn.center[2]=this._centerAltitude))},_n=(Cs,Xs)=>{if(.707*Xs{if(Cs.zoom=.9)return!0}else if(F&&(In=Cs.aabb.distanceZ(nt)*Ue),this.projection.isReprojectedInTileSpace&&C<=5){const vr=Math.pow(2,Cs.zoom),Ga=At(new Q((Cs.x+.5)/vr,(Cs.y+.5)/vr));Pn=Ga>.85?1:Ga}if(!z&&!xe){const vr=Math.sqrt(Xs*Xs+rn*rn+In*In);let Ga=(1<0;){const Cs=ts.pop(),Xs=Cs.x,rn=Cs.y;let In=Cs.fullyVisible;const Pn=()=>this.projection.name==="globe"&&(Cs.y===0||Cs.y===(1<$n)continue;let Rn=0;if(!In){let or=it?Cs.aabb.intersectsPrecise(Te):Cs.aabb.intersectsPreciseFlat(Te);if(or===0&&Pn()){const vr=new rM(Cs.zoom,Xs,rn);or=rOe(this,se,vr,!0).intersectsPrecise(Te)}if(or===0)continue;if(p.calculateQuadrantVisibility)if(Te.containsPoint(Cs.aabb.center))Rn=15;else for(let vr=0;vr<4;vr++)Cs.aabb.quadrant(vr).intersects(Te)!==0&&(Rn|=1<>1),On={aabb:z?Cs.aabb.quadrant($n):Mdt(this,se,Cs.zoom+1,Rn,rr,Cs.wrap,Cs.minZ,Cs.maxZ,this.projection),zoom:Cs.zoom+1,x:Rn,y:rr,wrap:Cs.wrap,fullyVisible:In,tileID:void 0,shouldSplit:void 0,minZ:Cs.minZ,maxZ:Cs.maxZ};F&&!xe&&(On.tileID=new ug(Cs.zoom+1===Ps?Ws:Cs.zoom+1,Cs.wrap,Cs.zoom+1,Rn,rr),ln(On)),ts.push(On)}}if(this.fogCullDistSq){const Cs=this.fogCullDistSq,Xs=this.horizonLineFromTop();ns=ns.filter(rn=>{const In=[0,0,0,1],Pn=[Pr,Pr,0,1],$n=this.calculateFogTileMatrix(rn.tileID.toUnwrapped());Ft(In,In,$n),Ft(Pn,Pn,$n);const Rn=(or=In,vr=Pn,(Ar=[])[0]=Math.min(or[0],vr[0]),Ar[1]=Math.min(or[1],vr[1]),Ar[2]=Math.min(or[2],vr[2]),Ar[3]=Math.min(or[3],vr[3]),Ar),rr=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}([],In,Pn),On=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}(Rn,rr);var Ar,or,vr;if(On===0)return!0;let Ga=!1;const Wa=this._elevation;if(Wa&&On>Cs&&Xs!==0){const oi=this.calculateProjMatrix(rn.tileID.toUnwrapped());let Fa;p.isTerrainDEM||(Fa=Wa.getMinMaxForTile(rn.tileID)),Fa||(Fa={min:kt,max:vt});const Ai=function(Fo){const rl=Math.round((Fo+45+360)%360/90)%4;return Th[rl]}(this.rotation),Ni=[Ai[0]*Pr,Ai[1]*Pr,Fa.max];Qe(Ni,Ni,oi),Ga=(1-Ni[1])*this.height*.5Cs.distanceSq-Xs.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 _=ea(p.lat,-85.051129,L),C=this.projection.project(p.lng,_);return new xs(C.x*this.worldSize,C.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/Xd(1,this.center.lat)/this.worldSize}setLocationAtPoint(p,_){let C,M;const F=this.centerPoint;if(this.projection.name==="globe"){const H=this.worldSize;C=(_.x-F.x)/H,M=(_.y-F.y)/H}else{const H=this.pointCoordinate(_),Y=this.pointCoordinate(F);C=H.x-Y.x,M=H.y-Y.y}const z=this.locationCoordinate(p);this.setLocation(new Q(z.x-C,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 C=_?Xd(_,p.lat):void 0,M=this.projection.project(p.lng,p.lat);return new Q(M.x,M.y,C)}coordinateLocation(p){return this.projection.unproject(p.x,p.y)}pointRayIntersection(p,_){const C=_??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];bs(M,M,1/M[3]),bs(F,F,1/z);const H=M[2],Y=F[2];return{p0:M,p1:F,t:H===Y?0:(C-H)/(Y-H)}}screenPointToMercatorRay(p){const _=[p.x,p.y,0,1],C=[p.x,p.y,1,1];return Ft(_,_,this.pixelMatrixInverse),Ft(C,C,this.pixelMatrixInverse),bs(_,_,1/_[3]),bs(C,C,1/C[3]),_[2]=Xd(_[2],this._center.lat)*this.worldSize,C[2]=Xd(C[2],this._center.lat)*this.worldSize,bs(_,_,1/this.worldSize),bs(C,C,1/this.worldSize),new Eoe([_[0],_[1],_[2]],qe([],ft([],C,_)))}rayIntersectionCoordinate(p){const{p0:_,p1:C,t:M}=p,F=Xd(_[2],this._center.lat),z=Xd(C[2],this._center.lat);return new Q(ya(_[0],C[0],M)/this.worldSize,ya(_[1],C[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 C=this.projection.pointCoordinate3D(this,p.x,p.y);if(C)return new Q(C[0],C[1],C[2]);let M=0,F=this.horizonLineFromTop();if(p.y>F)return this.pointCoordinate(p,_);const z=.02*F,H=p.clone();for(let Y=0;Y<10&&F-M>z;Y++){H.y=ya(M,F,.66);const se=this.projection.pointCoordinate3D(this,H.x,H.y);se?(F=H.y,C=se):M=H.y}return C?new Q(C[0],C[1],C[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 C=_&&this.elevation?this.elevation.getAtPointOrZero(p,this._centerAltitude):this._centerAltitude,M=[p.x*this.worldSize,p.y*this.worldSize,C+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,C=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,C)),Y=this.pointLocation3D(new xs(_,C));let se=Math.min(F.lng,z.lng,H.lng,Y.lng),me=Math.max(F.lng,z.lng,H.lng,Y.lng),xe=Math.min(F.lat,z.lat,H.lat,Y.lat),_e=Math.max(F.lat,z.lat,H.lat,Y.lat);const Te=Math.pow(2,-this.zoom)/16*270,De=this.projection.name==="globe"?1:4,Ue=(Ye,nt,it,ut,ot)=>{const vt=(Ye+it)/2,kt=(nt+ut)/2,ls=new xs(vt,kt),{lng:At,lat:qt}=this.pointLocation3D(ls),ts=Math.max(0,se-At,xe-qt,At-me,qt-_e);se=Math.min(se,At),me=Math.max(me,At),xe=Math.min(xe,qt),_e=Math.max(_e,qt),(otTe)&&(Ue(Ye,nt,vt,kt,ot+1),Ue(vt,kt,it,ut,ot+1))};if(Ue(_,p,M,p,1),Ue(M,p,M,C,1),Ue(M,C,_,C,1),Ue(_,C,_,p,1),this.projection.name==="globe"){const[Ye,nt]=function(it){const ut=w(new Float64Array(16));E(ut,it.pixelMatrix,it.globeMatrix);const ot=[0,Vv,0],vt=[0,q_,0];return Qe(ot,ot,ut),Qe(vt,vt,ut),[ot[0]>0&&ot[0]<=it.width&&ot[1]>0&&ot[1]<=it.height&&!lOe(it,new Il(it.center.lat,90)),vt[0]>0&&vt[0]<=it.width&&vt[1]>0&&vt[1]<=it.height&&!lOe(it,new Il(it.center.lat,-90))]}(this);Ye?(_e=90,me=180,se=-180):nt&&(xe=-90,me=180,se=-180)}return new V_(new Il(se,xe),new Il(me,_e))}_getBoundsRectangular(p,_){const{top:C,left:M}=this._edgeInsets,F=this.height-this._edgeInsets.bottom,z=this.width-this._edgeInsets.right,H=new xs(M,C),Y=new xs(z,C),se=new xs(z,F),me=new xs(M,F);let xe=this.pointCoordinate(H,p),_e=this.pointCoordinate(Y,p);const Te=this.pointCoordinate(se,_),De=this.pointCoordinate(me,_),Ue=(Ye,nt)=>(nt.y-Ye.y)/(nt.x-Ye.x);return xe.y>1&&_e.y>=0?xe=new Q((1-De.y)/Ue(De,xe)+De.x,1):xe.y<0&&_e.y<=1&&(xe=new Q(-De.y/Ue(De,xe)+De.x,0)),_e.y>1&&xe.y>=0?_e=new Q((1-Te.y)/Ue(Te,_e)+Te.x,1):_e.y<0&&xe.y<=1&&(_e=new Q(-Te.y/Ue(Te,_e)+Te.x,0)),new V_().extend(this.coordinateLocation(xe)).extend(this.coordinateLocation(_e)).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((C,M)=>{if(M.dem){const F=M.dem.tree;C.min=Math.min(C.min,F.minimums[0]),C.max=Math.max(C.max,F.maximums[0])}return C},{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,C=this.height/2-_*(1-this._horizonShift);return p?Math.max(0,C):C}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-meTe&&(z=Te-Y),Te-_e{for(let Ws=0;Ws<16;Ws++)qt[Ws]=ya(ts[Ws],ns[Ws],Ps)})(H,H,Y,vo(this.pitch>=e$?1:this.pitch/e$))}else H=Y;const se=re([],Y,z),me=re([],H,z);if(this.projection.isReprojectedInTileSpace){const vt=this.locationCoordinate(this.center);w(this._mat4Scratch);const kt=this._mat4Scratch;I(kt,kt,[vt.x*this.worldSize,vt.y*this.worldSize,0]),E(kt,kt,Out(this)),I(kt,kt,[-vt.x*this.worldSize,-vt.y*this.worldSize,0]),E(me,me,kt),E(se,se,kt),this.inverseAdjustmentMatrix=function(ls){const At=Out(ls,!0);return m([],[At[0],At[1],At[4],At[5]])}(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(P(this.mercatorMatrix,me,[this.worldSize,this.worldSize,this.worldSize/F,1]),this.projMatrix=me,A(this.invProjMatrix,this.projMatrix),_){const vt=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);vt[8]=2*-p.x/this.width,vt[9]=2*p.y/this.height,re(this._expandedFarZProjMatrixBuf,vt,z),this.expandedFarZProjMatrix=this._expandedFarZProjMatrixBuf}else this.expandedFarZProjMatrix=this.projMatrix;A(this._mat4Scratch,H),this.frustumCorners=tOe.fromInvProjectionMatrix(this._mat4Scratch,this.horizonLineFromTop(),this.height),this.cameraFrustum=B3.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 _e=this.point,Te=_e.x,De=_e.y,Ue=this.width%2/2,Ye=this.height%2/2,nt=Math.cos(this.angle),it=Math.sin(this.angle),ut=Te-Math.round(Te)+nt*Ue+it*Ye,ot=De-Math.round(De)+nt*Ye+it*Ue;if(b(this.alignedProjMatrix,me),I(this.alignedProjMatrix,this.alignedProjMatrix,[ut>.5?ut-1:ut,ot>.5?ot-1:ot,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={},!A(this.pixelMatrixInverse,this.pixelMatrix))throw new Error("failed to invert matrix");if(this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=function(kt){const{x:ls,y:At}=kt.point,{lng:qt,lat:ts}=kt._center;return Sdt(ls,At,kt.worldSize,qt,ts)}(this);const vt=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=Qe(vt,vt,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,C=this._camera.position,M=1/this.height/this._pixelsPerMercatorPixel,F=[p,p,_];Fe(F,F,M),Fe(C,C,-1),Ee(C,C,F),U(this.mercatorFogMatrix,C),P(this.mercatorFogMatrix,this.mercatorFogMatrix,F),this.worldToFogMatrix=this._camera.getWorldToCameraPosition(p,_,M)}_computeCameraPosition(p){const _=(p=p||this.pixelsPerMeter)/this.pixelsPerMeter,C=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-C[0]*F,M.y/this.worldSize-C[1]*F,p/this.worldSize*this._centerAltitude-C[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),C=this._camera.position[2],M=p[2];let F=1;this.projection.wrap&&(this.center=this.center.wrap()),M>0&&(F=Math.min((_-C)/M,1)),this._camera.position=Ne([],this._camera.position,p,F),this._updateStateFromCamera()}_updateStateFromCamera(){const p=this._camera.position,_=this._camera.forward(),{pitch:C,bearing:M}=this._camera.getPitchBearing(),F=Xd(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,z=this._mercatorZfromZoom(this._maxZoom)*Math.cos(Yr(this._maxPitch)),H=Math.max((p[2]-F)/Math.cos(C),z),Y=this._zoomFromMercatorZ(H);Ne(p,p,_,H),this._pitch=ea(C,Yr(this.minPitch),Yr(this.maxPitch)),this.angle=ml(M,-Math.PI,Math.PI),this._setZoom(ea(Y,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,C=6,M=0,F=1/0;for(;C-_>1e-6&&C>_;){const z=_+.5*(C-_),H=this.tileSize*Math.pow(2,z),Y=this.getCameraToCenterDistance(this.projection,z,H),se=this.scaleZoom(Y/(Math.max(0,p)*this.tileSize)),me=Math.abs(z-se);mese||_e.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 C=ce(ft([],this._camera.position,p)),M=this._zoomFromMercatorZ(C)+_;return C-this._mercatorZfromZoom(M)}getCameraPoint(){if(this.projection.name==="globe"){const p=function([_,C,M],F){const z=[_,C,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,C=this.worldSize){const M=UY(p,_,this.width,this.height,1024),F=p.pixelSpaceConversion(this.center.lat,C,M);let z=.5/Math.tan(.5*this._fov)*this.height*F;return this.isOrthographic&&(z=ya(1,z,vo(this.pitch>=e$?1:this.pitch/e$))),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 B3.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,p,this.projection.zAxisUnit==="meters")}}const t$=(N,p)=>{if(p<=0||N.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const _=N.transform,C=_.pitch,M=_.isLODDisabled(!1)?60:30;if(C0,uniformValues:{u_cutoff_params:[_._nearZ,_._farZ,(me-_._nearZ)/F,(me-xe-_._nearZ)/F]}}};function v8e(N,p,_,C){const M=1<({u_matrix:N,u_color:p,u_overlay:0,u_overlay_scale:_}),WC=new Float64Array(16),uM=new Float64Array(16),Pmt=new Float64Array(16),b8e=new Float64Array(16),_8e=new Float64Array(16),Ple=new Float64Array(16),Dfs=new Float64Array(16),Ile=[0,0,0],Ffs=new Float32Array(16),Lle=[0,0,0],Ofs=[0,0,0],w8e=[];function Imt(N,p,_){const C=_.cameraWorldSizeForFog/_.worldSize;return P(N,_.worldToFogMatrix,[C,C,1]),E(N,N,p),N}function JY(N,p,_,C){return I(N,p,_),Je(C,Dms)||P(N,N,C),N}function zfs(N,p,_,C){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,C?1:0,0]}function Bfs(N,p){return p.featureBuffer?N.partStyleUBO:null}function j8e(N,p,_,C,M,F=null){const z=_.material,H=C.context,{baseColorTexture:Y,metallicRoughnessTexture:se}=z.pbrMetallicRoughness,{normalTexture:me,occlusionTexture:xe,emissionTexture:_e}=z;function Te(Ue,Ye,nt){if(Ue&&(N.push(Ye),H.activeTexture.set(H.gl.TEXTURE0+nt),Ue.gfxTexture)){const{minFilter:it,magFilter:ut,wrapS:ot,wrapT:vt}=Ue.sampler;Ue.gfxTexture.bindExtraParam(it,ut,ot,vt)}}Te(Y,"HAS_TEXTURE_u_baseColorTexture",Hv.BaseColor),Te(se,"HAS_TEXTURE_u_metallicRoughnessTexture",Hv.MetallicRoughness),Te(me,"HAS_TEXTURE_u_normalTexture",Hv.Normal),Te(xe,"HAS_TEXTURE_u_occlusionTexture",Hv.Occlusion),Te(_e,"HAS_TEXTURE_u_emissionTexture",Hv.Emission),M&&(M.texture||(M.texture=new Kdt(C.context,M.image,[M.image.height,M.image.height,M.image.height],H.gl.RGBA8)),H.activeTexture.set(H.gl.TEXTURE0+Hv.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=C.shadowRenderer;De&&(N.push("RENDER_SHADOWS"),De.useNormalOffset&&N.push("NORMAL_OFFSET"))}function N8e(N,p,_,C,M,F){const z=N.modelOpacity,H=p.context,Y=new vy(p.context.gl.LEQUAL,N.isLightMesh?vy.ReadOnly:vy.ReadWrite,p.depthRangeFor3D),se=p.transform,me=N.mesh,xe=me.material,_e=xe.pbrMetallicRoughness,Te=p.style.fog;p.transform.projection.zAxisUnit==="pixels"?WC.set(N.nodeModelMatrix):E(WC,C.zScaleMatrix,N.nodeModelMatrix),E(WC,C.negCameraPosMatrix,WC),A(uM,WC),S(uM,uM);const De=_.paint.get("model-color-use-theme").constantOr("default")==="none",Ue=_.paint.get("model-emissive-strength").constantOr(0),Ye={defines:[]},nt=[],it=p.shadowRenderer;it&&(it.useNormalOffset=!1),j8e(Ye.defines,nt,me,p,De?null:_.lut);let ut=null;if(Te&&(ut=Imt(Pmt,N.nodeModelMatrix,p.transform),se.projection.name!=="globe")){const ls=me.aabb.min,At=me.aabb.max,[qt,ts]=Te.getOpacityForBounds(ut,ls[0],ls[1],At[0],At[1]);Ye.overrideFog=qt>=PY||ts>=PY}const ot=t$(p,_.paint.get("model-cutoff-fade-range"));ot.shouldRenderCutoff&&Ye.defines.push("RENDER_CUTOFF");const vt=p.getOrCreateProgram("model",Ye),kt=u8e(N.worldViewProjection,WC,uM,null,p,z,_e.baseColorFactor,xe.emissiveFactor,_e.metallicFactor,_e.roughnessFactor,xe,Ue,_,void 0,void 0,N.materialOverride,N.modelColor,1,vt.fixedDefines.includes("LIGHTING_3D_MODE"));p.uploadCommonUniforms(H,vt,null,ut,ot,N.lightOverrides),p.renderPass!=="shadow"&&it&&it.setupShadowsFromMatrix(N.nodeModelMatrix,vt),vt.draw(p,H.gl.TRIANGLES,Y,M,F,me.material.doubleSided?by.disabled:by.backCCW,kt,_.id,me.vertexBuffer,me.indexBuffer,me.segments,_.paint,p.transform.zoom,void 0,nt)}function Lmt(N,p){return N.style._importedAsBasemap?"basemap":p.scope}function k8e(N,p,_,C,M,F,z,H,Y,se,me){const xe=N.transform,_e=!!p.isGeometryBloom&&p.isGeometryBloom;if(p.minZoom!==void 0&&N.transform.zoomp.maxZoom||_e&&N.renderPass==="shadow")return;const Te=xe.projection.name==="globe"?ule(_,xe):[..._];E(Te,Te,p.globalMatrix);const De=E([],C,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:_e,materialOverride:Ye,modelOpacity:Y,modelColor:se,lightOverrides:me,node:p,modelMatrix:_});continue}const nt=Qe([],Ue.centroid,De);!xe.isOrthographic&&nt[2]<=0||F.push({mesh:Ue,depth:nt[2],modelIndex:M,worldViewProjection:De,nodeModelMatrix:Te,isLightMesh:_e,materialOverride:Ye,modelOpacity:Y,modelColor:se,lightOverrides:me,node:p,modelMatrix:_})}if(p.children)for(const Ue of p.children)k8e(N,Ue,_,C,M,F,z,H,Y,se,me)}function eZ(N,p,_,C,M){const F=_.shadowRenderer;if(!F)return;const z=F.getShadowPassDepthMode(),H=M||F.calculateShadowPassMatrixFromMatrix(p),Y=bmt(H);_.getOrCreateProgram("modelDepth").draw(_,_.context.gl.TRIANGLES,z,lj.disabled,wh.disabled,by.disabled,Y,C.id,N.vertexBuffer,N.indexBuffer,N.segments,C.paint,_.transform.zoom,void 0,void 0)}function Rmt(N,p,_,C){const M=function(me,xe){if(xe.footprintDebugMesh)return xe.footprintDebugMesh;if(!xe.footprint)return null;const _e=me.context,Te=xe.footprint.vertices,De=xe.footprint.indices,Ue=new Gs;Ue.reserve(Te.length);for(const ts of Te)Ue.emplaceBack(ts.x,ts.y);const Ye=new $r;Ye.reserve(De.length);for(let ts=0;ts0){const _e=F.terrain,Te=_e.findDEMTileFor(H);Te&&Te.dem?Y=U9.create(_e,H,Te):xe=0}if(xe===0&&(z.terrainElevationMin=0,z.terrainElevationMax=0),xe===z.validForExaggeration&&(xe===0||Y&&Y._demTile&&Y._demTile.tileID===z.validForDEMTile.id&&Y._dem._timestamp===z.validForDEMTile.timestamp))return!1;for(const _e in z.instancesPerModel){const Te=z.instancesPerModel[_e];for(let De=0;Dese&&(se=Te.max)}const me=ea(C.x,F,z)-C.x,xe=ea(C.y,H,Y)-C.y,_e=Xd(se,p.center.lat)-C.z;return p._zoomFromMercatorZ(Math.sqrt(me*me+xe*xe+_e*_e))}function Fmt(N,p,_,C,M,F,z){const H=N.context,Y=N.renderPass==="shadow",se=N.shadowRenderer,me=Y&&se?se.getShadowPassDepthMode():new vy(H.gl.LEQUAL,vy.ReadWrite,N.depthRangeFor3D),xe=N.isTileAffectedByFog(F),_e=N.transform.projection.name==="globe";if(_.meshes)for(const Te of _.meshes){const De=_e?[]:["MODEL_POSITION_ON_GPU"],Ue=[];let Ye,nt,it;const ut=!_e&&C.instancedDataArray.length>20;ut&&De.push("INSTANCED_ARRAYS");const ot=t$(N,p.paint.get("model-cutoff-fade-range"));if(ot.shouldRenderCutoff&&De.push("RENDER_CUTOFF"),Y&&se)Ye=N.getOrCreateProgram("modelDepth",{defines:De}),nt=bmt(z.shadowTileMatrix,z.shadowTileMatrix,_.globalMatrix),it=wh.disabled;else{j8e(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 kt=Te.material,ls=kt.pbrMetallicRoughness,At=p.paint.get("model-opacity").constantOr(1),qt=p.paint.get("model-emissive-strength").constantOr(0);nt=u8e(F.expandedProjMatrix,_.globalMatrix,Ffs,null,N,At,ls.baseColorFactor,kt.emissiveFactor,ls.metallicFactor,ls.roughnessFactor,kt,qt,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)),it=ot.shouldRenderCutoff||At<1||kt.alphaMode!=="OPAQUE"?wh.alphaBlended:wh.unblended}N.uploadCommonUniforms(H,Ye,F.toUnwrapped(),null,ot);const vt=Te.material.doubleSided?by.disabled:by.backCCW;if(ut)Ue.push(C.instancedDataBuffer),Ye.draw(N,H.gl.TRIANGLES,me,lj.disabled,it,vt,nt,p.id,Te.vertexBuffer,Te.indexBuffer,Te.segments,p.paint,N.transform.zoom,void 0,Ue,C.instancedDataArray.length);else{const kt=Y?"u_instance":"u_normal_matrix";for(let ls=0;ls0)if(N.targetLod<0)N.targetLod=p>C?1:0;else{const z=M>0?_/1e3/M:1;N.targetLod=ea(p>C?N.targetLod+z:N.targetLod-z,0,1)}else N.targetLod=0}function Gfs(N,p,_,C){if(!_.modelManager)return!0;const M=_.modelManager;if(!_.shadowRenderer)return!0;const F=_.shadowRenderer,z=p.aabb;let H=!0,Y=N.maxHeight;if(Y===0){let me=0;for(const xe in N.instancesPerModel){const _e=M.getModel(xe,C);_e?me=Math.max(me,Math.max(Math.max(_e.aabb.max[0],_e.aabb.max[1]),_e.aabb.max[2])):H=!1}Y=N.maxScale*me*1.41+N.maxVerticalOffset,H&&(N.maxHeight=Y)}z.max[2]=Y,z.min[2]+=N.terrainElevationMin,z.max[2]+=N.terrainElevationMax,Qe(z.min,z.min,p.tileMatrix),Qe(z.max,z.max,p.tileMatrix);const se=z.intersects(F.getCurrentCascadeFrustum());return _.currentShadowCascade===0&&(N.isInsideFirstShadowMapFrustum=se===2),se===0}function Wfs(N,p){const _=N.uniformValues.u_cutoff_params[0],C=N.uniformValues.u_cutoff_params[1],M=N.uniformValues.u_cutoff_params[2],F=N.uniformValues.u_cutoff_params[3];return C===_||F===M?1:ea(((p-_)/(C-_)-M)/(F-M),0,1)}function Kfs(N,p,_,C){if(p.pitch<20)return 1;const M=p.getWorldToCameraMatrix();E(M,M,N);const F=as(_.min[0],_.min[1],_.min[2],1);let z=Ft(Ht(),F,M),H=z,Y=z;F[1]=_.max[1],z=Ft(Ht(),F,M),H=z[1]Y[1]?z:Y,F[0]=_.max[0],z=Ft(Ht(),F,M),H=z[1]Y[1]?z:Y,F[1]=_.min[1],z=Ft(Ht(),F,M),H=z[1]Y[1]?z:Y;const se=ea(C[0],0,1),me=100*p.pixelsPerMeter*ea(C[1],0,1),xe=ea(C[2],0,1),_e=(Ue=Ht(),ot=(Ye=H)[1],vt=Ye[2],kt=Ye[3],Ue[0]=(ut=Ye[0])+(it=se)*((nt=Y)[0]-ut),Ue[1]=ot+it*(nt[1]-ot),Ue[2]=vt+it*(nt[2]-vt),Ue[3]=kt+it*(nt[3]-kt),Ue),Te=Math.tan(.5*p.fovX),De=-_e[2]*Te;var Ue,Ye,nt,it,ut,ot,vt,kt;if(me===0)return _e[1]<-Math.abs(De)?xe:1;const ls=ea(ya(1,xe,(-Math.abs(De)-_e[1])/me),xe,1);return ya(1,ls,ea((p.pitch-20)/20,0,1))}var S8e=` #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`,Omt=` #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 }`,zmt=` #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 `,Bmt="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;}",$mt=` #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`,Umt=`#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`,qmt=`#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`,C8e=` #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`,Vmt=`#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`,Hmt=`#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`,Gmt=`#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 Wmt=/^#include\s+"([^"]+)"\s*\r?\n/gm,Kmt=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,Yfs=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,Zfs=new Set(["ifdef","ifndef","elif","if","defined"]),Rle=new Set;s$(S8e,Rle),s$(zmt,Rle),s$(Omt,Rle);const Ymt={"_prelude_fog.vertex.glsl":Umt,"_prelude_terrain.vertex.glsl":$mt,"_prelude_shadow.vertex.glsl":Hmt,"_prelude_material_table.vertex.glsl":"","_prelude_fog.fragment.glsl":qmt,"_prelude_shadow.fragment.glsl":Gmt,"_prelude_lighting.glsl":C8e,"_prelude_raster_array.glsl":Vmt,"_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) `},Dle={},Zmt="precision highp float;",Xmt="precision mediump float;",Qmt=` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,Jmt={preludeTerrain:hd("",$mt),preludeFog:hd(qmt,Umt),preludeShadow:hd(Gmt,Hmt),preludeRasterArray:hd(Vmt,""),preludeLighting:hd(C8e,C8e),preludePrecisionQualifiers:hd(Xmt,Zmt),prelude:hd(Omt,zmt),preludeExtensions:hd(Qmt,"")},Xfs=[Qmt,Xmt,S8e,Jmt.prelude.fragmentSource].join(` `),Qfs=[Zmt,S8e,Jmt.prelude.vertexSource].join(` `);var Jfs={background:hd(`#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:hd(`#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:hd(`#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:hd("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:hd(`#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:hd(`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:hd("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:hd("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:hd("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:hd(`#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:hd(`#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:hd(`#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:hd(`#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:hd(`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:hd("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:hd(`#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:hd(`#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:hd(`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:hd(`#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:hd(`#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:hd(`#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:hd(`#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:hd(`#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:hd(`#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 }`,Bmt),skyboxGradient:hd(`#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 }`,Bmt),skyboxCapture:hd(` 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:hd(`#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:hd(`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:hd("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 s$(N,p){const _=N.split(` `);for(let C of _){if(C=C.trimStart(),C[0]!=="#"||!C.includes("if")||C.startsWith("#endif"))continue;const M=C.match(Yfs);if(M)for(const F of M)Zfs.has(F)||p.add(F)}}function eft(N){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(N)}function hd(N,p){const _=new Set,C=[],M=[];N=N.replace(Wmt,(z,H)=>(M.push(H),"")),p=p.replace(Wmt,(z,H)=>(C.push(H),""));let F=new Set(Rle);s$(N,F),s$(p,F);for(const z of[...C,...M])Dle[z]||(Dle[z]=new Set,s$(Ymt[z],Dle[z])),F=new Set([...F,...Dle[z]]);return{fragmentSource:N=N.replace(Kmt,(z,H,Y,se,me)=>(_.add(me),H==="define"?` #ifndef HAS_UNIFORM_u_${me} ${eft(se)?"flat ":""}in ${Y} ${se} ${me}; #else uniform ${Y} ${se} u_${me}; #endif `:H==="initialize"?` #ifdef HAS_UNIFORM_u_${me} ${Y} ${se} ${me} = u_${me}; #endif `:H==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${me} in ${Y} ${se} ${me}; #endif `:H==="initialize-attribute"?"":void 0)),vertexSource:p=p.replace(Kmt,(z,H,Y,se,me)=>{const xe=`MATERIAL_ATTRIBUTE_OFFSET_${me}`,_e=se==="float"?"vec2":se,Te=`GET_ATTRIBUTE_${_e}(a_${me}, materialInfo, ${xe})`,De=me.includes("color")?"color":_e;return H==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${me} in ${Y} ${se} a_${me}; #endif `:_.has(me)?H==="define"?` #ifndef HAS_UNIFORM_u_${me} uniform lowp float u_${me}_t; #if !defined(${xe}) in ${Y} ${_e} a_${me}; #endif ${eft(se)?"flat ":""}out ${Y} ${se} ${me}; #else uniform ${Y} ${se} u_${me}; #endif `:H==="initialize"?De==="vec4"||De==="uvec4"?` #ifndef HAS_UNIFORM_u_${me} ${me} = a_${me}; #else ${Y} ${se} ${me} = u_${me}; #endif `:` #if !defined(HAS_UNIFORM_u_${me}) #ifdef ${xe} ${me} = unpack_mix_${De}(${Te}, u_${me}_t); #else ${me} = unpack_mix_${De}(a_${me}, u_${me}_t); #endif #else ${Y} ${se} ${me} = u_${me}; #endif `:H==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${me} in ${Y} ${se} a_${me}; out ${Y} ${se} ${me}; #endif `:H==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${me} ${me} = a_${me}; #endif `:void 0:H==="define"?` #ifndef HAS_UNIFORM_u_${me} uniform lowp float u_${me}_t; #if !defined(${xe}) in ${Y} ${_e} a_${me}; #endif #else uniform ${Y} ${se} u_${me}; #endif `:H==="define-instanced"?De==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${me}0; in vec4 a_${me}1; in vec4 a_${me}2; in vec4 a_${me}3; #else uniform ${Y} ${se} u_${me}; #endif `:` #ifdef INSTANCED_ARRAYS in ${Y} ${_e} a_${me}; #else uniform ${Y} ${se} u_${me}; #endif `:H==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${me} ${Y} ${se} ${me} = a_${me}; #endif `:De==="vec4"||De==="uvec4"?` #ifndef HAS_UNIFORM_u_${me} #ifdef ${xe} ${Y} ${se} ${me} = ${Te}; #else ${Y} ${se} ${me} = a_${me}; #endif #else ${Y} ${se} ${me} = u_${me}; #endif `:` #ifndef HAS_UNIFORM_u_${me} #ifdef ${xe} ${Y} ${se} ${me} = unpack_mix_${De}(${Te}, u_${me}_t); #else ${Y} ${se} ${me} = unpack_mix_${De}(a_${me}, u_${me}_t); #endif #else ${Y} ${se} ${me} = u_${me}; #endif `}),usedDefines:F,vertexIncludes:C,fragmentIncludes:M}}var eps={model:hd(`#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:hd("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:hd("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:hd(`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:hd(`#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 tps=(N,p)=>({u_matrix:N,u_ground_shadow_factor:p});function tft(N,p,_=0){const C=Math.pow(2,p.tileID.overscaledZ),M=p.tileSize*Math.pow(2,N.transform.tileZoom)/C,F=M*(p.tileID.canonical.x+p.tileID.wrap*C),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/YY(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 Fle={terrain:0,flat:1},sps=v(),sft=[0,0,0],nft=(N,p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye,nt,it=[0,0,1],ut=!1)=>{let ot=sft,vt=0,kt=sft;if(!ut){const qt=p.style.light,ts=qt.properties.get("position");if(ot=[ts.x,ts.y,ts.z],qt.properties.get("anchor")==="viewport"){const Ps=f();x(Ps,-p.transform.angle),at(ot,ot,Ps)}const ns=qt.properties.get("color").toPremultipliedRenderColor(null);vt=qt.properties.get("intensity"),kt=[ns.r,ns.g,ns.b]}const ls=p.transform,At={u_matrix:N,u_lightpos:ot,u_lightintensity:vt,u_lightcolor:kt,u_vertical_gradient:+_,u_opacity:C,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:Fle[se],u_base_type:Fle[me],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:nt,u_front_cutoff_params:it};return ls.projection.name==="globe"&&(At.u_tile_id=[H.canonical.x,H.canonical.y,1<{let rn=qt;_n.groundRadiusBuffer!=null&&(rn=qt.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const In=_n.programConfigurations.get(C.id),Pn=p.isTileAffectedByFog(ln),$n=p.getOrCreateProgram("fillExtrusionGroundEffect",{config:In,defines:rn,overrideFog:Pn}),Rn=((On,Ar,or,vr,Ga,Wa,oi,Fa,Ai,Ni)=>({u_matrix:On,u_opacity:Ar,u_ao_pass:or?1:0,u_meter_to_tile:vr,u_ao:Ga,u_flood_light_intensity:Wa,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,Xs,[_e,Te*Xs],De,Ue,Ye,At>=17?0:Ps*Xs,ut?ut.size[0]:0),rr=[];nt&&rr.push(_n.hiddenByLandmarkVertexBuffer),_n.groundRadiusBuffer!=null&&rr.push(_n.groundRadiusBuffer),p.uploadCommonUniforms(vt,$n,ln.toUnwrapped(),null,Ws),$n.draw(p,vt.gl.TRIANGLES,F,z,H,Y,Rn,C.id,_n.vertexBuffer,_n.indexBuffer,Un,C.paint,At,In,rr)};for(const ln of M){const _n=_.getTile(ln),Un=_n.getBucket(C);if(!Un||Un.projection.name!==ls.projection.name||!Un.groundEffect||Un.groundEffect&&!Un.groundEffect.hasData())continue;const Cs=Un.groundEffect,Xs=1/Un.tileToMeter;{const rn=p.translatePosMatrix(ln.projMatrix,_n,ts,ns),In=Cs.getDefaultSegment();mn(ln,Cs,In,rn,Xs)}if(it)for(let rn=0;rn<4;rn++){const In=Tdt[rn](ln),Pn=_.getTile(In);if(!Pn)continue;const $n=Pn.getBucket(C);if(!$n||$n.projection.name!==ls.projection.name||!$n.groundEffect||$n.groundEffect&&!$n.groundEffect.hasData())continue;const Rn=$n.groundEffect;let rr,On;rn===0?(rr=[-8192,0,0],On=1):rn===1?(rr=[Pr,0,0],On=0):rn===2?(rr=[0,-8192,0],On=3):(rr=[0,Pr,0],On=2);const Ar=Rn.regionSegments[On];Ar&&(I(rft,ln.projMatrix,rr),mn(ln,Rn,Ar,p.translatePosMatrix(rft,_n,ts,ns),Xs))}}}const nps={model:N=>({u_matrix:new Of(N),u_lighting_matrix:new Of(N),u_normal_matrix:new Of(N),u_node_matrix:new Of(N),u_lightpos:new Um(N),u_lightintensity:new lo(N),u_lightcolor:new Um(N),u_camera_pos:new Um(N),u_opacity:new lo(N),u_baseColorFactor:new G_(N),u_emissiveFactor:new G_(N),u_metallicFactor:new lo(N),u_roughnessFactor:new lo(N),u_baseTextureIsAlpha:new $m(N),u_alphaMask:new $m(N),u_alphaCutoff:new lo(N),u_baseColorTexture:new $m(N),u_metallicRoughnessTexture:new $m(N),u_normalTexture:new $m(N),u_occlusionTexture:new $m(N),u_emissionTexture:new $m(N),u_lutTexture:new $m(N),u_color_mix:new G_(N),u_aoIntensity:new lo(N),u_emissive_strength:new lo(N),u_occlusionTextureTransform:new G_(N),u_dithered_discard_threshold:new lo(N),u_model_mesh_params:new G_(N)}),modelDepth:N=>({u_matrix:new Of(N),u_instance:new Of(N),u_node_matrix:new Of(N)}),groundShadow:N=>({u_matrix:new Of(N),u_ground_shadow_factor:new Um(N)}),fillExtrusionDepth:N=>({u_matrix:new Of(N),u_edge_radius:new lo(N),u_width_scale:new lo(N),u_vertical_scale:new lo(N),u_height_type:new $m(N),u_base_type:new $m(N)}),fillExtrusionGroundEffect:N=>({u_matrix:new Of(N),u_opacity:new lo(N),u_ao_pass:new lo(N),u_meter_to_tile:new lo(N),u_ao:new up(N),u_flood_light_intensity:new lo(N),u_flood_light_color:new Um(N),u_attenuation:new lo(N),u_edge_radius:new lo(N),u_fb:new $m(N),u_fb_size:new lo(N),u_dynamic_offset:new lo(N)})};function ift(N){const p=N.properties.get("direction"),_=lm(p.x,p.y,p.z);_[2]=ea(_[2],0,75);const C=Mh([_[0],_[1],_[2]]);return ve(C.x,C.y,C.z)}function oft(N,p,_){const C=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],Y=_.properties.get("color-use-theme")==="none",se=_.properties.get("color"),me=_.properties.get("intensity"),xe=Math.max(ze([0,0,1],H),0),_e=[0,0,0];Fe(_e,se.toPremultipliedRenderColor(Y?null:N.getLut(p.scope)).toArray01Linear().slice(0,3),me);const Te=[0,0,0];return Fe(Te,M.toPremultipliedRenderColor(C?null:N.getLut(_.scope)).toArray01Linear().slice(0,3),xe*F),ko([_e[0]>0?_e[0]/(_e[0]+Te[0]):0,_e[1]>0?_e[1]/(_e[1]+Te[1]):0,_e[2]>0?_e[2]/(_e[2]+Te[2]):0])}const Ole=[];function lft(N){return Ole[N]=Ole[N]||new Float64Array(16)}const zle=[],rps=new Float32Array(16);class aps{constructor(p,_){this.aabb=p,this.lastCascade=_}}class ips{add(p,_){const C=this.receivers[p.key];C!==void 0?(C.aabb.min[0]=Math.min(C.aabb.min[0],_.min[0]),C.aabb.min[1]=Math.min(C.aabb.min[1],_.min[1]),C.aabb.min[2]=Math.min(C.aabb.min[2],_.min[2]),C.aabb.max[0]=Math.max(C.aabb.max[0],_.max[0]),C.aabb.max[1]=Math.max(C.aabb.max[1],_.max[1]),C.aabb.max[2]=Math.max(C.aabb.max[2],_.max[2])):this.receivers[p.key]=new aps(_,null)}clear(){this.receivers={}}get(p){return this.receivers[p.key]}computeRequiredCascades(p,_,C){const M=du.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 Y=H.aabb.getCorners();for(let se=0;se1||_e[1]<-1||_e[1]>1){me=!1;break}}if(H.lastCascade=se,F=Math.max(F,se),me)break}}return F+1}}function Ble(N,p,_){const C=Ve([],ft([],_,p),ft([],N,p)),M=ce(C);return M===0?[0,0,1,0]:(Fe(C,C,1/M),[C[0],C[1],C[2],-ze(C,p)])}function ops(N,p,_,C,M,F){const z=N.zoom,H=N.scale,Y=N.worldSize,se=1/Y,me=N.aspect,xe=Math.sqrt(1+me*me)*Math.tan(.5*N.fovX),_e=xe*xe,Te=C-_,De=C+_;let Ue,Ye;_e>Te/De?(Ue=C,Ye=C*xe):(Ue=.5*De*(1+_e),Ye=.5*Math.sqrt(Te*Te+2*(C*C+_*_)*_e+De*De*_e*_e));const nt=N.projection.pixelsPerMeter(N.center.lat,Y),it=[0,0,-Ue*se];Qe(it,it,N._camera.getCameraToWorldMercator());let ut=Ye*se;const ot=function(Xs){return Xs[0]/=H,Xs[1]/=H,Xs[2]=Xd(Xs[2],N._center.lat),Xs},vt=N._edgeInsets;if(!(vt.left===0&&vt.top===0&&vt.right===0&&vt.bottom===0||vt.left===vt.right&&vt.top===vt.bottom)){const Xs=N._camera.getWorldToCamera(N.worldSize,N.projection.zAxisUnit==="meters"?nt:1),rn=N._camera.getCameraToClipPerspective(N._fov,N.width/N.height,_,C);rn[8]=2*-N.centerOffset.x/N.width,rn[9]=2*N.centerOffset.y/N.height;const In=new Float64Array(16);re(In,rn,Xs);const Pn=new Float64Array(16);A(Pn,In);const $n=B3.fromInvProjectionMatrix(Pn,Y,z,!0);for(const Rn of $n.points){const rr=ot(Rn);ut=Math.max(ut,es(be([],it,rr)))}}ut*=M/(M-1);const kt=Math.acos(p[2]),ls=Math.atan2(-p[0],-p[1]),At=new Tle;At.position=it,At.setPitchBearing(kt,ls);const qt=At.getWorldToCamera(Y,nt),ts=ut*Y,ns=Math.min(N._mercatorZfromZoom(17)*Y*-2,-2*ts),Ps=At.getCameraToClipOrthographic(-ts,ts,-ts,ts,ns,(ts+F*nt)/p[2]),Ws=new Float64Array(16);E(Ws,Ps,qt);const mn=.5*M,ln=[0,0,0];Qe(ln,ve(Math.floor(1e6*it[0])/1e6*Y,Math.floor(1e6*it[1])/1e6*Y,0),Ws),Fe(ln,ln,mn);const _n=[Math.floor(ln[0]),Math.floor(ln[1]),Math.floor(ln[2])],Un=[0,0,0];ft(Un,ln,_n),Fe(Un,Un,-1/mn);const Cs=new Float64Array(16);return w(Cs),I(Cs,Cs,Un),E(Ws,Cs,Ws),[Ws,ts]}class W3 extends Xc{constructor(p,_,C,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 Fut((await this.map._requestManager.transformRequest(p,gr.Model,_)).url,_)}async loadModel(p,_,C){try{const M=await this.loadGLTFFromURI(_.uri,C);if(C.aborted)return;const F=this._modelsInfo.get(p);if(!F)return;const z=WOe(M),H=F.modelSpec,Y=new Uut(p,H.uri,H.position,H.orientation,z);W3.applyModelSpecification(Y,H),Y.computeBoundsAndApplyParent(),this.models.push(Y),F.model=Y}catch(M){if(C.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 C in this._options.models){const M=this._options.models[C],F=this._modelsInfo.get(C);if(F&&F.model){F.modelSpec=M;const z=F.model;z.position=M.position!=null?new Il(M.position[0],M.position[1]):new Il(0,0),z.orientation=M.orientation??[0,0,0],W3.applyModelSpecification(z,M),z.computeBoundsAndApplyParent(),this.models.push(z)}else F?F.modelSpec=M:(this._modelsInfo.set(C,{modelSpec:M,model:null}),_.push(this.loadModel(C,M,p)))}_.length!==0?(await Promise.allSettled(_),p.aborted||this.fire(new zl("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new zl("data",{dataType:"source",sourceDataType:"metadata"}))}static arrayFromColorSpecification(p){const _=p;if(_===void 0)return;if(Array.isArray(_))return[_[0],_[1],_[2]];const C=Ci.parse(_);return C?[C.r,C.g,C.b]:void 0}static applyModelSpecification(p,_){if(_.nodeOverrides&&W3.convertNodeOverrides(p,_.nodeOverrides),_.materialOverrides&&W3.convertMaterialOverrides(p,_.materialOverrides),_.nodeOverrideNames&&(p.nodeOverrideNames=[..._.nodeOverrideNames]),_.materialOverrideNames&&(p.materialOverrideNames=[..._.materialOverrideNames]),_.featureProperties&&(p.featureProperties=_.featureProperties),_.lightOverrides){const C=_.lightOverrides,M=W3.arrayFromColorSpecification(C["light-ambient-color"]),F=W3.arrayFromColorSpecification(C["light-directional-color"]);p.lightOverrides={ambientIntensity:C["light-ambient-intensity"],ambientColor:M,directionalIntensity:C["light-directional-intensity"],directionalColor:F}}else p.lightOverrides=void 0}static convertNodeOverrides(p,_){if(Array.isArray(_)&&_.every(C=>typeof C=="string")){p.nodeOverrideNames=[];for(const C of _)p.nodeOverrideNames.push(C)}else Object.entries(_).forEach(([C,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(C,F)})}static convertMaterialOverrides(p,_){if(Array.isArray(_)&&_.every(C=>typeof C=="string")){p.materialOverrideNames=[];for(const C of _)p.materialOverrideNames.push(C)}else Object.entries(_).forEach(([C,M])=>{const F=W3.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 Y=M["model-emissive-strength"];Y!==void 0&&(z.emissionStrength=Y);const se=M["model-opacity"];se!==void 0&&(z.opacity=se),p.materialOverrides.set(C,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=z6(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 C in p){const M=p[C],F=this._modelsInfo.get(C);F&&F.modelSpec.uri===M.uri&&_.set(C,F)}if(this._modelsInfo.size!==_.size){this.cancelModelRequests();for(const[C,M]of _)M.model||_.delete(C)}this._modelsInfo=_,this._options.models=p,this.load()}}function cft(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 Y of M.variants){if(Y==null||typeof Y!="object"||Y.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(Y.capabilities))throw new Error("capabilities must be an array");Y.capabilities.length===1&&(Y.capabilities[0]==="meshopt-v2+lod"?z=Y:Y.capabilities[0]==="meshopt"&&(F=Y))}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 C=mu({...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&&(C.tiles=p.tiles),C.tiles=_.canonicalizeTileset(C,N.url),C}function dft(N,p,_,C,M){const F=function(H,Y){if(H)return M(H);if(Y){N.url&&Y.tiles&&N.tiles&&delete N.tiles;const se=cft(N,Y,p);if(se instanceof Error)return M(se);M(null,se)}},z=function(H,Y,se){if(!H)return null;if(!Y&&!se)return H;se=se||H.worldview_default;const me=Object.values(H.language||{});if(me.length===0)return null;const xe=Object.values(H.worldview||{});if(xe.length===0)return null;const _e=me.every(De=>De===Y),Te=xe.every(De=>De===se);return _e&&Te?H:Y in(H.language_options||{})||se in(H.worldview_options||{})?null:H.language_options&&H.worldview_options?H:null}(N.data,_,C);if(z)return ah.frame(()=>F(null,z));if(N.url){const H=new AbortController;return(async()=>{const Y=await p.transformRequest(p.normalizeSourceURL(N.url,null,_,C),gr.Source,H.signal),{data:se}=await sr(Y,H.signal);F(null,se)})().catch(Y=>{H.signal.aborted||F(Y)}),{cancel:()=>H.abort()}}return ah.frame(()=>{const{data:H,...Y}=N;F(null,Y)})}function uft(N,p){const _=Math.pow(2,p.z),C=Math.floor(Zg(N.getWest())*_),M=Math.floor(rp(N.getNorth())*_),F=Math.ceil(Zg(N.getEast())*_),z=Math.ceil(rp(N.getSouth())*_);return p.x>=C&&p.x=M&&p.ythis.maxzoom||p.z{se&&(se.useNormalOffset=!0,me||(se.enabled=!0))},_e=p.getSource();if(N.renderPass==="light-beam"&&_e.type!=="batched-model")return;if(_e.type==="vector"||_e.type==="geojson")return function(ot,vt,kt,ls,At){const qt=ot.transform,ts=qt.projection.name==="globe",ns=qt.getFreeCameraOptions().position;if(!ot.modelManager)return;const Ps=ot.modelManager;kt.modelManager=Ps;const Ws=ot.shadowRenderer;if(!Object.hasOwn(kt._unevaluatedLayout._values,"model-id"))return;const mn=kt._unevaluatedLayout._values["model-id"],ln={...kt.layout.get("model-id").parameters},_n=ot.style.order.indexOf(kt.fqid),Un=kt.paint.get("model-opacity").constantOr(1);for(const Cs of ls){const Xs=vt.getTile(Cs).getBucket(kt);if(!Xs||Xs.projection.name!==qt.projection.name)continue;const rn=Xs.getModelUris();if(rn&&!Xs.modelsRequested&&(Ps.addModelsFromBucket(rn,At),Xs.modelsRequested=!0),ts)ln.zoom=Cs.overscaledZ;else{const or=Vfs(Cs,qt);ln.zoom=or}const In=mn.possiblyEvaluate(ln);if(qfs(ot,Xs,Cs),KC.shadowUniformsInitialized=!1,KC.useSingleShadowCascade=!!Ws&&Ws.getMaxCascadeForTile(Cs.toUnwrapped())===0,ot.renderPass==="shadow"&&Ws){if(ot.currentShadowCascade===1&&Xs.isInsideFirstShadowMapFrustum)continue;const or=qt.calculatePosMatrix(Cs.toUnwrapped(),qt.worldSize);if(KC.tileMatrix.set(or),KC.shadowTileMatrix.set(Ws.calculateShadowPassMatrixFromMatrix(or)),KC.aabb.min=[0,0,0],KC.aabb.max[0]=KC.aabb.max[1]=Pr,KC.aabb.max[2]=0,Gfs(Xs,KC,ot,kt.scope))continue}const Pn=1<0&&ot.style.isLayerClipped(kt,vt.getSource())&&Xs.updateReplacement(Cs,ot.replacementSource,_n,kt.scope)&&(Xs.uploaded=!1,Xs.upload(ot.context));let Rn=0;const rr=new Array,On=new Array,Ar=new Array;for(let or in Xs.instancesPerModel){const vr=Xs.instancesPerModel[or];vr.features.length>0&&!ts&&(or=In.evaluate(vr.features[0].feature,{}));const Ga=Ps.getModel(or,At);if(Ga||Ps.hasURLBeenRequested(or)||Xs.modelUris.includes(or)||(Xs.modelUris.push(or),Xs.modelsRequested=!1),Ga&&Ga.uploaded)if(ts){const Wa=Fe([],[ns.x,ns.y,ns.z],ot.transform.worldSize);Ce(Wa,Wa);for(let oi=0;oi0&&Fo.elevationUpdate(vr.terrain,Fa,Ni,Wa.source),Fo.needsReEvaluation(vr,Ai,Wa)&&Fo.evaluate(Wa))}})(ot,vt,kt,ls),function(){const vr=new Map;let Ga,Wa,oi;On?(Ga=ls.length-1,Wa=-1,oi=-1):(Ga=0,Wa=ls.length,oi=1);const Fa=te(),Ai=new xs(0,0);for(let Ni=Ga;Ni!==Wa;Ni+=oi){const Fo=ls[Ni],rl=vt.getTile(Fo).getBucket(kt);if(!rl||!rl.uploaded)continue;let Bl=!1;ns&&(Bl=ns.getMaxCascadeForTile(Fo.toUnwrapped())===0);const bc=qt.calculatePosMatrix(Fo.toUnwrapped(),qt.worldSize),qm=!!(4&rl.modelTraits);E(b8e,_n,bc),E(_8e,qt.expandedFarZProjMatrix,bc),A(Ple,b8e),S(Ple,Ple);const W0=!In&&ns&&ns.enabled?ns.computeCascadeTileMatrices(bc):null;!In&&On&&(A(uM,bc),Qe(Fa,Ws,uM),Ai.x=Fa[0],Ai.y=Fa[1]);const Zh=[];rl.setFilter(kt.filter);for(const _l of rl.getNodesInfo()){if(_l.hiddenByReplacement||!_l.node.meshes)continue;const qd=_l.node;let hh=0;ot.terrain&&qd.elevation&&(hh=qd.elevation*ot.terrain.exaggeration());const Vm=()=>{const Yu=_l.aabb,qb=rn.min,Vb=rn.max;return qb[0]=Yu.min[0],qb[1]=Yu.min[1],qb[2]=Yu.min[2]+hh,Vb[0]=Yu.max[0],Vb[1]=Yu.max[1],Vb[2]=Yu.max[2]+hh,Qe(qb,qb,bc),Qe(Vb,Vb,bc),rn},ho=Vm(),mp=_l.evaluatedScale;if(mp[0]<=1&&mp[1]<=1&&mp[2]<=1&&ho.intersects(Rn)===0)continue;if(!In){const Yu=ho.min,qb=ho.max;Lle[0]=.5*(Yu[0]+qb[0]),Lle[1]=.5*(Yu[1]+qb[1]),Lle[2]=.5*(Yu[2]+qb[2]);const Vb=Be(Ws,Lle)*ln,hg=ot._debugParams.lodSwitchDistance,Yk=hg>=0;if(Yk&&hg>=9999)_l.targetLod=0;else{let W_;if(Yk)W_=hg;else{const K0=(qb[2]-Yu[2])*ln*mp[2],K3=Math.max(qb[0]-Yu[0],qb[1]-Yu[1])*ln*Math.max(mp[0],mp[1]);let YC;YC=K0>=30?1:K3>=80?.5:Math.max(K0,K3)>=20?.25:0,W_=2e3+3e3*YC}Hfs(_l,Vb,Math.min(ot.frameTimeDelta,1e3/30),W_,ot._debugParams.lodSwitchFadeDuration)}}if(!In&&On){const Yu=.16666666666666666;_l.cameraCollisionOpacity=Ws[0]>ho.min[0]&&Ws[0]ho.min[1]&&Ws[1]!On||_l.opacity===1&&qd.opacity===1?_l.depthqd.depth?-1:1);for(const _l of Zh){const qd=_l.nodeInfo,hh=qd.node;let Vm=null;if(ot._debugParams.show3DModelFootprints&&hh.footprint){const wy=hh.id||hh.name||"footprint";if(!vr.has(wy)){const Gv=JY(new Float64Array(16),_8e,_l.tileTranslation,_l.nodeInfo.evaluatedScale);vr.set(wy,{node:hh,mvp:Gv})}}const ho=_l.nodeInfo.evaluatedScale;JY(WC,b8e,_l.tileTranslation,ho),Ile[0]=1/ho[0],Ile[1]=-1/ho[1],Ile[2]=1/ho[2],P(uM,Ple,Ile),E(WC,WC,hh.globalMatrix);const mp=qm?0:qd.evaluatedRMEA[0][2],Ip=qd.targetLod,gf=hh.lodMeshes&&hh.lodMeshes.length>0,$x=gf&&Ip>0&&Ip<1;if(In&&gf&&Math.round(Ip)===1)continue;const Ux=!In&&ts?Imt(Pmt,_l.nodeModelMatrix,ot.transform):null,Ub=In&&ns?ns.calculateShadowPassMatrixFromMatrix(_l.nodeModelMatrix):null,_y=$x?2:1,qx=gf&&Math.round(Ip)===1;for(let wy=0;wy<_y;++wy){const Gv=$x?wy===1:qx,Yu=Gv?hh.lodMeshes:hh.meshes,qb=$x?Gv?-Ip:1-Ip:1;for(let Vb=0;Vb=PY||D8e>=PY}const wo=hg.material;let mg;wo.occlusionTexture&&wo.occlusionTexture.offsetScale&&(mg=wo.occlusionTexture.offsetScale,K0.defines.push("OCCLUSION_TEXTURE_TRANSFORM")),$x&&K0.defines.push("DITHERED_DISCARD");const Tu=ot.getOrCreateProgram("model",K0);if(!In&&ns&&ns.enabled)if(Vm!==YC){for(let Vx=0;Vx0){const Ni=Array.from(vr.keys()).sort();for(const Fo of Ni){const{node:rl,mvp:Bl}=vr.get(Fo);Rmt(ot,0,rl,Bl)}}}()}(N,p,_,C),void xe();if(_e.type!=="model")return;const Te=_e.getModels(),De=[],Ue=N.transform.getFreeCameraOptions().position,Ye=Fe([],[Ue.x,Ue.y,Ue.z],N.transform.worldSize);Ce(Ye,Ye);const nt=[],it=[];let ut=0;for(const ot of Te){const vt=p.getFeatureState("",ot.id),kt={type:"Unknown",id:ot.id,properties:ot.featureProperties},ls=_.paint.get("model-rotation").evaluate(kt,vt),At=_.paint.get("model-scale").evaluate(kt,vt),qt=_.paint.get("model-translation").evaluate(kt,vt),ts=_.paint.get("model-opacity").evaluate(kt,vt);$fs(_,ot.id,vt,ot.featureProperties,ot.nodeOverrideNames,ot.nodeOverrides),Ufs(_,ot.id,vt,ot.featureProperties,ot.materialOverrideNames,ot.materialOverrides),ot.nodeOverrides.size>0&&ot.computeBoundsAndApplyParent(),ot.computeModelMatrix(N,ls,At,qt,H,z,!1);const ns=U([],Ye),Ps=W([],[1,1,1/T(ot.position.lat,N.transform.zoom)]);De.push({zScaleMatrix:Ps,negCameraPosMatrix:ns});for(const Ws of ot.nodes)k8e(N,Ws,ot.matrix,N.transform.expandedFarZProjMatrix,ut,nt,it,ot.materialOverrides,ts,void 0,ot.lightOverrides);ut++}if(nt.sort((ot,vt)=>vt.depth-ot.depth),N.renderPass!=="shadow"){if(N._debugParams.show3DModelFootprints){const ot=N.transform.projMatrix,vt=new Map,kt=(At,qt)=>{if(At.footprint){const ts=At.id||At.name||"footprint";if(!vt.has(ts)){const ns=E([],ot,qt);vt.set(ts,{node:At,mvp:ns})}}};for(const At of it)kt(At.node,At.modelMatrix);for(const At of nt)kt(At.node,At.modelMatrix);const ls=Array.from(vt.keys()).sort();for(const At of ls){const{node:qt,mvp:ts}=vt.get(At);Rmt(N,0,qt,ts)}}Dmt(N,_,nt,it,De),xe()}else{for(const ot of it)eZ(ot.mesh,ot.nodeModelMatrix,N,_);for(const ot of nt)eZ(ot.mesh,ot.nodeModelMatrix,N,_);xe()}},prepare:function(N,p,_){const C=p.getSource();if(!C.loaded())return;if(C.type==="vector"||C.type==="geojson")return void(_.modelManager&&_.modelManager.upload(_,Lmt(_,N)));if(C.type==="batched-model"||C.type!=="model")return;const M=C.getModels();for(const F of M)F.upload(_.context)},shaders:eps,programUniforms:nps,ShadowRenderer:class{constructor(N){this.painter=N,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new ips,this._depthMode=new vy(N.context.gl.LEQUAL,vy.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 C=_.getSource();if(C.type==="model")return C.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 C=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 nt of C.style.order){const it=C.style._mergedLayers[nt];it.hasShadowPass()&&!it.isHidden(N.zoom)&&this._hasCasterGeometry(it,_)&&(z=H),!F||F!==nt&&F!==it.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 Y=C.context,se=this._shadowParameters.shadowMapResolution,me=this._shadowParameters.shadowMapResolution;if(this._cascades.length===0||this._shadowParameters.shadowMapResolution!==this._cascades[0].texture.size[0]){this._cascades=[];for(let nt=0;ntut.dem).forEach(ut=>{const ot=ut.dem.tree;it[0]=Math.min(it[0],ot.minimums[0]),it[1]=Math.max(it[1],ot.maximums[0])}),it[0]!==1e4&&(xe=(it[1]-it[0])*nt.exaggeration())}const _e=1.5*N.cameraToCenterDistance,Te=3*_e,De=new Float64Array(16);for(let nt=0;nt=0)return{};const M=function(H,Y,se){const me=se/(1<0&&(ue(M[1],M[1],[C[0]*F,0,0]),ue(M[2],M[2],[C[0]*F,0,0])),C[1]<0?(ue(M[0],M[0],[0,C[1]*F,0]),ue(M[1],M[1],[0,C[1]*F,0])):C[1]>0&&(ue(M[2],M[2],[0,C[1]*F,0]),ue(M[3],M[3],[0,C[1]*F,0]));const z={};return z.vertices=M,z.planes=[Ble(M[1],M[0],M[4]),Ble(M[2],M[1],M[5]),Ble(M[3],M[2],M[6]),Ble(M[0],M[3],M[7])],z}addShadowReceiver(N,p,_){this._receivers.add(N,du.fromTileIdAndHeight(N,p,_))}getMaxCascadeForTile(N){const p=this._receivers.get(N);return p&&p.lastCascade?p.lastCascade:0}},drawGroundEffect:aft,queryModelLayerRendered:function(N,p,_,C){const M=_.getSource();if(!M||M.type!=="model")return{};const F=M,z={};z[N.id]=[];const H=z[N.id];let Y=0;for(const se of F.models){const me=_.getFeatureState(N.sourceLayer,se.id),xe={type:"Unknown",id:se.id,properties:se.featureProperties},_e=N.paint.get("model-rotation").evaluate(xe,me),Te=N.paint.get("model-scale").evaluate(xe,me),De=N.paint.get("model-translation").evaluate(xe,me),Ue=N.paint.get("model-elevation-reference");let Ye=[];hle(Ye,se,C,se.position,_e,Te,De,Ue==="ground",Ue==="ground",!1),C.projection.name==="globe"&&(Ye=ule(Ye,C));const nt=E([],C.projMatrix,Ye),it=BOe(p.isPointQuery()?p.screenBounds:p.screenGeometry,C,nt,se.aabb);if(it!=null){const ut=new sR(void 0,0,0,0,se.id);ut.layer=N.layer,ut.properties=structuredClone(se.featureProperties),ut.properties.layer=N.id,ut.properties.uri=se.uri,ut.properties.orientation=se.orientation,ut.sourceLayer=N.sourceLayer,ut.geometry={type:"Point",coordinates:[se.position.lng,se.position.lat]},ut.state=me,ut.source=N.source,H.push({featureIndex:Y,feature:ut,intersectionZ:it})}++Y}return z},queryModelLayerIntersectsFeature:function(N,p,_,C,M,F){if(!N.modelManager)return!1;const z=N.modelManager,H=p.tile.getBucket(N);if(!(H&&H instanceof l8e))return!1;for(const Y in H.instancesPerModel){const se=H.instancesPerModel[Y],me=_.id!==void 0?_.id:_.properties&&Object.hasOwn(_.properties,"id")?_.properties.id:void 0;if(Object.hasOwn(se.idToFeaturesIndex,me)){const xe=se.features[se.idToFeaturesIndex[me]],_e=z.getModel(Y,F||N.scope);if(!_e)return!1;let Te=[];const De=new Il(0,0),Ue=H.canonical;let Ye=Number.MAX_VALUE;for(let nt=0;ntthis.map.style.clearSource(N))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(N){this._loaded=!1,this.fire(new zl("dataloading",{dataType:"source"}));const p=Array.isArray(this.map._language)?this.map._language.join():this.map._language,_=this.map.getWorldview();this._tileJSONRequest=dft(this._options,this.map._requestManager,p,_,(C,M)=>{this._tileJSONRequest=null,this._loaded=!0,C?(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(C))):M&&(Object.assign(this,M),M.bounds&&(this.tileBounds=new $le(M.bounds,this.minzoom,this.maxzoom)),Eu(M.tiles,this.map._requestManager._customAccessToken),this.fire(new zl("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new zl("data",{dataType:"source",sourceDataType:"content"}))),N&&N(C)})}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)),C=!N.actor||N.state==="expired";if(C)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 Y of H)Y.dirty=!0;return void(N.state="loaded")}}const M=C?"loadTile":"reloadTile",F=new AbortController;N.request=F;const z=(H,Y)=>(delete N.request,N.aborted?p(null):H&&!et(H)?p(H):(this.map._refreshExpiredTiles&&Y&&N.setExpiryData(Xa(Y.headers)),N.loadModelData(Y,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(_,gr.Tile,F.signal);if(F.signal.aborted)return p(null);const Y={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:ah.devicePixelRatio,promoteId:this.promoteId};N.request=N.actor.sendCancelable(M,Y,{},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 C=await Fut(N),M=new Uut(p,_,void 0,void 0,WOe(C));return M.computeBoundsAndApplyParent(),M}};class hft{constructor(p,_){this.tileID=p,this.x=p.canonical.x,this.y=p.canonical.y,this.z=p.canonical.z,this.grid=new Uv(Pr,Pr,512),this.featureIndexArray=new Jy,this.promoteId=_,this.is3DTile=!1,this.serializedLayersCache=new Map}insert(p,_,C,M,F,z=0,H=0){const Y=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(C,M,F,z);const se=this.grid;for(let me=0;me<_.length;me++){const xe=_[me],_e=[1/0,1/0,-1/0,-1/0];for(let Te=0;Te=0&&_e[3]>=0&&se.insert(Y,_e[0],_e[1],_e[2],_e[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new BFe(new qoe(this.rawTileData)).layers,this.sourceLayerCoder=new ymt(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:C,transform:M,tileTransform:F,pixelPosMatrix:z,availableImages:H,worldview:Y}=_;this.loadVTLayers(),this.serializedLayersCache.clear();const se=_.queryRadius?_.queryRadius:0,me=C.bufferedTilespaceBounds,xe=this.grid.queryKeys(me.min.x,me.min.y,me.max.x,me.max.y,(Ue,Ye,nt,it)=>GFe(C.bufferedTilespaceGeometry,Ue-se,Ye-se,nt+se,it+se));xe.sort(lps);let _e=null;M.elevation&&xe.length>0&&(_e=U9.create(M.elevation,this.tileID));const Te={};let De;for(let Ue=0;Ue(it||(it=dt(ut,this.tileID.canonical,F)),ot.queryIntersectsFeature(C,ut,vt,it,this.z,M,z,_e,kt,_.scope)))}return Te}loadMatchingFeature(p,_,C,M,F,z){const{featureIndex:H,bucketIndex:Y,sourceLayerIndex:se,layoutVertexArrayOffset:me}=_,xe=this.bucketLayerIDs[Y],_e=C.layers,Te=Object.keys(_e);if(Te.length&&!sg(Te,xe))return;const De=C.sourceCache,Ue=this.sourceLayerCoder.decode(se),Ye=this.vtLayers[Ue].feature(H),nt=this.getId(Ye,Ue);for(let it=0;it`${H.key}: ${H.message}`).join(", ");return void Yo(`Failed to create expression for promoteId: ${z}`)}this.promoteIdExpression=F.value}C=this.promoteIdExpression.evaluate({zoom:0},p)}else C=p.properties[M];typeof C=="boolean"&&(C=Number(C))}return C}}function mft(N,p,_,C,M){return Bc(N,(F,z)=>{const H=p instanceof Sl?p.get(z):null;return H&&H.evaluate?H.evaluate(_,C,void 0,M):H})}function lps(N,p){return p-N}async function fft(){return Promise.resolve()}oa(hft,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const cps={circle:class extends Qy{constructor(N,p,_,C){super(N,{layout:dht||(dht=new Wu({"circle-sort-key":new kr(Zs.layout_circle["circle-sort-key"]),"circle-elevation-reference":new fr(Zs.layout_circle["circle-elevation-reference"]),visibility:new fr(Zs.layout_circle.visibility)})),paint:uht||(uht=new Wu({"circle-radius":new kr(Zs.paint_circle["circle-radius"]),"circle-color":new kr(Zs.paint_circle["circle-color"]),"circle-blur":new kr(Zs.paint_circle["circle-blur"]),"circle-opacity":new kr(Zs.paint_circle["circle-opacity"]),"circle-translate":new fr(Zs.paint_circle["circle-translate"]),"circle-translate-anchor":new fr(Zs.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new fr(Zs.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new fr(Zs.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new kr(Zs.paint_circle["circle-stroke-width"]),"circle-stroke-color":new kr(Zs.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new kr(Zs.paint_circle["circle-stroke-opacity"]),"circle-emissive-strength":new fr(Zs.paint_circle["circle-emissive-strength"]),"circle-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"circle-stroke-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C)}createBucket(N){return new koe(N)}queryRadius(N){const p=N;return Q9("circle-radius",this,p)+Q9("circle-stroke-width",this,p)+kle(this.paint.get("circle-translate"))}queryIntersectsFeature(N,p,_,C,M,F,z,H){const Y=ght(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 yht(N,C,F,z,H,this.paint.get("circle-pitch-alignment")==="map",this.paint.get("circle-pitch-scale")==="map",Y,se)}getProgramIds(){return["circle"]}getDefaultProgramParams(N,p,_){const C=xht(this);return{config:new K6(this,{zoom:p,lut:_}),defines:C,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"&&A9(this,"circle-elevation-reference",p=>p==="hd-road-markup")}prepare(){return this.mayUse("HD")?Nle():Promise.resolve()}},heatmap:class extends Qy{createBucket(N){return new bht(N)}constructor(N,p,_,C){super(N,{layout:_ht||(_ht=new Wu({visibility:new fr(Zs.layout_heatmap.visibility)})),paint:wht||(wht=new Wu({"heatmap-radius":new kr(Zs.paint_heatmap["heatmap-radius"]),"heatmap-weight":new kr(Zs.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new fr(Zs.paint_heatmap["heatmap-intensity"]),"heatmap-color":new P3(Zs.paint_heatmap["heatmap-color"]),"heatmap-opacity":new fr(Zs.paint_heatmap["heatmap-opacity"]),"heatmap-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C),this._updateColorRamp()}_handleSpecialPaintPropertyUpdate(N){N==="heatmap-color"&&this._updateColorRamp()}_updateColorRamp(){this.colorRamp=WY({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 Q9("heatmap-radius",this,N)}queryIntersectsFeature(N,p,_,C,M,F,z,H){const Y=this.paint.get("heatmap-radius").evaluate(p,_);return yht(N,C,F,z,H,!0,!0,new xs(0,0),Y)}hasOffscreenPass(){return this.paint.get("heatmap-opacity")!==0&&this.visibility!=="none"}getProgramIds(){return["heatmap","heatmapTexture"]}getDefaultProgramParams(N,p,_){return N==="heatmap"?{config:new K6(this,{zoom:p,lut:_}),overrideFog:!1}:{}}},hillshade:class extends Qy{constructor(N,p,_,C){super(N,{layout:jht||(jht=new Wu({visibility:new fr(Zs.layout_hillshade.visibility)})),paint:Nht||(Nht=new Wu({"hillshade-illumination-direction":new fr(Zs.paint_hillshade["hillshade-illumination-direction"]),"hillshade-illumination-anchor":new fr(Zs.paint_hillshade["hillshade-illumination-anchor"]),"hillshade-exaggeration":new fr(Zs.paint_hillshade["hillshade-exaggeration"]),"hillshade-shadow-color":new fr(Zs.paint_hillshade["hillshade-shadow-color"]),"hillshade-highlight-color":new fr(Zs.paint_hillshade["hillshade-highlight-color"]),"hillshade-accent-color":new fr(Zs.paint_hillshade["hillshade-accent-color"]),"hillshade-emissive-strength":new fr(Zs.paint_hillshade["hillshade-emissive-strength"]),"hillshade-shadow-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"hillshade-highlight-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"hillshade-accent-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C)}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 Qy{constructor(N,p,_,C){super(N,{layout:kht||(kht=new Wu({"fill-sort-key":new kr(Zs.layout_fill["fill-sort-key"]),visibility:new fr(Zs.layout_fill.visibility),"fill-elevation-reference":new fr(Zs.layout_fill["fill-elevation-reference"]),"fill-construct-bridge-guard-rail":new kr(Zs.layout_fill["fill-construct-bridge-guard-rail"])})),paint:Sht||(Sht=new Wu({"fill-antialias":new fr(Zs.paint_fill["fill-antialias"]),"fill-opacity":new kr(Zs.paint_fill["fill-opacity"]),"fill-color":new kr(Zs.paint_fill["fill-color"]),"fill-outline-color":new kr(Zs.paint_fill["fill-outline-color"]),"fill-translate":new fr(Zs.paint_fill["fill-translate"]),"fill-translate-anchor":new fr(Zs.paint_fill["fill-translate-anchor"]),"fill-pattern":new kr(Zs.paint_fill["fill-pattern"]),"fill-pattern-cross-fade":new fr(Zs.paint_fill["fill-pattern-cross-fade"]),"fill-emissive-strength":new fr(Zs.paint_fill["fill-emissive-strength"]),"fill-z-offset":new kr(Zs.paint_fill["fill-z-offset"]),"fill-bridge-guard-rail-color":new kr(Zs.paint_fill["fill-bridge-guard-rail-color"]),"fill-tunnel-structure-color":new kr(Zs.paint_fill["fill-tunnel-structure-color"]),"fill-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"fill-outline-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"fill-bridge-guard-rail-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"fill-tunnel-structure-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C)}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 K6(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 zFe(N)}queryRadius(){return kle(this.paint.get("fill-translate"))}queryIntersectsFeature(N,p,_,C,M,F){return!N.queryGeometry.isAboveHorizon&&UFe(pht(N.tilespaceGeometry,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),F.angle,N.pixelToTileUnitsFactor),C)}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"&&A9(this,"fill-elevation-reference",p=>p!=="none")}prepare(){return this.mayUse("HD")?Nle():Promise.resolve()}hasShadowPass(){return this.layout&&this.layout.get("fill-elevation-reference")!=="none"}},"fill-extrusion":class extends Qy{constructor(N,p,_,C){super(N,{layout:Eht||(Eht=new Wu({visibility:new fr(Zs["layout_fill-extrusion"].visibility),"fill-extrusion-edge-radius":new fr(Zs["layout_fill-extrusion"]["fill-extrusion-edge-radius"]),"source-max-zoom":new fr(Zs["layout_fill-extrusion"]["source-max-zoom"])})),paint:Tht||(Tht=new Wu({"fill-extrusion-opacity":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new kr(Zs["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new kr(Zs["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-pattern-cross-fade":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-pattern-cross-fade"]),"fill-extrusion-height":new kr(Zs["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new kr(Zs["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-height-alignment":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-height-alignment"]),"fill-extrusion-base-alignment":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-base-alignment"]),"fill-extrusion-vertical-gradient":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"]),"fill-extrusion-ambient-occlusion-intensity":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-intensity"]),"fill-extrusion-ambient-occlusion-radius":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-radius"]),"fill-extrusion-ambient-occlusion-wall-radius":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-wall-radius"]),"fill-extrusion-ambient-occlusion-ground-radius":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-ground-radius"]),"fill-extrusion-ambient-occlusion-ground-attenuation":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-ground-attenuation"]),"fill-extrusion-flood-light-color":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-flood-light-color"]),"fill-extrusion-flood-light-intensity":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-flood-light-intensity"]),"fill-extrusion-flood-light-wall-radius":new kr(Zs["paint_fill-extrusion"]["fill-extrusion-flood-light-wall-radius"]),"fill-extrusion-flood-light-ground-radius":new kr(Zs["paint_fill-extrusion"]["fill-extrusion-flood-light-ground-radius"]),"fill-extrusion-flood-light-ground-attenuation":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-flood-light-ground-attenuation"]),"fill-extrusion-vertical-scale":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-vertical-scale"]),"fill-extrusion-rounded-roof":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-rounded-roof"]),"fill-extrusion-cutoff-fade-range":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-cutoff-fade-range"]),"fill-extrusion-front-cutoff":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-front-cutoff"]),"fill-extrusion-emissive-strength":new kr(Zs["paint_fill-extrusion"]["fill-extrusion-emissive-strength"]),"fill-extrusion-line-width":new kr(Zs["paint_fill-extrusion"]["fill-extrusion-line-width"]),"fill-extrusion-cast-shadows":new fr(Zs["paint_fill-extrusion"]["fill-extrusion-cast-shadows"]),"fill-extrusion-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"fill-extrusion-flood-light-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(N){return new _le(N)}queryRadius(){return kle(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,_,C,M,F,z,H,Y){const se=ght(this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),F.angle,N.pixelToTileUnitsFactor),me=this.paint.get("fill-extrusion-height").evaluate(p,_),xe=this.paint.get("fill-extrusion-base").evaluate(p,_),_e=[0,0],Te=H&&F.elevation,De=F.elevation?F.elevation.exaggeration():1,Ue=N.tile.getBucket(this);if(Ue instanceof _le){const ot=Ue.centroidData.find(vt=>Y>=vt.vertexArrayOffset&&Yot.polygon).flat());const Ye=Te?H:null,[nt,it]=Oht(F,C,xe,me,se,z,Ye,_e,De,F.center.lat,N.tileID.canonical),ut=N.queryGeometry;return Fht(nt,it,ut.isPointQuery()?ut.screenBounds:ut.screenGeometry)}},building:class extends Qy{constructor(N,p,_,C){super(N,{layout:Mht||(Mht=new Wu({visibility:new fr(Zs.layout_building.visibility),"building-facade":new kr(Zs.layout_building["building-facade"]),"building-facade-floors":new kr(Zs.layout_building["building-facade-floors"]),"building-facade-unit-width":new kr(Zs.layout_building["building-facade-unit-width"]),"building-facade-window":new kr(Zs.layout_building["building-facade-window"]),"building-roof-shape":new kr(Zs.layout_building["building-roof-shape"]),"building-height":new kr(Zs.layout_building["building-height"]),"building-base":new kr(Zs.layout_building["building-base"]),"building-flood-light-wall-radius":new kr(Zs.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new kr(Zs.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new kr(Zs.layout_building["building-flip-roof-orientation"])})),paint:Pht||(Pht=new Wu({"building-opacity":new fr(Zs.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new fr(Zs.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new fr(Zs.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new fr(Zs.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new fr(Zs.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new fr(Zs.paint_building["building-vertical-scale"]),"building-cast-shadows":new fr(Zs.paint_building["building-cast-shadows"]),"building-color":new kr(Zs.paint_building["building-color"]),"building-emissive-strength":new kr(Zs.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new fr(Zs.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new fr(Zs.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new fr(Zs.paint_building["building-front-cutoff"]),"building-flood-light-color":new fr(Zs.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new fr(Zs.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new fr(Zs.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}mayUse(N){return N==="HD"}prepare(){return async function(){return function(){if(!Yc(self)||oj!=null||hht!=null)return null;if(X9!=null)return X9;const N=fetch(Nt());return X9=function(p){let _,C,M,F,z;function H(){_=new Uint8Array(z.buffer),C=new Int16Array(z.buffer),M=new Int32Array(z.buffer),F=new Float32Array(z.buffer)}function Y(){throw new Error("Unexpected BuildingGen error.")}const se=()=>{},me={a:{a:Y,f:function(xe){const _e=_.length,Te=Math.max(xe>>>0,Math.ceil(1.2*_e)),De=Math.ceil((Te-_e)/65536);try{return z.grow(De),H(),!0}catch{return!1}},g:Y,b:se,c:se,d:se,e:se}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(p,me):p.then(xe=>xe.arrayBuffer()).then(xe=>WebAssembly.instantiate(xe,me))).then(xe=>{const _e=xe.instance.exports;return(0,_e.g)(),z=_e.f,H(),new gfs({setStyle:_e.h,setAOOptions:_e.i,setMetricOptions:_e.j,setStructuralOptions:_e.k,setFacadeOptions:_e.l,setFauxFacadeOptions:_e.m,setFacadeClassifierOptions:_e.n,addFeature:_e.o,addFacade:_e.p,generateMesh:_e.q,getLastError:_e.r,getOuterRingLength:_e.s,getMeshCount:_e.t,getPositionsPtr:_e.u,getPositionsLength:_e.v,getNormalsPtr:_e.w,getNormalsLength:_e.x,getAOPtr:_e.y,getAOLength:_e.z,getUVPtr:_e.A,getUVLength:_e.B,getFauxFacadePtr:_e.C,getFauxFacadeLength:_e.D,getIndicesPtr:_e.E,getIndicesLength:_e.F,getBuildingPart:_e.G,getRingCount:_e.H,getRingPtr:_e.I,getRingLength:_e.J,malloc:_e.K,free:_e.L,heapU8:_,heap16:C,heap32:M,heapF32:F})})}(N).then(p=>{X9=null,oj=p}).catch(p=>{Yo("Could not load building-gen"),X9=null,hht=p}),X9}()}()}createBucket(N){return new mht(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,_,C,M,F,z,H,Y,se){let me=this.layout.get("building-height").evaluate(p,_);const xe=this.layout.get("building-base").evaluate(p,_),_e=N.tile.getBucket(this).getFootprint(p);if(_e){if(_e.hiddenFlags!==0)return!1;me=_e.height}const[Te,De]=Oht(F,C,xe,me,new xs(0,0),z,null,[0,0],1,F.center.lat,N.tileID.canonical),Ue=N.queryGeometry;return Fht(Te,De,Ue.isPointQuery()?Ue.screenBounds:Ue.screenGeometry)}},line:class extends Qy{constructor(N,p,_,C){const M=Vht();super(N,M,p,_,C),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 vi,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 vi,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(ZY)return ZY;const _=Vht();return ZY=new Sfs(_.paint.properties["line-width"].specification),ZY.useIntegerZoom=!0,ZY})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,N)}createBucket(N){return new ZFe(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 C=Uht(this);return{config:new K6(this,{zoom:p,lut:_}),defines:C,overrideFog:!1}}queryRadius(N){const p=N,_=Wht(Q9("line-width",this,p),Q9("line-gap-width",this,p)),C=Q9("line-offset",this,p);return _/2+Math.abs(C)+kle(this.paint.get("line-translate"))}queryIntersectsFeature(N,p,_,C,M,F){if(N.queryGeometry.isAboveHorizon)return!1;const z=pht(N.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),F.angle,N.pixelToTileUnitsFactor),H=N.pixelToTileUnitsFactor/2*Wht(this.paint.get("line-width").evaluate(p,_),this.paint.get("line-gap-width").evaluate(p,_)),Y=this.paint.get("line-offset").evaluate(p,_);return Y&&(C=function(se,me){const xe=[],_e=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 C=p._unevaluatedLayout.getValue("line-z-offset");return C!==void 0&&(typeof C!="number"||C!==0)}(this)}prepare(){return this.mayUse("HD")?Nle():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:Sle,background:class extends Qy{constructor(N,p,_,C){super(N,{layout:Xht||(Xht=new Wu({visibility:new fr(Zs.layout_background.visibility)})),paint:Qht||(Qht=new Wu({"background-pitch-alignment":new fr(Zs.paint_background["background-pitch-alignment"]),"background-color":new fr(Zs.paint_background["background-color"]),"background-pattern":new fr(Zs.paint_background["background-pattern"]),"background-opacity":new fr(Zs.paint_background["background-opacity"]),"background-emissive-strength":new fr(Zs.paint_background["background-emissive-strength"]),"background-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C)}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:tmt,"raster-particle":dmt,sky:class extends Qy{constructor(N,p,_,C){super(N,{layout:rmt||(rmt=new Wu({visibility:new fr(Zs.layout_sky.visibility)})),paint:amt||(amt=new Wu({"sky-type":new fr(Zs.paint_sky["sky-type"]),"sky-atmosphere-sun":new fr(Zs.paint_sky["sky-atmosphere-sun"]),"sky-atmosphere-sun-intensity":new fr(Zs.paint_sky["sky-atmosphere-sun-intensity"]),"sky-gradient-center":new fr(Zs.paint_sky["sky-gradient-center"]),"sky-gradient-radius":new fr(Zs.paint_sky["sky-gradient-radius"]),"sky-gradient":new P3(Zs.paint_sky["sky-gradient"]),"sky-atmosphere-halo-color":new fr(Zs.paint_sky["sky-atmosphere-halo-color"]),"sky-atmosphere-color":new fr(Zs.paint_sky["sky-atmosphere-color"]),"sky-opacity":new fr(Zs.paint_sky["sky-opacity"]),"sky-gradient-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"sky-atmosphere-halo-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"}),"sky-atmosphere-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C),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=WY({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 C=this.paint.get("sky-atmosphere-sun"),M=!C,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?o8e(z.azimuthal,90-z.polar,p):o8e(C[0],90-C[1],p)}const _=this.paint.get("sky-gradient-center");return o8e(_[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 Qy{constructor(N,p,_,C){super(N,{paint:imt||(imt=new Wu({}))},p,null)}},"placement-group":class extends Qy{constructor(N,p,_,C){super(N,{paint:omt||(omt=new Wu({}))},p,_,C)}},model:class extends Qy{constructor(N,p,_,C){super(N,{layout:lmt||(lmt=new Wu({visibility:new fr(Zs.layout_model.visibility),"model-id":new kr(Zs.layout_model["model-id"]),"model-allow-density-reduction":new fr(Zs.layout_model["model-allow-density-reduction"])})),paint:cmt||(cmt=new Wu({"model-opacity":new kr(Zs.paint_model["model-opacity"]),"model-rotation":new kr(Zs.paint_model["model-rotation"]),"model-scale":new kr(Zs.paint_model["model-scale"]),"model-translation":new kr(Zs.paint_model["model-translation"]),"model-color":new kr(Zs.paint_model["model-color"]),"model-color-mix-intensity":new kr(Zs.paint_model["model-color-mix-intensity"]),"model-type":new fr(Zs.paint_model["model-type"]),"model-cast-shadows":new fr(Zs.paint_model["model-cast-shadows"]),"model-receive-shadows":new fr(Zs.paint_model["model-receive-shadows"]),"model-ambient-occlusion-intensity":new fr(Zs.paint_model["model-ambient-occlusion-intensity"]),"model-emissive-strength":new kr(Zs.paint_model["model-emissive-strength"]),"model-roughness":new kr(Zs.paint_model["model-roughness"]),"model-height-based-emissive-strength-multiplier":new kr(Zs.paint_model["model-height-based-emissive-strength-multiplier"]),"model-cutoff-fade-range":new fr(Zs.paint_model["model-cutoff-fade-range"]),"model-front-cutoff":new fr(Zs.paint_model["model-front-cutoff"]),"model-elevation-reference":new fr(Zs.paint_model["model-elevation-reference"]),"model-line-cutout-mode":new fr(Zs.paint_model["model-line-cutout-mode"]),"model-color-use-theme":new kr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C),this.layer=N,this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}mayUse(N){return N==="Standard"}prepare(){return fft()}createBucket(N){return new l8e(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 nR.queryModelLayerRendered?nR.queryModelLayerRendered(this,N,p,_):{}}queryIntersectsFeature(N,p,_,C,M,F,z,H,Y,se){return!!nR.queryModelLayerIntersectsFeature&&nR.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 og}isZoomDependent(){return this._isPropertyZoomDependent("model-scale")||this._isPropertyZoomDependent("model-rotation")||this._isPropertyZoomDependent("model-translation")}},clip:class extends Qy{constructor(N,p,_,C){super(N,{layout:Cht||(Cht=new Wu({"clip-layer-types":new fr(Zs.layout_clip["clip-layer-types"]),"clip-layer-scope":new fr(Zs.layout_clip["clip-layer-scope"]),visibility:new fr(Zs.layout_clip.visibility)})),paint:Aht||(Aht=new Wu({}))},p,_,C)}recalculate(N,p){super.recalculate(N,p)}createBucket(N){return new Rht(N)}is3D(N){return!0}}};class A8e{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(A8e,"LRUCache");class dps{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 pft={Other:0,Symbol:1,FillExtrusion:2,HdRoadCoverage:3};class ups{constructor(){this.tasks=new Map,zc(["process"],this),this.invoker=new dps(this.process),this.nextId=0}add(p,_){const C=this.nextId++,M=function({type:F,renderSourceType:z,zoom:H}){H=H||0;const Y=z===pft.Symbol;return F==="message"?0:F!=="maybePrepare"||Y?F!=="parseTile"||Y?F==="parseTile"&&Y?300-H:F==="maybePrepare"&&Y?400-H:500:200-H:100-H}(_);if(M===0){try{p()}finally{}return null}return this.tasks.set(C,{fn:p,metadata:_,priority:M,id:C}),this.invoker.trigger(),{cancel:()=>{this.tasks.delete(C)}}}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 C of this.tasks.values())C.priority<_&&(_=C.priority,p=C);return p}remove(){this.tasks.clear(),this.invoker.remove()}}const gft={type:"message"},E8e=new Map,xft=new Map;class yft{constructor(p){this.size=p,this.minimums=[],this.maximums=[],this.leaves=[]}getElevation(p,_){const C=this.toIdx(p,_);return{min:this.minimums[C],max:this.maximums[C]}}isLeaf(p,_){return this.leaves[this.toIdx(p,_)]}toIdx(p,_){return _*this.size+p}}function vft(N,p,_,C){let M=0,F=Number.MAX_VALUE;for(let z=0;z<3;z++)if(Math.abs(C[z])<1e-15){if(_[z]p[z])return null}else{const H=1/C[z];let Y=(N[z]-_[z])*H,se=(p[z]-_[z])*H;if(Y>se){const me=Y;Y=se,se=me}if(Y>M&&(M=Y),seF)return null}return M}function bft(N,p,_,C,M,F,z,H,Y,se,me){const xe=C-N,_e=M-p,Te=F-_,De=z-N,Ue=H-p,Ye=Y-_,nt=me[1]*Ye-me[2]*Ue,it=me[2]*De-me[0]*Ye,ut=me[0]*Ue-me[1]*De,ot=xe*nt+_e*it+Te*ut;if(Math.abs(ot)<1e-15)return null;const vt=1/ot,kt=se[0]-N,ls=se[1]-p,At=se[2]-_,qt=(kt*nt+ls*it+At*ut)*vt;if(qt<0||qt>1)return null;const ts=ls*Te-At*_e,ns=At*xe-kt*Te,Ps=kt*_e-ls*xe,Ws=(me[0]*ts+me[1]*ns+me[2]*Ps)*vt;return Ws<0||qt+Ws>1?null:(De*ts+Ue*ns+Ye*Ps)*vt}function _ft(N,p,_,C,M,F,z,H,Y){const se=1<<_,me=F-C,xe=z-M,_e=(N+1)/se*me+C,Te=(p+0)/se*xe+M,De=(p+1)/se*xe+M;H[0]=(N+0)/se*me+C,H[1]=Te,Y[0]=_e,Y[1]=De}class wft{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)),Y=[];let se=Math.ceil(Math.pow(2,H));const me=(Ye,nt,it,ut,ot)=>{const vt=ut?1:0,kt=(Ye+1)*it-vt,ls=nt*it,At=(nt+1)*it-vt;ot[0]=Ye*it,ot[1]=ls,ot[2]=kt,ot[3]=At};let xe=new yft(se);const _e=1/se,{floatView:Te,stride:De}=F,Ue=[];for(let Ye=0;YePs&&(Ps=_n)}}xe.minimums.push(ls),xe.maximums.push(Ps),xe.leaves.push(1)}for(Y.push(xe),se/=2;se>=1;se/=2){const Ye=Y.at(-1);xe=new yft(se);for(let nt=0;nt0;){const{idx:De,t:Ue,nodex:Ye,nodey:nt,depth:it}=Te.pop();if(this.leaves[De]){_ft(Ye,nt,it,p,_,C,M,xe,_e);const ot=1<1e-10,rr=Math.abs(z[1])>1e-10,On=z[0]>=0?1:-1,Ar=z[1]>=0?1:-1;let or=Math.max(0,Math.min(ln-1,Math.floor((Pn-Un)/Xs))),vr=Math.max(0,Math.min(_n-1,Math.floor(($n-Cs)/rn)));const Ga=Rn?Math.abs(Xs/z[0]):Number.MAX_VALUE,Wa=rr?Math.abs(rn/z[1]):Number.MAX_VALUE;let oi=Rn?In+(Un+(z[0]>=0?or+1:or)*Xs-Pn)/z[0]:Number.MAX_VALUE,Fa=rr?In+(Cs+(z[1]>=0?vr+1:vr)*rn-$n)/z[1]:Number.MAX_VALUE;const Ai=(Vm,ho)=>ts[(ho+1)*ns+Vm+1]*H;let Ni=Ai(Ps+or,mn+vr),Fo=Ai(Ps+or+1,mn+vr),rl=Ai(Ps+or,mn+vr+1),Bl=Ai(Ps+or+1,mn+vr+1),bc=null;for(let Vm=0;Vm=0||F[2]+z[2]*ho<=Math.max(Ni,Fo,rl,Bl)){const Ip=Un+or*Xs,gf=Ip+Xs,$x=Cs+vr*rn,Ux=$x+rn,Ub=bft(gf,$x,Fo,Ip,$x,Ni,Ip,Ux,rl,F,z),_y=bft(Ip,Ux,rl,gf,Ux,Bl,gf,$x,Fo,F,z);Ub!=null&&Ub>=0&&(bc===null||Ub=0&&(bc===null||_y=ln||vr<0||vr>=_n||bc!==null&&ho>bc)break;mp?On>0?(Ni=Fo,rl=Bl,Fo=Ai(Ps+or+1,mn+vr),Bl=Ai(Ps+or+1,mn+vr+1)):(Fo=Ni,Bl=rl,Ni=Ai(Ps+or,mn+vr),rl=Ai(Ps+or,mn+vr+1)):Ar>0?(Ni=rl,Fo=Bl,rl=Ai(Ps+or,mn+vr+1),Bl=Ai(Ps+or+1,mn+vr+1)):(rl=Ni,Bl=Fo,Ni=Ai(Ps+or,mn+vr),Fo=Ai(Ps+or+1,mn+vr))}if(bc!==null)return bc||0;const qm=Ne([],F,z,Ue),W0=(qm[0]-xe[0])/(_e[0]-xe[0]),Zh=(qm[1]-xe[1])/(_e[1]-xe[1]),_l=hM(vt,ls,this.dem)*H,qd=hM(kt,ls,this.dem)*H,hh=hM(kt,At,this.dem)*H;if(jft(_l,qd,hM(vt,At,this.dem)*H,hh,W0,Zh)>=qm[2])return Ue;continue}let ut=0;for(let ot=0;ot=se[me[At]]&&(me.splice(At,0,ot),ls=!0);ls||(me[ut]=ot),ut++}}for(let ot=0;ot=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 C=[0,0,0,0],M=Ule.getUnpackVector(_);let F=Math.floor((p+M[3])/M[2]);return C[2]=F%256,F=Math.floor(F/256),C[1]=F%256,F=Math.floor(F/256),C[0]=F,C}getPixels(){return new rdt({width:this.stride,height:this.stride},this.pixels)}backfillBorder(p,_,C){if(this.dim!==p.dim)throw new Error("dem dimension mismatch");let M=_*this.dim,F=_*this.dim+this.dim,z=C*this.dim,H=C*this.dim+this.dim;switch(_){case-1:M=F-1;break;case 1:F=M+1}switch(C){case-1:z=H-1;break;case 1:H=z+1}const Y=-_*this.dim,se=-C*this.dim;for(let me=z;me=1;C--){const M=C===1?1:0,F=C===2?1:0;for(let z=0;z>>1^-(1&N[p]);return N}function jps(N,p){switch(p){case"uint32":return N;case"uint16":for(let _=0;_>4|(61440&C)>>8|(240&M)<<4|61440&M,N[_+1]=15&C|(3840&C)>>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&C)>>4|(48&M)>>2|48&F|(48&z)<<2,N[_+2]=(12&C)>>2|12&M|(12&F)<<2|(12&z)<<4,N[_+3]=3&C|(3&M)<<2|(3&F)<<4|(3&z)<<6}return N;default:throw new Error(`Invalid pixel format, "${p}"`)}}oa(Ule,"DEMData"),oa(wft,"DemMinMaxQuadTree",{omit:["dem"]});var cj=Uint8Array,tZ=Uint16Array,Nps=Int32Array,Nft=new cj([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]),kft=new cj([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]),kps=new cj([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Sft=function(N,p){for(var _=new tZ(31),C=0;C<31;++C)_[C]=p+=1<>1|(21845&hp)<<1;Eft[hp]=((65280&(n$=(61680&(n$=(52428&n$)>>2|(13107&n$)<<2))>>4|(3855&n$)<<4))>>8|(255&n$)<<8)>>1}var sZ=function(N,p,_){for(var C=N.length,M=0,F=new tZ(p);M>Y]=se;return z},nZ=new cj(288);for(hp=0;hp<144;++hp)nZ[hp]=8;for(hp=144;hp<256;++hp)nZ[hp]=9;for(hp=256;hp<280;++hp)nZ[hp]=7;for(hp=280;hp<288;++hp)nZ[hp]=8;var Tft=new cj(32);for(hp=0;hp<32;++hp)Tft[hp]=5;var Aps=sZ(nZ,9),Eps=sZ(Tft,5),T8e=function(N){for(var p=N[0],_=1;_p&&(p=N[_]);return p},Wk=function(N,p,_){var C=p/8|0;return(N[C]|N[C+1]<<8)>>(7&p)&_},M8e=function(N,p){var _=p/8|0;return(N[_]|N[_+1]<<8|N[_+2]<<16)>>(7&p)},Tps=function(N){return(N+7)/8|0},Mps=["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"],Kk=function(N,p,_){var C=new Error(p||Mps[N]);if(C.code=N,Error.captureStackTrace&&Error.captureStackTrace(C,Kk),!_)throw C;return C},Pps=new cj(0),Ips=typeof TextDecoder<"u"&&new TextDecoder;try{Ips.decode(Pps,{stream:!0})}catch{}const Lps={gzip_data:"gzip"};class Z2 extends Error{constructor(p){super(p),this.name="MRTError"}}const Rps={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},Mft={uint32:1,uint16:2,uint8:4},Dps={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let P8e;class qle{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 Z2(`Layer '${p}' not found`);return _}getHeaderLength(p){const _=new Uint8Array(p),C=new DataView(p);if(_[0]!==13)throw new Z2("File is not a valid MRT.");return C.getUint32(1,!0)}parseHeader(p){const _=new Uint8Array(p),C=this.getHeaderLength(p);if(_.length= ${C} 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(vps(F,F.readVarint()+F.pos));return z}(new P8e(_.subarray(0,C)));if(!isNaN(this.x)&&(this.x!==M.x||this.y!==M.y||this.z!==M.z))throw new Z2(`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 Pft(F,{cacheSize:this._cacheSize});return this}createDecodingTask(p){const _=[],C=this.getLayer(p.layerName);for(let M of p.blockIndices){const F=C.dataIndex[M],z=F.firstByte-p.firstByte,H=F.lastByte-p.firstByte;if(C._blocksInProgress.has(M))continue;const Y={layerName:C.name,firstByte:z,lastByte:H,pixelFormat:C.pixelFormat,blockIndex:M,blockShape:[F.bands.length].concat(C.bandShape),buffer:C.buffer,codec:F.codec.codec,filters:F.filters.map(se=>se.filter)};C._blocksInProgress.add(M),_.push(Y)}return new Ift(_,()=>{_.forEach(M=>C._blocksInProgress.delete(M.blockIndex))},(M,F)=>{if(_.forEach(z=>C._blocksInProgress.delete(z.blockIndex)),M)throw M;F.forEach(z=>{this.getLayer(z.layerName).processDecodedData(z)})})}}class Pft{constructor({version:p,name:_,units:C,tileSize:M,pixelFormat:F,buffer:z,dataIndex:H},Y){if(this.version=p,this.version!==1)throw new Z2(`Cannot parse raster layer encoded with MRT version ${p}`);this.name=_,this.units=C,this.tileSize=M,this.buffer=z,this.pixelFormat=Rps[F],this.dataIndex=H,this.bandShape=[M+2*z,M+2*z,Mft[this.pixelFormat]],this._decodedBlocks=new A8e(Y?Y.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return Mft[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[C,M]of this.dataIndex.entries()){for(const[F,z]of M.bands.entries())if(z===p)return{bandIndex:_+F,blockIndex:C,blockBandIndex:F};_+=M.bands.length}break;case"number":for(const[C,M]of this.dataIndex.entries()){if(p>=_&&p<_+M.bands.length)return{bandIndex:p,blockIndex:C,blockBandIndex:p-_};_+=M.bands.length}break;default:throw new Z2(`Invalid band \`${JSON.stringify(p)}\`. Expected string or integer.`)}return{blockIndex:-1,blockBandIndex:-1}}getDataRange(p){let _=1/0,C=-1/0;const M=[],F=new Set;for(const z of p){const{blockIndex:H}=this.getBlockForBand(z);if(H<0)throw new Z2(`Invalid band: ${JSON.stringify(z)}`);const Y=this.dataIndex[H];M.includes(H)||M.push(H),F.add(H),_=Math.min(_,Y.firstByte),C=Math.max(C,Y.lastByte)}if(F.size>this.cacheSize)throw new Z2(`Number of blocks to decode (${F.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:_,lastByte:C,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:C}=this.getBlockForBand(p);if(_<0)throw new Z2(`Band not found: ${JSON.stringify(p)}`);const M=this._decodedBlocks.get(_.toString());if(!M)throw new Z2(`Data for band ${JSON.stringify(p)} of layer "${this.name}" not decoded.`);const F=this.dataIndex[_],z=this.bandShape.reduce((se,me)=>se*me,1),H=C*z,Y=M.subarray(H,H+z);return{data:Y,bytes:new Uint8Array(Y.buffer).subarray(Y.byteOffset,Y.byteOffset+Y.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:F.offset,scale:F.scale}}}qle.setPbf=function(N){P8e=N};class Ift{constructor(p,_,C){this.tasks=p,this._onCancel=_,this._onComplete=C,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(p,_){this._finalized||(this._onComplete(p,_),this._finalized=!0)}}qle.performDecoding=function(N,p){const _=new Uint8Array(N);return Promise.all(p.tasks.map(C=>{const{layerName:M,firstByte:F,lastByte:z,pixelFormat:H,blockShape:Y,blockIndex:se,filters:me,codec:xe}=C,_e=_.subarray(F,z+1),Te=new Uint32Array(Y[0]*Y[1]*Y[2]);let De;if(xe!=="gzip_data")throw new Z2(`Unhandled codec: ${xe}`);return De=function(Ue,Ye){if(!globalThis.DecompressionStream&&Ye==="gzip_data")return Promise.resolve((vt=function(At){At[0]==31&&At[1]==139&&At[2]==8||Kk(6,"invalid gzip data");var qt=At[3],ts=10;4&qt&&(ts+=2+(At[10]|At[11]<<8));for(var ns=(qt>>3&1)+(qt>>4&1);ns>0;ns-=!At[ts++]);return ts+(2&qt)}(nt=Ue),vt+8>nt.length&&Kk(6,"invalid gzip data"),function(At,qt,ts,ns){var Ps=At.length;if(!Ps||qt.f&&!qt.l)return ts||new cj(0);var Ws=!ts,mn=Ws||qt.i!=2,ln=qt.i;Ws&&(ts=new cj(3*Ps));var _n=function(_y){var qx=ts.length;if(_y>qx){var wy=new cj(Math.max(2*qx,_y));wy.set(ts),ts=wy}},Un=qt.f||0,Cs=qt.p||0,Xs=qt.b||0,rn=qt.l,In=qt.d,Pn=qt.m,$n=qt.n,Rn=8*Ps;do{if(!rn){Un=Wk(At,Cs,1);var rr=Wk(At,Cs+1,3);if(Cs+=3,!rr){var On=At[(rl=Tps(Cs)+4)-4]|At[rl-3]<<8,Ar=rl+On;if(Ar>Ps){ln&&Kk(0);break}mn&&_n(Xs+On),ts.set(At.subarray(rl,Ar),Xs),qt.b=Xs+=On,qt.p=Cs=8*Ar,qt.f=Un;continue}if(rr==1)rn=Aps,In=Eps,Pn=9,$n=5;else if(rr==2){var or=Wk(At,Cs,31)+257,vr=Wk(At,Cs+10,15)+4,Ga=or+Wk(At,Cs+5,31)+1;Cs+=14;for(var Wa=new cj(Ga),oi=new cj(19),Fa=0;Fa>4)<16)Wa[Fa++]=rl;else{var bc=0,qm=0;for(rl==16?(qm=3+Wk(At,Cs,3),Cs+=2,bc=Wa[Fa-1]):rl==17?(qm=3+Wk(At,Cs,7),Cs+=3):rl==18&&(qm=11+Wk(At,Cs,127),Cs+=7);qm--;)Wa[Fa++]=bc}}var W0=Wa.subarray(0,or),Zh=Wa.subarray(or);Pn=T8e(W0),$n=T8e(Zh),rn=sZ(W0,Pn),In=sZ(Zh,$n)}else Kk(1);if(Cs>Rn){ln&&Kk(0);break}}mn&&_n(Xs+131072);for(var _l=(1<>4;if((Cs+=15&bc)>Rn){ln&&Kk(0);break}if(bc||Kk(2),Vm<256)ts[Xs++]=Vm;else{if(Vm==256){hh=Cs,rn=null;break}var ho=Vm-254;Vm>264&&(ho=Wk(At,Cs,(1<<(gf=Nft[Fa=Vm-257]))-1)+Aft[Fa],Cs+=gf);var mp=In[M8e(At,Cs)&qd],Ip=mp>>4;if(mp||Kk(3),Cs+=15&mp,Zh=Cps[Ip],Ip>3){var gf=kft[Ip];Zh+=M8e(At,Cs)&(1<Rn){ln&&Kk(0);break}mn&&_n(Xs+131072);var $x=Xs+ho;if(Xs_y.length)&&(wy=_y.length),new cj(_y.subarray(0,wy))}(ts,0,Xs):ts.subarray(0,Xs)}(nt.subarray(vt,-8),{i:2},new cj(((ut=nt)[(ot=ut.length)-4]|ut[ot-3]<<8|ut[ot-2]<<16|ut[ot-1]<<24)>>>0),it)));var nt,it,ut,ot,vt;const kt=Lps[Ye];if(!kt)throw new Error(`Unhandled codec: ${Ye}`);const ls=new globalThis.DecompressionStream(kt);return new Response(new Blob([Ue]).stream().pipeThrough(ls)).arrayBuffer().then(At=>new Uint8Array(At))}(_e,xe).then(Ue=>(function(Ye,nt){let it;for(;it=Ye.nextField();)if(it===2)bps(Ye,Ye.readVarint()+Ye.pos,nt);else if(it===3)throw new Error("Not implemented")}(new P8e(Ue),Te),new Dps[H](Te.buffer))),De.then(Ue=>{for(let Ye=me.length-1;Ye>=0;Ye--)switch(me[Ye]){case"delta_filter":_ps(Ue,Y);break;case"zigzag_filter":wps(Ue);break;case"bitshuffle_filter":jps(Ue,H);break;default:throw new Z2(`Unhandled filter "${me[Ye]}"`)}return{layerName:M,blockIndex:se,data:Ue}}).catch(Ue=>{throw Ue})}))},oa(Ift,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),oa(qle,"MapboxRasterTile"),oa(Pft,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const Lft=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Pp=new Uint32Array(96);class I8e{static from(p){if(!p||p.byteLength===void 0||p.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");const[_,C]=new Uint8Array(p,0,2);if(_!==219)throw new Error("Data does not appear to be in a KDBush format.");const M=C>>4;if(M!==1)throw new Error(`Got v${M} data when expected v1.`);const F=Lft[15&C];if(!F)throw new Error("Unrecognized array type.");const[z]=new Uint16Array(p,2,1),[H]=new Uint32Array(p,4,1);return new I8e(H,z,F,void 0,p)}constructor(p,_=64,C=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=C,this.IndexArrayType=p<65536?Uint16Array:Uint32Array;const z=Lft.indexOf(this.ArrayType),H=2*p*this.ArrayType.BYTES_PER_ELEMENT,Y=p*this.IndexArrayType.BYTES_PER_ELEMENT,se=(8-Y%8)%8;if(z<0)throw new Error(`Unexpected typed array class: ${C}.`);if(F)this.data=F,this.ids=new this.IndexArrayType(F,8,p),this.coords=new C(F,8+Y+se,2*p),this._pos=2*p,this._finished=!0;else{const me=this.data=new M(8+H+Y+se);this.ids=new this.IndexArrayType(me,8,p),this.coords=new C(me,8+Y+se,2*p),this._pos=0,this._finished=!1,new Uint8Array(me,0,2).set([219,16+z]),new Uint16Array(me,2,1)[0]=_,new Uint32Array(me,4,1)[0]=p}}add(p,_){const C=this._pos>>1;return this.ids[C]=C,this.coords[this._pos++]=p,this.coords[this._pos++]=_,C}finish(){const p=this._pos>>1;if(p!==this.numItems)throw new Error(`Added ${p} items when expected ${this.numItems}.`);return L8e(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(p,_,C,M){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:F,coords:z,nodeSize:H}=this;Pp[0]=0,Pp[1]=F.length-1,Pp[2]=0;let Y=3;const se=[];for(;Y>0;){const me=Pp[--Y],xe=Pp[--Y],_e=Pp[--Y];if(xe-_e<=H){for(let Ye=_e;Ye<=xe;Ye++){const nt=z[2*Ye],it=z[2*Ye+1];nt>=p&&nt<=C&&it>=_&&it<=M&&se.push(F[Ye])}continue}const Te=_e+xe>>1,De=z[2*Te],Ue=z[2*Te+1];De>=p&&De<=C&&Ue>=_&&Ue<=M&&se.push(F[Te]),(me===0?p<=De:_<=Ue)&&(Pp[Y++]=_e,Pp[Y++]=Te-1,Pp[Y++]=1-me),(me===0?C>=De:M>=Ue)&&(Pp[Y++]=Te+1,Pp[Y++]=xe,Pp[Y++]=1-me)}return se}within(p,_,C){const M=[];return this.withinInto(p,_,C,M),M}withinInto(p,_,C,M){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:F,coords:z,nodeSize:H}=this;Pp[0]=0,Pp[1]=F.length-1,Pp[2]=0;let Y=3,se=0;const me=C*C;for(;Y>0;){const xe=Pp[--Y],_e=Pp[--Y],Te=Pp[--Y];if(_e-Te<=H){for(let nt=Te;nt<=_e;nt++)Dft(z[2*nt],z[2*nt+1],p,_)<=me&&(M[se++]=F[nt]);continue}const De=Te+_e>>1,Ue=z[2*De],Ye=z[2*De+1];Dft(Ue,Ye,p,_)<=me&&(M[se++]=F[De]),(xe===0?p-C<=Ue:_-C<=Ye)&&(Pp[Y++]=Te,Pp[Y++]=De-1,Pp[Y++]=1-xe),(xe===0?p+C>=Ue:_+C>=Ye)&&(Pp[Y++]=De+1,Pp[Y++]=_e,Pp[Y++]=1-xe)}return se}}function L8e(N,p,_,C,M,F){if(M-C<=_)return;const z=C+M>>1;Rft(N,p,z,C,M,F),L8e(N,p,_,C,z-1,1-F),L8e(N,p,_,z+1,M,1-F)}function Rft(N,p,_,C,M,F){for(;M>C;){if(M-C>600){const se=M-C+1,me=_-C+1,xe=Math.log(se),_e=.5*Math.exp(2*xe/3),Te=.5*Math.sqrt(xe*_e*(se-_e)/se)*(me-se/2<0?-1:1);Rft(N,p,_,Math.max(C,Math.floor(_-me*_e/se+Te)),Math.min(M,Math.floor(_+(se-me)*_e/se+Te)),F)}const z=p[2*_+F];let H=C,Y=M;for(rZ(N,p,C,_),p[2*M+F]>z&&rZ(N,p,C,M);Hz;)Y--}p[2*C+F]===z?rZ(N,p,C,Y):(Y++,rZ(N,p,Y,M)),Y<=_&&(C=Y+1),_<=Y&&(M=Y-1)}}function rZ(N,p,_,C){R8e(N,_,C),R8e(p,2*_,2*C),R8e(p,2*_+1,2*C+1)}function R8e(N,p,_){const C=N[p];N[p]=N[_],N[_]=C}function Dft(N,p,_,C){const M=N-_,F=p-C;return M*M+F*F}c.$=by,c.A=U0,c.B=Dx,c.C=Ci,c.D=D1,c.E=Xc,c.F=np,c.G=Mk,c.H=Yw,c.I=vd,c.J=F6,c.K=/^(.*)-transition$/,c.L=A8e,c.M=lp,c.N=zk,c.O=Tr,c.P=xs,c.Q=y,c.R=gr,c.S=U3,c.T=Goe,c.U=/^(.*)-use-theme$/,c.V=function(N,p){const _=U3(p.zoom);if(_===0)return VC(N);const C=Moe(N),M=aOe(C),F=Zg(C.getWest())*p.worldSize,z=Zg(C.getEast())*p.worldSize,H=rp(C.getNorth())*p.worldSize,Y=rp(C.getSouth())*p.worldSize,se=[F,H,0],me=[z,H,0],xe=[F,Y,0],_e=[z,Y,0],Te=A([],p.globeMatrix);return Qe(se,se,Te),Qe(me,me,Te),Qe(xe,xe,Te),Qe(_e,_e,Te),M[0]=$3(M[0],xe,_),M[1]=$3(M[1],_e,_),M[2]=$3(M[2],me,_),M[3]=$3(M[3],se,_),du.fromPoints(M)},c.W=iOe,c.X=E,c.Y=v,c.Z=vy,c._=lj,c.a=async function(N,p){N.headers||(N.headers={}),N.headers.accept="image/webp,*/*";const _=await function(C){return new Promise((M,F)=>{if(C&&C.aborted)return void F(C.reason);const z=()=>{const se=$a.shift();se?se():Na--};if(Na{C&&C.removeEventListener("abort",Y),M(z)},Y=()=>{const se=$a.indexOf(H);se!==-1&&$a.splice(se,1),F(C.reason)};C&&C.addEventListener("abort",Y),$a.push(H)})}(p);try{const{data:C,headers:M}=await Xr(N,p);let F;try{F=await createImageBitmap(new Blob([new Uint8Array(C)],{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=Mmt,c.a1=wh,c.a2=up,c.a3=lo,c.a4=Of,c.a5=Um,c.a6=Pr,c.a7=Zg,c.a8=rp,c.a9=function(N,p,_){if(p.projection.name===_.projection.name)return N.projMatrix;const C=_.clone();return C.setProjection(p.projection),gOe(C,p.getProjection(),N)},c.aA=B3,c.aB=T,c.aC=Tdt,c.aD=_le,c.aE=oht,c.aF=t$,c.aG=oft,c.aH=yh,c.aI=(N,p,_,C,M,F,z,H,Y,se,me,xe,_e,Te,De,Ue,Ye,nt,it=!1)=>{const ut=nft(N,p,_,C,M,F,z,H,se,me,xe,_e,Te,De,Ue,Ye,1,[0,0,0],[0,0,1],it),ot={u_height_factor:-Math.pow(2,H.overscaledZ)/Y.tileSize/8};return Object.assign(ut,tft(p,Y,nt),ot)},c.aJ=nft,c.aK=G3,c.aL=450,c.aM=7,c.aN=(N,p,_,C,M,F)=>({u_matrix:N,u_edge_radius:p,u_width_scale:_,u_vertical_scale:C,u_height_type:Fle[M],u_base_type:Fle[F]}),c.aO=P,c.aP=A,c.aQ=S,c.aR=aft,c.aS=4,c.aT=2,c.aU=$Fe,c.aV=UFe,c.aW=zc,c.aX=class{static calculate(N,p,_){const C=new Set,M=new Map,F=new Set,z=new Set;for(const Y of Object.values(N))for(const[se,me]of Object.entries(Y.floors)){F.add(se),me.isDefault&&z.add(se),me.conflicts&&M.set(se,me.conflicts);const xe=se===p,_e=me.connections&&p&&me.connections.has(p);(xe||_e)&&C.add(se)}const H=Y=>{const se=M.get(Y)||new Set;for(const me of C)if((M.get(me)||new Set).has(Y)||se.has(me))return!0;return!1};if(_)for(const Y of _)F.has(Y)&&(H(Y)||C.add(Y));for(const Y of z)C.has(Y)||H(Y)||C.add(Y);return C}},c.aY=$m,c.aZ=G_,c.a_=class extends yy{constructor(N){super(N),this.current=new Float32Array(9)}set(N,p,_){if(!this.fetchUniformLocation(N,p))return;const C=this.current;for(let M=0;M<9;M++)if(_[M]!==C[M]){C.set(_),this.gl.uniformMatrix3fv(this.location,!1,C);break}}},c.aa=re,c.ab=Hr,c.ac=hhs,c.ad=Li,c.ae=$r,c.af=gl,c.ag=Wu,c.ah=fr,c.ai=class{constructor(N){this.specification=N}possiblyEvaluate(N,p){return Mh(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=Hn,c.ak=og,c.al=Sl,c.am=ya,c.an=pc,c.ao=65,c.ap=45,c.aq=function(N,p,_){const C=Q.fromLngLat(p),M=_.elevation?_.elevation.getAtPointOrZero(C):0;return Bdt(N,C.x,C.y,M,_)},c.ar=function(N,p,_,C,M,F,z){const H=[[_,C,0],[M,C,0],[M,F,0],[_,F,0]];let Y=Number.MAX_VALUE,se=-Number.MAX_VALUE;for(const me of H){const xe=ce(Qe([],me,p));Y=Math.min(Y,xe),se=Math.max(se,xe)}return[Uoe(N,Y,z.pitch),Uoe(N,se,z.pitch)]},c.as=Gu,c.at=Bdt,c.au=PY,c.av=Yr,c.aw=function(){return cc++},c.ax=class{constructor(N,p,_){this.target=N,this.parent=p,this.mapId=_,this.pendingResponses=new Map,zc(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new ups}send(N,p,_){const{signal:C,targetMapId:M,metadata:F}=_||{},z=Math.round(1e18*Math.random()).toString(36).substring(0,10),H=new Set;return C&&C.aborted?Promise.reject(C.reason):(this.target.postMessage({id:z,type:N,targetMapId:M,sourceMapId:this.mapId,data:qv(p,H)},[...H]),new Promise((Y,se)=>{const me={resolve:Y,reject:se,metadata:F||gft};if(C){const xe=()=>{this.pendingResponses.delete(z),se(C.reason)};C.addEventListener("abort",xe,{once:!0}),me.detach=()=>C.removeEventListener("abort",xe)}this.pendingResponses.set(z,me)}))}notify(N,p,_){const{targetMapId:C}=_||{},M=new Set;this.target.postMessage({type:N,targetMapId:C,sourceMapId:this.mapId,data:qv(p,M)},[...M])}sendCancelable(N,p,_,C){const M=new AbortController;return this.send(N,p,{..._,signal:M.signal}).then(F=>C(null,F)).catch(F=>{F.name!=="AbortError"&&C(F)}),M}getWorkerSourceActor(N){return{scheduler:this.scheduler,send:(p,_,C)=>this.send(p,_,{...C,targetMapId:N}),notify:(p,_)=>{this.notify(p,_,{targetMapId:N})},sendCancelable:(p,_,C,M)=>this.sendCancelable(p,_,{...C,targetMapId:N},M)}}receive(N){const p=N.data;if(!p)return;const _=p.id;if(!p.targetMapId||this.mapId===p.targetMapId)if(Yc(self)){const C=this.pendingResponses.get(_);this.scheduler.add(()=>{this.processTask(_,p)},C&&C.metadata||gft)}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(Bx(p.error)):M.resolve(Bx(p.data))}catch(F){M.reject(F)}}return}const _=new Set,C=Bx(p.data);try{let M;if(this.parent[p.type])M=await this.parent[p.type](p.sourceMapId,C);else{if(!this.parent.getWorkerSource)throw new Error(`Could not find function ${p.type}`);{const F=p.type.split("."),{source:z,scope:H}=C;M=await this.parent.getWorkerSource(p.sourceMapId,{type:F[0],source:z,scope:H})[F[1]](C)}}if(!N)return;this.target.postMessage({id:N,type:"",sourceMapId:this.mapId,error:null,data:qv(M,_)},[..._])}catch(M){this.target.postMessage({id:N,type:"",sourceMapId:this.mapId,error:qv(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([_,C]){const M=Mh([1,_,C]);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=nR,c.b=e0,c.b$=rh,c.b0=Vl,c.b1=ea,c.b2=6,c.b3=Moe,c.b4=function(N){const p=80.051129;N=ea(N,-80.051129,p)/p*90;const _=Math.pow(Math.abs(Math.sin(Yr(N))),3);return Math.round(_*(yY.length-1))},c.b5=Loe,c.b6=VC,c.b7=function(N){const p=N.pixelsPerMeter,_=p/Xd(1,N.center.lat),C=w(new Float64Array(16));return I(C,C,[N.point.x,N.point.y,0]),P(C,C,[_,_,p]),Float32Array.from(C)},c.b8=function(N,p,_,C){const M=p.getNorth(),F=p.getSouth(),z=p.getWest(),H=p.getEast(),Y=1<0){const De=180/C;g(Te,Te,[De/se+1,0,0,0,De/me+1,0,-.5*De/xe,.5*De/_e,1])}return Te[2]=Y,Te[5]=N.x,Te[8]=N.y,Te},c.b9=Gg,c.bA=ZFe,c.bB=zFe,c.bC=dt,c.bD=Gs,c.bE=_d,c.bF=eOe,c.bG=ZT,c.bH=kY,c.bI=Qe,c.bJ=$3,c.bK=Ls,c.bL=_hs,c.bM=W,c.bN=I,c.bO=function(){zr.isLoading()||zr.isLoaded()||xy()!=="deferred"||U_()},c.bP=et,c.bQ=ug,c.bR=function(N,p){const _=[];for(const C in N)C in p||_.push(C);return _},c.bS=pft,c.bT=Q,c.bU=Co,c.bV="hd_road_coverage",c.bW=rM,c.bX=Roe,c.bY=G6,c.bZ=le,c.b_=lm,c.ba=256,c.bb=Ymt,c.bc=hd,c.bd=Ko,c.be=jt,c.bf=yt,c.bg=Ss,c.bh=X,c.bi=ve,c.bj=ig,c.bk=JT,c.bl=Uc,c.bm=yu,c.bn=joe,c.bo=e$,c.bp=vo,c.bq=cOe,c.br=Rx,c.bs=$d,c.bt=sn,c.bu=dc,c.bv=Qoe,c.bw=dY,c.bx=_t,c.by=sR,c.bz=ws,c.c=V0,c.c$=qoe,c.c0=function(N,p,_){const C=U3(_.zoom),M=N.style.map._antialias,F=N.terrain&&N.terrain.exaggeration()>0;return C===0&&!M&&!F},c.c1=function(N,p,_){const C=w(new Float64Array(16)),M=(p/(1<{C(F,z)},p):C(F,z),()=>{}}return M.callbacks.push(C),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!==C),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 _=xt.TILE_PROVIDER_URLS[p];if(!_)return null;let C;try{C=new URL(_,xt.API_URL).href}catch{return new Error(`TileProvider "${p}" has an invalid URL: "${_}"`)}return{name:p,url:C}},c.cE=dft,c.cF=$le,c.cG=ar,c.cH=function(N,p,_){const C=JSON.stringify(N.request);return N.data&&(this.deduped.entries[C]={result:[null,N.data]}),this.deduped.request(C,{type:"parseTile",renderSourceType:N.renderSourceType,zoom:N.tileZoom},M=>{const F=new AbortController;return Xr(N.request,F.signal).then(({data:z,headers:H})=>{M(null,{rawData:z,vectorTile:_?void 0:new BFe(new qoe(z)),headers:H})}).catch(z=>{F.signal.aborted||(et(z)?M(null,null):M(z))}),()=>{F.abort(),M(null,null)}},p)},c.cI=Xa,c.cJ=function(N){gn++,gn>Ts&&(N.getActor().notify("enforceCacheSizeLimit",js),gn=0)},c.cK=Eu,c.cL=async function(N,p,_){const C=N.url&&!N.tiles?await p.transformRequest(N.url,gr.Source,_):void 0;return{request:C,options:C?{...N,url:C.url}:N}},c.cM=function(N,p,_){return p?cft(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 _=xft.get(N);if(_)return _;const C=E8e.get(N);if(C!==void 0)return C;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 xft.set(N,z),z}).finally(()=>{E8e.delete(N)});return E8e.set(N,M),M},c.cO=class{constructor(N,p){this.context=N,this.texture=p}bind(N,p){const{context:_}=this,{gl:C}=_;C.bindTexture(C.TEXTURE_2D,this.texture),N!==this.minFilter&&(C.texParameteri(C.TEXTURE_2D,C.TEXTURE_MAG_FILTER,N),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_MIN_FILTER,N),this.minFilter=N),p!==this.wrapS&&(C.texParameteri(C.TEXTURE_2D,C.TEXTURE_WRAP_S,p),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_WRAP_T,p),this.wrapS=p)}},c.cP=L,c.cQ=function(N,p,_,C){for(;p<_;){const M=p+_>>1;N[M]<=C?p=M+1:_=M}return p},c.cR=function(N,p,_,C){for(;p<_;){const M=p+_>>1;N[M]{p.onloadstart=()=>_(),p.onerror=()=>C(new Error(`Could not load video: ${N.join(", ")}`))}),p},c.cX=tmt,c.cY=dmt,c.cZ=Il,c.c_=qle,c.ca=Ne,c.cb=tft,c.cc=kdt,c.cd=YY,c.ce=i8e,c.cf=qi,c.cg=cm,c.ch=function(N,p){const _=[0,0,0];return Qe(_,_,Loe(VC(p.canonical))),Qe(_,_,N),_},c.ci=Hv,c.cj=function(N,p,_,C,M,F){const{width:z,height:H}=C.imageManager.getPixelSize(p),Y=Math.pow(2,F.tileID.overscaledZ),se=F.tileSize*Math.pow(2,C.transform.tileZoom)/Y,me=se*(F.tileID.canonical.x+F.tileID.wrap*Y),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?[C.transform.width,-1*C.transform.height]:[1/YY(F,1,C.transform.tileZoom),1/YY(F,1,C.transform.tileZoom)],u_pixel_coord_upper:[me>>16,xe>>16],u_pixel_coord_lower:[65535&me,65535&xe]}},c.ck=N=>({u_matrix:new Of(N),u_texsize:new up(N),u_pixels_to_tile_units:new W6(N),u_device_pixel_ratio:new lo(N),u_width_scale:new lo(N),u_floor_width_scale:new lo(N),u_image:new $m(N),u_units_to_pixels:new up(N),u_tile_units_to_pixels:new lo(N),u_alpha_discard_threshold:new lo(N),u_trim_offset:new up(N),u_trim_fade_range:new up(N),u_trim_gradient_mix_range:new up(N),u_trim_color:new G_(N),u_zbias_factor:new lo(N),u_tile_to_meter:new lo(N),u_ground_shadow_factor:new Um(N),u_pattern_transition:new lo(N),u_opacity_multiplier:new lo(N)}),c.cl=N=>({u_matrix:new Of(N),u_pixels_to_tile_units:new W6(N),u_device_pixel_ratio:new lo(N),u_width_scale:new lo(N),u_floor_width_scale:new lo(N),u_units_to_pixels:new up(N),u_dash_image:new $m(N),u_gradient_image:new $m(N),u_border_gradient_image:new $m(N),u_image_height:new lo(N),u_texsize:new up(N),u_tile_units_to_pixels:new lo(N),u_alpha_discard_threshold:new lo(N),u_trim_offset:new up(N),u_trim_fade_range:new up(N),u_trim_gradient_mix_range:new up(N),u_trim_color:new G_(N),u_zbias_factor:new lo(N),u_road_view_depth_bias:new lo(N),u_road_clip_to_view:new G_(N),u_tile_to_meter:new lo(N),u_ground_shadow_factor:new Um(N),u_opacity_multiplier:new lo(N)}),c.cm=N=>({u_color:new G6(N),u_matrix:new Of(N),u_overlay:new $m(N),u_overlay_scale:new lo(N)}),c.cn=N=>({u_camera_to_center_distance:new lo(N),u_extrude_scale:new W6(N),u_device_pixel_ratio:new lo(N),u_matrix:new Of(N),u_inv_rot_matrix:new Of(N),u_merc_center:new up(N),u_tile_id:new Um(N),u_zoom_transition:new lo(N),u_up_dir:new Um(N),u_emissive_strength:new lo(N)}),c.co=N=>({u_matrix:new Of(N),u_lightpos:new Um(N),u_lightintensity:new lo(N),u_lightcolor:new Um(N),u_vertical_gradient:new lo(N),u_height_factor:new lo(N),u_edge_radius:new lo(N),u_width_scale:new lo(N),u_ao:new up(N),u_height_type:new $m(N),u_base_type:new $m(N),u_tile_id:new Um(N),u_zoom_transition:new lo(N),u_inv_rot_matrix:new Of(N),u_merc_center:new up(N),u_up_dir:new Um(N),u_height_lift:new lo(N),u_image:new $m(N),u_texsize:new up(N),u_pixel_coord_upper:new up(N),u_pixel_coord_lower:new up(N),u_tile_units_to_pixels:new lo(N),u_opacity:new lo(N),u_pattern_transition:new lo(N)}),c.cp=N=>({u_matrix:new Of(N),u_lightpos:new Um(N),u_lightintensity:new lo(N),u_lightcolor:new Um(N),u_vertical_gradient:new lo(N),u_opacity:new lo(N),u_edge_radius:new lo(N),u_width_scale:new lo(N),u_ao:new up(N),u_height_type:new $m(N),u_base_type:new $m(N),u_tile_id:new Um(N),u_zoom_transition:new lo(N),u_inv_rot_matrix:new Of(N),u_merc_center:new up(N),u_up_dir:new Um(N),u_height_lift:new lo(N),u_flood_light_color:new Um(N),u_vertical_scale:new lo(N),u_flood_light_intensity:new lo(N),u_ground_shadow_factor:new Um(N),u_front_cutoff_params:new Um(N)}),c.cq=function(N,p,_=0,C=!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 C&&H.push(F.clone()),H},c.cr=function(N,p){const _=[];for(let C=0;C{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[C]of this.textures.entries()){if(this.currentFrameAtlases.has(C))continue;const M=this.textureAccessTimes.get(C)||0;M<_&&(_=M,p=C)}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 C=_.deref();if(C&&C.contentDescriptor){const M=N.subsetOf(C.contentDescriptor),F=this.isMipmapCompatible(N,C.contentDescriptor);if(M&&F)return C}}}getTextureForAtlas(N,p,_){this.textureAccessTimes.set(N,performance.now()),this.currentFrameAtlases.add(N);let C=this.textures.get(N);if(C)return C;if(N.image){const M=this.calculateTextureMemory(N);return this.evictTexturesIfNeeded(M),C=new Goe(p,N.image,_,{useMipmap:!!N.patternPositions.size}),this.textures.set(N,C),this.textureMemoryUsed+=M,C}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,C=this.cache.get(_);if(C){const M=C.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 G_(N)}),c.d0=Xr,c.d1=["type","source","source-layer","minzoom","maxzoom","filter","layout"],c.d2=Uv,c.d3=Cn,c.d4=Br,c.d5=ia,c.d6=Fn,c.d7=ml,c.d8=as,c.d9=.55,c.dA=Gt,c.dB=Woe,c.dC=NOe,c.dD=Zi,c.dE=$t,c.dF=dd,c.dG=$l,c.dH=function(N){const p=N.indexOf(YT);return p>=0?N.slice(0,p):N},c.dI=function(N){return N.includes(YT)},c.dJ=function(N){const p=N.lastIndexOf(YT);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 V0(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,_,C){return N.type==="custom"?new Efs(N,p):new cps[N.type](N,p,_,C)},c.dN=gc,c.dO=hY,c.dP=class extends sR{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=uh,c.dR=ift,c.dS=Udt,c.dT=function(){return{API_URL:xt.API_URL,DRACO_URL:xt.DRACO_URL,MESHOPT_URL:xt.MESHOPT_URL,MESHOPT_SIMD_URL:xt.MESHOPT_SIMD_URL,BUILDING_GEN_URL:xt.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=Xfs,c.d_=Qfs,c.da=dM,c.db=kmt,c.dc=KFe,c.dd=zdt,c.de=fOe,c.df=w,c.dg=O9,c.dh=.9,c.di=$dt,c.dj=function(N,p,_,C,M,F,z){const H=x8e(N,p,_,C,M,F,z);return F.name==="globe"&&_||(H[2]=H[6]=H[10]=H[14]=0),H},c.dk=function(N,p,_,C,M,F,z){if(_){if(F.name==="globe"){const H=x8e(N,p,_,C,M,F,z);return A(H,H),E(H,N,H),H}{const H=y(N),[Y,se,me,xe]=z,[_e,Te,De,Ue,Ye,nt,it,ut]=H;return H[0]=Y*_e+se*Ye,H[1]=Y*Te+se*nt,H[2]=Y*De+se*it,H[3]=Y*Ue+se*ut,H[4]=me*_e+xe*Ye,H[5]=me*Te+xe*nt,H[6]=me*De+xe*it,H[7]=me*Ue+xe*ut,C||O(H,H,-M.angle),H}}return M.glCoordMatrix},c.dl=z3,c.dm=dOe,c.dn=MY,c.dp=mOe,c.dq=$oe,c.dr=Ht,c.ds=Coe,c.dt=O3,c.du=hdt,c.dv=function(N,[p,_]){let C=0,M=0;if(_===yhs){p<0&&(p=0);const F=p/vhs;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":C=-F;break;case"top-left":case"bottom-left":C=F;break;case"left":C=p;break;case"right":C=-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":C=-p;break;case"top-left":case"bottom-left":case"left":C=p}}return[C,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=I8e,c.dy=xOe,c.dz=function(N){return N({pluginStatus:Mi,pluginURL:pl}),uh.on("pluginStateChange",N),N},c.e=ah,c.e$=Cd,c.e0=N=>({u_light_matrix_0:new Of(N),u_light_matrix_1:new Of(N),u_fade_range:new up(N),u_shadow_normal_offset:new Um(N),u_shadow_intensity:new lo(N),u_shadow_texel_size:new lo(N),u_shadow_map_resolution:new lo(N),u_shadow_direction:new Um(N),u_shadow_bias:new Um(N),u_shadowmap_0:new $m(N),u_shadowmap_1:new $m(N)}),c.e1=function(N,p,_){return p.name===_.projection.name?N.projMatrix:gOe(_,p,N)},c.e2=x8e,c.e3=QY,c.e4=Nmt,c.e5=X6,c.e6=function(N,p,_,C,M,F,z,H,Y,se,me=1){const xe=_.transform,_e=C?N.textSizeData:N.iconSizeData,Te=z3(_e,_.transform.zoom,me),De=xe.projection.name==="globe",Ue=(()=>{if(!De)return null;const At=U3(xe.zoom);return At===0?null:{t:At,invMatrix:xe.projection.createInversionMatrix(xe,se.canonical),mercCenter:[Zg(xe.center.lng),rp(xe.center.lat)]}})(),Ye=[256/_.width*2+1,256/_.height*2+1],nt=C?N.text.dynamicLayoutVertexArray:N.icon.dynamicLayoutVertexArray;nt.clear();let it=null;De&&(it=C?N.text.globeExtVertexArray:N.icon.globeExtVertexArray);const ut=N.lineVertexArray,ot=C?N.text.placedSymbolArray:N.icon.placedSymbolArray,vt=_.transform.width/_.transform.height;let kt,ls=!1;for(let At=0;At{const z=N.transform,H=z.projection.name==="globe";let Y;if(F.paint.get("circle-pitch-alignment")==="map")if(H){const me=kdt(z.zoom,p.canonical)*z._pixelsPerMercatorPixel;Y=Float32Array.from([me,0,0,me])}else Y=z.calculatePixelsToTileUnitsMatrix(_);else Y=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:ah.devicePixelRatio,u_extrude_scale:Y,u_inv_rot_matrix:_fs,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=C,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 C=_?{signal:_}:{};return await this._transformRequestFn(N,p,C)||{url:N}}normalizeStyleURL(N,p){if(!ar(N))return N;const _=Vt(N);return _.params.push(`sdk=js-${d}`),_.path=`/styles/v1${_.path}`,this._makeAPIURL(_,this._customAccessToken||p)}normalizeGlyphsURL(N,p){if(!ar(N))return N;const _=Vt(N);return _.path=`/fonts/v1${_.path}`,this._makeAPIURL(_,this._customAccessToken||p)}normalizeModelURL(N,p){if(!ar(N))return N;const _=Vt(N);return _.path=`/models/v1${_.path}`,this._makeAPIURL(_,this._customAccessToken||p)}normalizeSourceURL(N,p,_,C){if(!ar(N))return N;const M=Vt(N);return M.path=`/v4/${M.authority}.json`,M.params.push("secure"),_&&M.params.push(`language=${_}`),C&&M.params.push(`worldview=${C}`),this._makeAPIURL(M,this._customAccessToken||p)}normalizeIconsetURL(N,p){const _=Vt(N);return ar(N)?(_.path=`/styles/v1${_.path}/iconset.pbf`,this._makeAPIURL(_,this._customAccessToken||p)):Nn(_)}normalizeSpriteURL(N,p,_,C){const M=Vt(N);return ar(N)?(M.path=`/styles/v1${M.path}/sprite${p}${_}`,this._makeAPIURL(M,this._customAccessToken||C)):(M.path+=`${p}${_}`,Nn(M))}normalizeTileURL(N,p,_){if(this._isSkuTokenExpired()&&this._createSkuToken(),N&&!ar(N))return N;const C=Vt(N);C.path=C.path.replace(Lo,(p||_&&C.authority!=="raster"&&_===512?"@2x":"")+".webp"),C.authority==="raster"?C.path=`/${xt.RASTER_URL_PREFIX}${C.path}`:C.authority==="rasterarrays"?C.path=`/${xt.RASTERARRAYS_URL_PREFIX}${C.path}`:C.authority==="3dtiles"?C.path=`/${xt.TILES3D_URL_PREFIX}${C.path}`:(C.path=C.path.replace(Ul,"/"),C.path=`/${xt.TILE_URL_VERSION}${C.path}`);const M=this._customAccessToken||function(F){for(const z of F){const H=z.match(Pl);if(H)return H[1]}return null}(C.params)||xt.ACCESS_TOKEN;return xt.REQUIRE_ACCESS_TOKEN&&M&&this._skuToken&&C.params.push(`sku=${this._skuToken}`),this._makeAPIURL(C,M)}canonicalizeTileURL(N,p){const _=Vt(N);if(!nl.test(_.path)||!fo.test(_.path))return N;let C="mapbox://";_.path.startsWith("/raster/v1/")?C+=`raster/${_.path.replace(`/${xt.RASTER_URL_PREFIX}/`,"")}`:_.path.startsWith("/rasterarrays/v1/")?C+=`rasterarrays/${_.path.replace(`/${xt.RASTERARRAYS_URL_PREFIX}/`,"")}`:C+=`tiles/${_.path.replace(`/${xt.TILE_URL_VERSION}/`,"")}`;let M=_.params;return p&&(M=M.filter(F=>!F.match(Pl))),M.length&&(C+=`?${M.join("&")}`),C}canonicalizeTileset(N,p){const _=!!p&&ar(p),C=[];for(const M of N.tiles||[])Mn(M)?C.push(this.canonicalizeTileURL(M,_)):C.push(M);return C}_makeAPIURL(N,p){const _="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",C=Vt(xt.API_URL);if(N.protocol=C.protocol,N.authority=C.authority,N.protocol==="http"){const M=N.params.indexOf("secure");M>=0&&N.params.splice(M,1)}if(C.path!=="/"&&(N.path=`${C.path}${N.path}`),!xt.REQUIRE_ACCESS_TOKEN)return Nn(N);if(p=p||xt.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||""}`),Nn(N)}},c.eX=na,c.eY=function(N,p){p?zd.add(N):zd.delete(N)},c.eZ=ad,c.e_=Hu,c.ea=Uht,c.eb=(N,p,_,C,M,F,z,H,Y,se)=>{const me=N.transform,xe=me.pitch<15?ya(.07,.7,ea((14-me.zoom)/5,0,1)):.07,_e=_.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:$ht(N,p,_,C),u_texsize:p.imageAtlasTexture?p.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:me.calculatePixelsToTileUnitsMatrix(p),u_device_pixel_ratio:M,u_width_scale:F,u_floor_width_scale:z,u_image:0,u_tile_units_to_pixels:Bht(p,me),u_units_to_pixels:[1/me.pixelsToGLUnits[0],1/me.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(_e?null:_.lut).toArray01(),u_zbias_factor:xe,u_tile_to_meter:K(p.tileID.canonical,0),u_ground_shadow_factor:Y,u_pattern_transition:se,u_opacity_multiplier:1}},c.ec=(N,p,_,C,M,F,z,H,Y,se)=>{const me=N.transform,xe=me.calculatePixelsToTileUnitsMatrix(p),_e=_.paint.get("line-trim-color-use-theme").constantOr("default")==="none",Te=me.pitch<15?ya(.07,.7,ea((14-me.zoom)/5,0,1)):.07;return{u_matrix:$ht(N,p,_,C),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/me.pixelsToGLUnits[0],1/me.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_border_gradient_image:2,u_image_height:M,u_texsize:qht(_)&&p.lineAtlasTexture?p.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:Bht(p,N.transform),u_alpha_discard_threshold:0,u_trim_offset:Y,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(_e?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=Dr,c.ee=WY,c.ef=5,c.eg=Afs,c.eh=Dn,c.ei=function(N,p){var _=Math.sin(p),C=Math.cos(p);return N[0]=C,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]=C,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),C=Math.cos(p);return N[0]=1,N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[5]=C,N[6]=_,N[7]=0,N[8]=0,N[9]=-_,N[10]=C,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=to,c.en=1,c.eo=J9,c.ep=0,c.eq=ql,c.er=function(N,p,_,C,M){return ea((N-p)/(_-p)*(M-C)+C,C,M)},c.es=ce,c.et=gs,c.eu=function(N,p){var _=p[0],C=p[1],M=p[2],F=p[3],z=p[4],H=p[5],Y=p[6],se=p[7],me=p[8],xe=me*z-H*se,_e=-me*F+H*Y,Te=se*F-z*Y,De=_*xe+C*_e+M*Te;return De?(N[0]=xe*(De=1/De),N[1]=(-me*C+M*se)*De,N[2]=(H*C-M*z)*De,N[3]=_e*De,N[4]=(me*_-M*Y)*De,N[5]=(-H*_+M*F)*De,N[6]=Te*De,N[7]=(-se*_+C*Y)*De,N[8]=(z*_-C*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 _=Fdt(new xs(0,0),new xs(Pr,Pr),N),C=[];if(p&&!uOe(_,this._globalClipBounds))return C;for(const M of this._activeRegions){if(M.hiddenByOverlap||!uOe(_,M))continue;const F=Fhs(M.min,M.max,N);C.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 C}setSources(N){this._setSources(N.map(p=>({getSourceId:()=>p.cache.id,getFootprints:()=>{const _=[];for(const C of p.cache.getVisibleCoordinates()){const M=p.cache.getTile(C).buckets[p.layer];M&&M.updateFootprints(C.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(),C=N.getClipMask(),M=N.getClipScope();for(const F of p){if(!F.footprint)continue;const z=Fdt(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:C,clipScope:M})}this._sourceIds.push(N.getSourceId())}_computeReplacement(){this._activeRegions.sort((p,_)=>p.priority-_.priority||zoe(p.min,_.min)||zoe(p.max,_.max)||p.order-_.order||p.clipMask-_.clipMask||function(C,M){const F=(z,H)=>z+H;return C.length-M.length||C.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],C=this._prevRegions[p];N=_.priority!==C.priority||!Ddt(_,C)||_.order!==C.order||_.clipMask!==C.clipMask||!Tr(_.clipScope,C.clipScope),this._activeRegions[p].hiddenByOverlap=C.hiddenByOverlap,++p}}if(N){++this._updateTime;for(const _ of this._activeRegions)_.order!==TY&&(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 C=this._activeRegions;if(_>=C.length)return _;const M=C[_].priority;for(;_1){let _=0,C=p(_);for(;_!==C;){let M=_;const F=_;for(;M!==C;){const z=this._activeRegions[M];z.hiddenByOverlap=!1;for(let H=0;H=0;p--)this._addSource(N[p]);this._computeReplacement()}},c.ex=TY,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 Gs,C=new $r,M=[],F=N+1+2,z=p[0]+1,H=p[0]+1+(1+p.length),Y=(se,me,xe)=>{let _e=se===F-1?se-2:se===0?se:se-1;return _e+=xe?24575:0,[_e,me]};for(let se=0;se0&&DOe(p,N.layers[0].source,N.sourceLayerName);(C||M)&&(N.hdExt=new _ut(N,C,M))},c.fC=function(N,p){const _=N.layers[0].layout.get("line-elevation-reference")==="hd-road-markup",C=!!p&&p.length>0&&DOe(p,N.layers[0].source,N.sourceLayerName);(_||C)&&(N.hdExt=new wut(_,C))},c.fD=koe,c.fE=function(N){const p=N.layers[0];p.type==="circle"&&p.layout.get("circle-elevation-reference")==="hd-road-markup"&&(N.hdExt=new jut)},c.fF=function(N){N.layers[0].layout.get("symbol-elevation-reference")==="hd-road-markup"&&(N.hdExt=new Nut)},c.fG=hft,c.fH=function(N){let p=0;if(new Uint32Array(N,0,1)[0]!==Put){const _=new Uint32Array(N,0,7),[,,C,M,F,z]=_;p=_.byteLength+M+F+z+F,(C!==N.byteLength||p>=N.byteLength)&&Yo("Invalid b3dm header information.")}return Dut(N,p)},c.fI=function(N,p){const _=WOe(N);for(const C of _){if(!C.meshBVH)for(const M of C.meshes)qms(M);if(C.lights){let M=65535;for(const F of C.meshes)F.doorVertexColor!==void 0&&(M=F.doorVertexColor,C.lightsStyleAabb=F.aabb);C.lightMeshIndex=C.meshes.length,C.meshes.push(Vms(C.lights,p,M))}}return _},c.fJ=K,c.fK=xmt,c.fL=oa,c.fM=function(N,p){let _="";for(let C=0;C=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=Zw,c.fU=Zct,c.fV=F3,c.fW=function(N){for(const p of N)if(!Oe(p.charCodeAt(0)))return!1;return!0},c.fX=de,c.fY=JFe,c.fZ=mdt,c.f_=ydt,c.fa=Eo,c.fb=Cdt,c.fc=function(N){const p=[0,0,0],_=w(new Float64Array(16));return E(_,N.pixelMatrix,N.globeMatrix),Qe(p,p,_),new xs(p[0],p[1])},c.fd=function(N){Ia=N},c.fe=Jn,c.ff=jmt,c.fg=function(N,p){if(!N||!p)throw new Error("TileProvider name and URL are required");xt.TILE_PROVIDER_URLS[N]=ah.resolveURL(p)},c.fh=function(N){typeof N!="string"||N.length>64||!gi.test(N)?Yo(`Invalid SDK info "${N}"; expected a "Name/version" string. Ignoring.`):Ca=N},c.fi=xy,c.fj=function(N,p,_=!1){if(Mi===Or.deferred||Mi===Or.loading||Mi===Or.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");pl=ah.resolveURL(N),Mi=Or.deferred,ci=p,Hh(),_||U_()},c.fk=function(N){xt.BUILDING_GEN_URL=ah.resolveURL(N)},c.fl=Nt,c.fm=function(N){const p=ah.resolveURL(N);xt.MESHOPT_URL=p,xt.MESHOPT_SIMD_URL=p},c.fn=ct,c.fo=function(N){xt.DRACO_URL=ah.resolveURL(N)},c.fp=We,c.fq=function(N){const p=hn();if(!p)return;const _=p.delete(Wt);N&&_.then(()=>N()).catch(N)},c.fr=function(N){xt.MAX_PARALLEL_IMAGE_REQUESTS=N},c.fs=function(N){xt.API_URL=N},c.ft=function(N){xt.ACCESS_TOKEN=N},c.fu="hd_road_elevation",c.fv=class{static parseFrom(N,p){const _=V3.parse(N);if(!_)return[];let{vertices:C,features:M}=_;const F=1/K(p);M.sort((se,me)=>se.id-me.id),C.sort((se,me)=>se.id-me.id||se.idx-me.idx),C=C.filter((se,me,xe)=>me===xe.findIndex(_e=>_e.id===se.id&&_e.idx===se.idx));const z=new Array;let H=0;const Y=C.length;for(const se of M){if(se.constantHeight){z.push(new H3(se.id,se.bounds,se.constantHeight));continue}for(;H!==Y&&C[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 C,M;if(p>=0?(C=p%4294967296|0,M=p/4294967296|0):(C=~(-p%4294967296),M=~(-p/4294967296),4294967295^C?C=C+1|0:(C=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)}(C,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(C,M,F){for(let z,H,Y=0;Y55295&&z<57344){if(!H){z>56319||Y+1===M.length?(C[F++]=239,C[F++]=191,C[F++]=189):H=z;continue}if(z<56320){C[F++]=239,C[F++]=191,C[F++]=189,H=z;continue}z=H-55296<<10|z-56320|65536,H=null}else H&&(C[F++]=239,C[F++]=191,C[F++]=189,H=null);z<128?C[F++]=z:(z<2048?C[F++]=z>>6|192:(z<65536?C[F++]=z>>12|224:(C[F++]=z>>18|240,C[F++]=z>>12&63|128),C[F++]=z>>6&63|128),C[F++]=63&z|128)}return F}(this.buf,N,this.pos);const _=this.pos-p;_>=128&&Hdt(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 C=this.pos-_;C>=128&&Hdt(_,C,this),this.pos=_-1,this.writeVarint(C),this.pos+=C}writeMessage(N,p,_){this.writeTag(N,2),this.writeRawMessage(p,_)}writePackedVarint(N,p){p.length&&this.writeMessage(N,Ohs,p)}writePackedSVarint(N,p){p.length&&this.writeMessage(N,zhs,p)}writePackedBoolean(N,p){p.length&&this.writeMessage(N,Uhs,p)}writePackedFloat(N,p){p.length&&this.writeMessage(N,Bhs,p)}writePackedDouble(N,p){p.length&&this.writeMessage(N,$hs,p)}writePackedFixed32(N,p){p.length&&this.writeMessage(N,qhs,p)}writePackedSFixed32(N,p){p.length&&this.writeMessage(N,Vhs,p)}writePackedFixed64(N,p){p.length&&this.writeMessage(N,Hhs,p)}writePackedSFixed64(N,p){p.length&&this.writeMessage(N,Ghs,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=Yc,c.gr=Ooe,c.gs=Or,c.gt=fft,c.gu=function(N){fn(),Ms!=null&&Ms.then(p=>{p.keys().then(_=>{for(let C=0;C<_.length-N;C++)p.delete(_[C]).catch(M=>Yo(M.message))}).catch(_=>Yo(_.message))}).catch(p=>Yo(p.message))},c.h=zl,c.i=Ih,c.j=2,c.k=IY,c.l=Kw,c.m=z6,c.n=L1,c.o=Wy,c.p=Gdt,c.q=D_,c.r=Zy,c.s=Zs,c.t=Yy,c.u=N9,c.v=ej,c.w=Yo,c.x=$v,c.y=k9,c.z=H0}),i(["require","./shared"],function(o,c){function d(xt){const We=xt?xt.url.toString():void 0;return We?performance.getEntriesByName(We):[]}function u(xt,We){if(Object.hasOwn(xt.layers,c.fu))return c.fv.parseFrom(xt.layers[c.fu],We)}function h({buckets:xt,data:We,sourceLayerCoder:ct,canonical:Nt,options:Rt}){if(!Rt.elevationFeatures||Rt.elevationFeatures.length===0)return;const $t=[];for(const js of Object.values(xt))if(js instanceof c.bB&&js.hdExt){const Ts=js.hdExt.getUnevaluatedPortalGraph();Ts&&$t.push(Ts)}const Wt=c.fw.evaluate($t);for(const js of Object.values(xt))if(js instanceof c.bB&&js.hdExt){const Ts=We.layers[ct.decode(js.sourceLayerIndex)];js.hdExt.setEvaluatedPortalGraph(Wt,Ts,Nt,Rt.availableImages,Rt.brightness,js.worldview)}}function m(xt){const We=[];for(let ct=0;ct0){let Ts=!1;for(const Ns of Wt[0])if(Ns.x<0||Ns.x>c.a6||Ns.y<0||Ns.y>c.a6){Ts=!0;break}if(Ts)continue}const js=Wt.length===1&&Wt[0].length===5&&Wt[0].some(Ts=>Ts.x<=0&&Ts.y<=0)&&Wt[0].some(Ts=>Ts.x>=c.a6&&Ts.y<=0)&&Wt[0].some(Ts=>Ts.x>=c.a6&&Ts.y>=c.a6)&&Wt[0].some(Ts=>Ts.x<=0&&Ts.y>=c.a6);We.push(new c.fx($t,js?[]:Wt))}return We}function f(xt,We,ct,Nt,Rt){const $t=c.fy(We);if($t===null)return!1;let Wt=ct.x,js=ct.y;const Ts=Rt??Nt.z;if(Nt.z!==Ts){const Ns=1<hn.map(fn=>[fn.x,fn.y]));if(c.fz([Wt,js],Ms))return!0}return!1}function g(xt,We,ct,Nt){const Rt=We.indoorState.activeFloorsVisible;if(!We.sourceLayers)return Rt?We.indoorState.activeFloors:void 0;const $t=function(Ts,Ns){if(!Ts)return c.w("No source layers defined in indoor specification"),Ns;if(Ts.size===0)return Ns;const Ms=Ts.difference(Ns);for(const hn of Ms)c.w(`Missing source layer required in indoor specification: ${hn}`);return Ns.intersection(Ns)}(We.sourceLayers,new Set(Object.keys(xt.layers))),Wt=We.indoorState,js=function(Ts,Ns,Ms,hn,fn){const gn={};for(const Mn of Ns){const ar=Ts.layers[Mn];if(ar)for(let Jn=0;JnMn.map(ar=>c.fA(ar,hn,Ms.extent)));return gn.length===0?void 0:{type:"Polygon",coordinates:[gn[0]]}}(xt,We);return{id:ct,isDefault:Nt,connections:Rt,conflicts:$t,buildings:Wt,name:js,zIndex:Ts,geometry:Ns}}function w(xt,We){return We.every(ct=>xt.properties&&xt.properties[ct]!=null)}function S(xt){return w(xt,["type","id","name"])&&xt.properties.type==="structure"}function A(xt){return w(xt,["type","id","name","z_index"])&&xt.properties.type==="floor"}function E(xt,We){xt instanceof c.bB?c.fB(xt,We):xt instanceof c.bA?c.fC(xt,We):xt instanceof c.fD?c.fE(xt):xt instanceof c.bv&&c.fF(xt)}function I(xt){for(const We in xt){const ct=xt[We];if(ct instanceof c.bA&&ct.hdExt&&ct.hdExt.hasDeferredElevationFeatures||ct instanceof c.bv&&ct.hdExt&&ct.hdExt.hasDeferredElevationFeatures)return!0}return!1}class P{constructor(We,ct,Nt){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=ct,this.worldview=Nt}async parse(We,ct,Nt){this.status="parsing";const Rt=new c.bQ(Nt.tileID.overscaledZ,Nt.tileID.wrap,Nt.tileID.canonical.z,Nt.tileID.canonical.x,Nt.tileID.canonical.y),$t=[],Wt=ct.familiesBySource[Nt.source],js=new c.fG(Rt,Nt.promoteId);js.bucketLayerIDs=[],js.is3DTile=!0;const Ts=await c.fH(We),Ns=Ts.json.extensionsUsed&&Ts.json.extensionsUsed.includes("MAPBOX_mesh_features")||Ts.json.asset.extras&&Ts.json.asset.extras.MAPBOX_mesh_features,Ms=Ts.json.extensionsUsed&&Ts.json.extensionsUsed.includes("EXT_meshopt_compression"),hn=new c.aj(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const fn in Wt)for(const gn of Wt[fn]){const Mn=gn[0];js.bucketLayerIDs.push(gn.map(er=>c.m(er.id,er.scope))),Mn.recalculate(hn,[]);const ar=c.fI(Ts,1/c.fJ(Nt.tileID.canonical)),Jn=new c.fK(gn,ar,Rt,Ns,Ms,this.brightness,js,this.worldview);$t.push(Jn),Jn.evaluate(Mn)}return this.status="done",{buckets:$t,featureIndex:js,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null}}}class R{constructor({actor:We,layerIndex:ct,availableImages:Nt,availableModels:Rt,brightness:$t,worldview:Wt}){this.actor=We,this.layerIndex=ct,this.availableImages=Nt,this.availableModels=Rt,this.brightness=$t,this.loading={},this.loaded={},this.worldview=Wt}async loadTile(We){const ct=We.uid,Nt=new AbortController,Rt=this.loading[ct]=new P(We,this.brightness,this.worldview);Rt.abort=()=>Nt.abort();const $t=(js,Ts)=>{const Ns=Rt.reloadCallback;Ns&&(delete Rt.reloadCallback,Ns(js,Ts))};let Wt;try{Wt=(await c.d0(We.request,Nt.signal)).data}catch(js){if(delete this.loading[ct],Rt.status="done",this.loaded[ct]=Rt,Nt.signal.aborted)return null;throw js}if(delete this.loading[ct],!Wt||Wt.byteLength===0)return Rt.status="done",this.loaded[ct]=Rt,null;try{const js=await Rt.parse(Wt,this.layerIndex,We);return this.loaded[ct]=Rt,$t(null,js),js}catch(js){throw this.loaded[ct]=Rt,$t(js),js}}async reloadTile(We){const ct=this.loaded&&this.loaded[We.uid];if(ct)return ct.projection=We.projection,ct.brightness=We.brightness,ct.status==="parsing"&&await new Promise((Nt,Rt)=>{ct.reloadCallback=$t=>{$t?Rt($t):Nt()}}),this.loadTile(We)}abortTile(We){const ct=We.uid,Nt=this.loading[ct];Nt&&(Nt.abort&&Nt.abort(),delete this.loading[ct])}removeTile(We){const ct=this.loaded,Nt=We.uid;ct&&ct[Nt]&&delete ct[Nt]}}function D(xt){if(typeof xt=="number"||typeof xt=="boolean"||typeof xt=="string"||xt==null)return JSON.stringify(xt);if(Array.isArray(xt)){let ct="[";for(const Nt of xt)ct+=`${D(Nt)},`;return`${ct}]`}let We="{";for(const ct of Object.keys(xt).sort())We+=`${ct}:${D(xt[ct])},`;return`${We}}`}function O(xt){let We="";for(const ct of c.d1)We+=`/${D(xt[ct])}`;return We}function U(xt,We){return function ct(Nt){return typeof Nt=="string"&&Nt===We||(Array.isArray(Nt)?Nt.some(ct):!(!Nt||typeof Nt!="object")&&Object.values(Nt).some(ct))}(xt)}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,ct){this._layerConfigs=Object.create(null),this._layers=Object.create(null),this.update(We,[],ct)}update(We,ct,Nt){this._options=Nt;for(const $t of We)this._layerConfigs[$t.id]=$t,(this._layers[$t.id]=c.dM($t,this.scope,null,this._options)).compileFilter(Nt),this.keyCache[$t.id]&&delete this.keyCache[$t.id];for(const $t of ct)delete this.keyCache[$t],delete this._layerConfigs[$t],delete this._layers[$t];this.familiesBySource=Object.create(null);const Rt=function($t,Wt){const js=Object.create(null);for(let Ns=0;Ns<$t.length;Ns++){const Ms=$t[Ns];let hn=Wt&&Wt[Ms.id];hn||(Ms.type==="symbol"?hn=Ms.id:(hn=O(Ms),Ms.type==="line"&&Ms.paint&&(U(Ms.paint["line-width"],"line-progress")&&(hn+=`/${D(Ms.paint["line-width"])}`),U(Ms.paint["line-emissive-strength"],"line-progress")&&(hn+=`/${D(Ms.paint["line-emissive-strength"])}`)))),Wt&&(Wt[Ms.id]=hn);let fn=js[hn];fn||(fn=js[hn]=[]),fn.push(Ms)}const Ts=[];for(const Ns in js)Ts.push(js[Ns]);return Ts}(Object.values(this._layerConfigs),this.keyCache);for(const $t of Rt){const Wt=$t.map(fn=>this._layers[fn.id]),js=Wt[0];if(js.visibility==="none")continue;const Ts=js.source||"";let Ns=this.familiesBySource[Ts];Ns||(Ns=this.familiesBySource[Ts]=Object.create(null));const Ms=js.sourceLayer||"_geojsonTileLayer";let hn=Ns[Ms];hn||(hn=Ns[Ms]=[]),hn.push(Wt)}}}class V extends c.P{constructor(We,ct,Nt,Rt,$t){super(We,ct),this.angle=Rt,this.z=Nt,$t!==void 0&&(this.segment=$t)}clone(){return new V(this.x,this.y,this.z,this.angle,this.segment)}}function G(xt,We,ct,Nt,Rt){if(We.segment===void 0)return!0;let $t=We,Wt=We.segment+1,js=0;for(;js>-ct/2;){if(Wt--,Wt<0)return!1;js-=xt[Wt].dist($t),$t=xt[Wt]}js+=xt[Wt].dist(xt[Wt+1]),Wt++;const Ts=[];let Ns=0;for(;jsNt;)Ns-=Ts.shift().angleDelta;if(Ns>Rt)return!1;Wt++,js+=Ms.dist(hn)}return!0}function Z(xt){let We=0;for(let ct=0;ctNs){const Mn=(Ns-Ts)/gn,ar=c.am(hn.x,fn.x,Mn),Jn=c.am(hn.y,fn.y,Mn),er=new V(ar,Jn,0,fn.angleTo(hn),Ms);return!Wt||G(xt,er,js,Wt,We)?er:void 0}Ts+=gn}}function re(xt,We,ct,Nt,Rt,$t,Wt,js,Ts){const Ns=X(Nt,$t,Wt),Ms=ae(Nt,Rt),hn=Ms*Wt,fn=xt[0].x===0||xt[0].x===Ts||xt[0].y===0||xt[0].y===Ts;return We-hn=0&&qa=0&&et=0&&fn+Ns<=Ms){const Gt=new V(qa,et,0,xr,Mn);Nt&&!G(xt,Gt,$t,Nt,Rt)||gn.push(Gt)}}hn+=er}return js||gn.length||Wt||(gn=te(xt,hn/2,ct,Nt,Rt,$t,Wt,!0,Ts)),gn}c.fL(V,"Anchor");class J{constructor(){this.scale=1,this.fontStack="",this.image=null}static forText(We,ct){const Nt=new J;return Nt.scale=We||1,Nt.fontStack=ct,Nt}static forImage(We){const ct=new J;return ct.image=We,ct}}class ce{constructor(){this.text="",this.sectionIndex=[],this.sections=[],this.imageSectionID=null}static fromFeature(We,ct,Nt,Rt=1){const $t=new ce;for(let Wt=0;Wt=0&&Nt>=We&&ue[this.text.charCodeAt(Nt)];Nt--)ct--;this.text=this.text.substring(We,ct),this.sectionIndex=this.sectionIndex.slice(We,ct)}substring(We,ct){const Nt=new ce;return Nt.text=this.text.substring(We,ct),Nt.sectionIndex=this.sectionIndex.slice(We,ct),Nt.sections=this.sections,Nt}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((We,ct)=>Math.max(We,this.sections[ct].scale),0)}addTextSection(We,ct){this.text+=We.text,this.sections.push(J.forText(We.scale,We.fontStack||ct));const Nt=this.sections.length-1;for(let Rt=0;Rt=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function ve(xt,We){if(!xt.image)return!1;const ct=We.get(xt.image.toString());return!!ct&&ct.sdf}function fe(xt,We,ct,Nt,Rt,$t,Wt,js,Ts,Ns,Ms,hn,fn,gn,Mn,ar=1,Jn=1){const er=ce.fromFeature(xt,Rt,ar,Jn);hn===c.dt.vertical&&er.verticalizePunctuation(fn);const xr=er.toString();if(function(en,tr){const sr=en.sections.findIndex(Na=>ve(Na,tr));if(sr===-1)return;c.w(`SDF image ${en.sections[sr].image.id.name} is not supported in text-field`);const Xr=en.sections.map(Na=>ve(Na,tr));let sa="";const $a=[];for(let Na=0;Na0&&ou>zo&&(zo=ou)}else{const dd=sr[Ad.fontStack];if(!dd)continue;dd[Zc]&&(Pf=dd[Zc]);const zl=tr[Ad.fontStack];if(!zl)continue;const Xi=zl.glyphs[Zc];if(!Xi)continue;if(ih=Xi.metrics,ad=Zc!==8203?c.dg:0,au){const Ed=zl.ascender!==void 0?Math.abs(zl.ascender):0,ou=zl.descender!==void 0?Math.abs(zl.descender):0,Xc=(Ed+ou)*rd;Pc$t)&&($t=Mn.x),(!gn||Mn.y>Wt)&&(Wt=Mn.y)}const Ts=Math.min($t-Nt,Wt-Rt);let Ns=Ts/2;const Ms=new c.fT([],Ae);if(Ts===0)return new c.P(Nt,Rt);for(let gn=Nt;gn<$t;gn+=Ts)for(let Mn=Rt;Mnhn.d||!hn.d)&&(hn=gn,ct&&console.log("found best %d after %d probes",Math.round(1e4*gn.d)/1e4,fn)),gn.max-hn.d<=We||(Ns=gn.h/2,Ms.push(new Ce(gn.p.x-Ns,gn.p.y-Ns,Ns,xt)),Ms.push(new Ce(gn.p.x+Ns,gn.p.y-Ns,Ns,xt)),Ms.push(new Ce(gn.p.x-Ns,gn.p.y+Ns,Ns,xt)),Ms.push(new Ce(gn.p.x+Ns,gn.p.y+Ns,Ns,xt)),fn+=4)}return ct&&(console.log(`num probes: ${fn}`),console.log(`best distance: ${hn.d}`)),hn.p}function Ae(xt,We){return We.max-xt.max}class Ce{constructor(We,ct,Nt,Rt){this.p=new c.P(We,ct),this.h=Nt,this.d=function($t,Wt){let js=!1,Ts=1/0;for(let Ns=0;Ns$t.y!=ar.y>$t.y&&$t.x<(ar.x-Mn.x)*($t.y-Mn.y)/(ar.y-Mn.y)+Mn.x&&(js=!js),Ts=Math.min(Ts,c.fU($t,Mn,ar))}}return(js?1:-1)*Math.sqrt(Ts)}(this.p,Rt),this.max=this.d+this.h*Math.SQRT2}}const qe=Object.keys;function ze(xt){return xt.imagePrimary!==void 0&&xt.top!==void 0&&xt.bottom!==void 0&&xt.left!==void 0&&xt.right!==void 0}function Ve(xt){return!xt.imagePrimary.stretchX}function ht(xt){return!xt.imagePrimary.stretchY}function Qe(xt){return{width:xt.right-xt.left,height:xt.bottom-xt.top}}const at=Number.POSITIVE_INFINITY;function rt(xt,We,ct,Nt,Rt,$t){const Wt=ze(xt)&&xt.collisionPadding?xt.collisionPadding:[0,0,0,0],js={top:xt.top-Wt[1],bottom:xt.bottom+Wt[3],left:xt.left-Wt[0],right:xt.right+Wt[2],scaled:!1};return Nt!==void 0&&function(Ts,Ns){Ts.top*=Ns,Ts.bottom*=Ns,Ts.left*=Ns,Ts.right*=Ns,Ts.scaled=!0}(js,Nt),$t&&(js.left+=$t[0],js.right+=$t[0],js.top+=$t[1],js.bottom+=$t[1]),ct&&function(Ts,Ns,Ms){if(!Ns)return;const hn=c.av(Ns),fn=new c.P(Ms?Ms[0]:0,Ms?Ms[1]:0),gn=new c.P(Ts.left,Ts.top),Mn=new c.P(Ts.right,Ts.top),ar=new c.P(Ts.left,Ts.bottom),Jn=new c.P(Ts.right,Ts.bottom);gn._rotateAround(hn,fn),Mn._rotateAround(hn,fn),ar._rotateAround(hn,fn),Jn._rotateAround(hn,fn),Ts.left=Math.min(gn.x,Mn.x,ar.x,Jn.x),Ts.right=Math.max(gn.x,Mn.x,ar.x,Jn.x),Ts.top=Math.min(gn.y,Mn.y,ar.y,Jn.y),Ts.bottom=Math.max(gn.y,Mn.y,ar.y,Jn.y)}(js,ct,Rt),We?{top:Math.min(We.top,js.top),bottom:Math.max(We.bottom,js.bottom),left:Math.min(We.left,js.left),right:Math.max(We.right,js.right),scaled:We.scaled||js.scaled}:js}function Ke(xt,We,ct,Nt,Rt,$t,Wt,js=1,Ts,Ns,Ms,hn,fn,gn,Mn,ar,Jn){xt.createArrays(),xt.tilePixelRatio=c.a6/(512*xt.overscaling),xt.compareText={},xt.iconsNeedLinear=!1;const er=xt.layers[0].layout,xr=xt.layers[0]._unevaluatedLayout._values,gr={};gr.scaleFactor=js,gr.textSizeScaleRange=er.get("text-size-scale-range"),gr.iconSizeScaleRange=er.get("icon-size-scale-range");const[qa,et]=gr.textSizeScaleRange,[Gt,Es]=gr.iconSizeScaleRange;gr.textScaleFactor=c.b1(gr.scaleFactor,qa,et),gr.iconScaleFactor=c.b1(gr.scaleFactor,Gt,Es);const on=xr["text-size"],en=xr["icon-size"];if(xt.textSizeData.kind==="composite"){const{minZoom:La,maxZoom:eo}=xt.textSizeData;gr.compositeTextSizes=[on.possiblyEvaluate(new c.aj(La,{worldview:Ms}),$t),on.possiblyEvaluate(new c.aj(eo,{worldview:Ms}),$t)]}if(xt.iconSizeData.kind==="composite"){const{minZoom:La,maxZoom:eo}=xt.iconSizeData;gr.compositeIconSizes=[en.possiblyEvaluate(new c.aj(La,{worldview:Ms}),$t,hn),en.possiblyEvaluate(new c.aj(eo,{worldview:Ms}),$t,hn)]}gr.layoutTextSize=on.possiblyEvaluate(new c.aj(Wt+1,{worldview:Ms}),$t),gr.layoutIconSize=en.possiblyEvaluate(new c.aj(Wt+1,{worldview:Ms}),$t,hn),gr.textMaxSize=on.possiblyEvaluate(new c.aj(18,{worldview:Ms}),$t);const tr=er.get("symbol-placement"),sr=er.get("text-rotation-alignment")==="map"&&tr!=="point",Xr=er.get("text-size");let sa=!1;const $a=[],Na=fn!=null&&fn!==0;for(const La of xt.features){if(Na&&La.properties&&ar&&ar(La.properties,fn))continue;let eo=65535;if(xt.hdExt&&La.properties&&Object.hasOwn(La.properties,c.fV)){const fu=+La.properties[c.fV];if(!Number.isNaN(fu)){const Zc=xt.hdExt.resolveRoadElevation(La,fu);if(Zc==="defer")continue;eo=Zc}}const xo=er.get("text-font").evaluate(La,{},$t).join(","),io=Xr.evaluate(La,{},$t)*gr.textScaleFactor,Lo=gr.layoutTextSize.evaluate(La,{},$t)*gr.textScaleFactor,Ul=gr.layoutIconSize.evaluate(La,{},$t,hn)*gr.iconScaleFactor,fo={horizontal:{},vertical:void 0},nl=La.text;let Pl,Cd=[0,0];if(nl){const fu=nl.toString(),Zc=er.get("text-letter-spacing").evaluate(La,{},$t)*c.dg,rd=er.get("text-line-height").evaluate(La,{},$t)*c.dg,ih=c.fW(fu)?Zc:0,Pf=er.get("text-anchor").evaluate(La,{},$t),Od=er.get("text-variable-anchor");if(!Od){const dd=er.get("text-radial-offset").evaluate(La,{},$t);if(dd)Cd=c.dv(Pf,[dd*c.dg,at]);else{const zl=er.get("text-offset").evaluate(La,{},$t);Cd=[zl[0]*c.dg,zl[1]*c.dg]}}let ad=sr?"center":er.get("text-justify").evaluate(La,{},$t);const Ph=tr==="point",Hu=Ph?er.get("text-max-width").evaluate(La,{},$t)*c.dg:1/0,zd=dd=>{xt.allowVerticalPlacement&&c.fX(fu)&&(fo.vertical=fe(nl,We,ct,Rt,xo,Hu,rd,Pf,dd,ih,Cd,c.dt.vertical,!0,Lo,io,Ts,gr.textScaleFactor))};if(!sr&&Od){const dd=ad==="auto"?Od.map(Xi=>c.dw(Xi)):[ad];let zl=!1;for(let Xi=0;Xi0?er/Ts:1;xr&&(xt.iconBBox=rt(xr,xt.iconBBox,Jn,et!==1?et:void 0)),gr&&(xt.iconVerticalBBox=rt(gr,xt.iconVerticalBBox,Jn+90,et!==1?et:void 0))}function gt(xt,We,ct,Nt,Rt,$t,Wt,js){let Ts=null;const Ns=We.getAppearanceValueAndResolveTokens(ct,"icon-image",Nt,Rt,js);if(Ns){const Ms=xt.getResolvedImageFromTokens(Ns),hn=ct.hasLayoutProperty("icon-size")?ct.getUnevaluatedLayoutProperty("icon-size"):We._unevaluatedLayout._values["icon-size"],fn=c.g5(xt.zoom,hn,xt.worldview,js),gn=c.fY(Ms,fn,hn,Rt,xt.zoom,Nt,xt.pixelRatio,Wt,xt.worldview,js);Ts=$t.get(gn.iconPrimary.toString())}return Ts}function es(xt,We,ct,Nt,Rt,$t,Wt,js,Ts,Ns){const{appearanceTextOffset:Ms,appearanceTextRotate:hn,appearanceTextSize:fn}=c.g3(ct,We,Nt,Rt,$t,Wt,js),gn=fn/js,Mn=[(Ms[0]-$t[0])*gn,(Ms[1]-$t[1])*gn],ar=Mn[0]!==0||Mn[1]!==0;Ts&&(xt.textBBox=rt(Ts,xt.textBBox,hn,gn,Ms,ar?Mn:void 0)),Ns&&(xt.textVerticalBBox=rt(Ns,xt.textVerticalBBox,hn+90,gn,Ms,ar?Mn:void 0))}function Ht(xt,We,ct,Nt,Rt,$t,Wt,js){if(!xt||!xt.usvg)return;const Ts=Qe(ct),Ns=Qe(Nt),Ms=Rt!=="both"&&Rt!=="width"||!Ve(ct)?1:Ns.width/Ts.width,hn=Rt!=="both"&&Rt!=="height"||!ht(ct)?1:Ns.height/Ts.height;We.scaleSelf(Ms,hn);const fn=We.toString();$t.set(fn,We),Wt.set(fn,xt);const{imagePosition:gn}=c.g0(fn,xt,c.g1);js.set(fn,gn)}function as(xt,We,ct){if(!We)return;const Nt=ct.get(xt.toString()),Rt=ct.get(We.toString());Nt&&Rt&&(Nt.paddedRect.w===Rt.paddedRect.w&&Nt.paddedRect.h===Rt.paddedRect.h||c.w(`Mismatch in icon variant sizes: ${xt.toString()} and ${We.toString()}`),Nt.usvg!==Rt.usvg&&c.w(`Mismatch in icon variant image types: ${xt.id} and ${We.id}`))}function bs(xt,We,ct,Nt,Rt,$t,Wt,js,Ts,Ns){xt.iconAtlasPositions=Ns.iconPositions;const{featureData:Ms,sizes:hn,textAlongLine:fn,symbolPlacement:gn,coveragePolygons:Mn,coverageTileZoom:ar,symbolAnchorInFrcCoverage:Jn}=We,er=We.hasAnySecondaryIcon||xt.hasAnySecondaryIcon;for(const xr of Ms){const{shapedIcon:gr,verticallyShapedIcon:qa,feature:et,shapedTextOrientations:Gt,shapedText:Es,layoutTextSize:on,textOffset:en,isSDFIcon:tr,iconPrimary:sr,iconSecondary:Xr,iconTextFit:sa,iconOffset:$a,iconCollisionBounds:Na,iconVerticalCollisionBounds:La,textCollisionBounds:eo,elevationFeatureIndex:xo}=xr;Ut(gr,Ns.iconPositions,sr,Xr),Ut(qa,Ns.iconPositions,sr,Xr),Ft(Gt,Ns.iconPositions),as(sr,Xr,Ns.iconPositions),(Es||gr)&&zs(xt,et,Gt,gr,qa,Ts,hn,on,0,en,tr,Nt,Rt,Wt,js,er,sa,$a,fn,gn,Na,La,eo,0,0,Mn,ar,Jn,xo)}ct&&xt.generateCollisionDebugBuffers($t,xt.collisionBoxArray,hn.textScaleFactor),xt.text.uboBinder&&xt.text.uboBinder.finalize(),xt.icon.uboBinder&&xt.icon.uboBinder.finalize()}function Ut(xt,We,ct,Nt){if(!xt)return;const Rt=We.get(ct.toString());if(Rt&&(xt.imagePrimary=Rt),Nt){const $t=We.get(Nt.toString());xt.imageSecondary=$t}}function Ft(xt,We){for(const ct in xt.horizontal)is(xt.horizontal[ct],We);is(xt.vertical,We)}function is(xt,We){if(xt){for(const ct of xt.positionedLines)for(const Nt of ct.positionedGlyphs)if(Nt.image!==null){const Rt=Nt.image.toString();Nt.rect=We.get(Rt).paddedRect}}}function jt(xt,We,ct,Nt,Rt,$t,Wt,js,Ts){const Ns=gs($t.horizontal)||$t.vertical,Ms=ct.get("icon-text-fit-padding").evaluate(Nt,{},Rt);let hn,fn=We;return We&&Ts!=="none"&&(xt.allowVerticalPlacement&&$t.vertical&&(hn=c.f$(We,$t.vertical,Ts,Ms,js,Wt)),Ns&&(fn=c.f$(We,Ns,Ts,Ms,js,Wt))),{defaultShapedIcon:fn,verticallyShapedIcon:hn}}function zs(xt,We,ct,Nt,Rt,$t,Wt,js,Ts,Ns,Ms,hn,fn,gn,Mn,ar,Jn,er,xr,gr,qa,et,Gt,Es,on,en,tr,sr,Xr=65535){let sa=Wt.textMaxSize.evaluate(We,{},fn);sa===void 0?sa=js*Wt.textScaleFactor:sa*=Wt.textScaleFactor;const $a=xt.layers[0].layout,Na=c.dg,La=c.f_(js,Wt.textScaleFactor),eo=gs(ct.horizontal)||ct.vertical,xo=xt.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),io=xt.getAppearanceFeatureData(We.index);(Jn!=="none"||xo)&&io&&(io.textShaping=eo,io.iconTextFitPadding=$a.get("icon-text-fit-padding").evaluate(We,{},fn),io.fontScale=La,io.textScaleFactor=Wt.textScaleFactor);const Lo=gn.name==="globe",Ul=xt.tilePixelRatio*sa/Na,fo=(Nn=xt.overscaling,xt.zoom>18&&Nn>2&&(Nn>>=1),Math.max(c.a6/(512*Nn),1)*$a.get("symbol-spacing")),nl=$a.get("text-padding")*xt.tilePixelRatio,Pl=$a.get("icon-padding")*xt.tilePixelRatio,Cd=c.av($a.get("text-max-angle")),au=$a.get("icon-rotation-alignment")==="map"&&gr!=="point",Vt=fo/2;var Nn;xt.hasAnyIconTextFit===!1&&Jn!=="none"&&(xt.hasAnyIconTextFit=!0);const nr=(na,Wr,Ca)=>{if(Wr.x<0||Wr.x>=c.a6||Wr.y<0||Wr.y>=c.a6||en&&en.length>0&&We.properties&&sr&&sr(en,We.properties,Wr,fn,tr))return;let gi=null;if(Lo){const{x:Ia,y:el,z:zo}=gn.projectTilePoint(Wr.x,Wr.y,Ca);gi={anchor:new V(Ia,el,zo,0,void 0),up:gn.upVector(Ca,Wr.x,Wr.y)}}(function(Ia,el,zo,Pc,Eu,iu,dm,Ad,fu,Zc,rd,ih,Pf,Od,ad,Ph,Hu,zd,dd,zl,Xi,Ed,ou,Xc,vd,Ap,Dv,Px,ya,Ky,Ci,Wg){const Om=Ia.addToLineVertexArray(el,Pc);let Ix,Gu,kc,Ro,kl,pu,da,Ao=0,fl=0,Qc=0,ng=0,Wo=-1,B0=-1;const xh={};let df=c.dF("");const Bd=zo?zo.anchor:el,gu=Px!=="none";let R_=0,Fv=0;if(fu._unevaluatedLayout.getValue("text-radial-offset")===void 0){const zm=fu.layout.get("text-offset").evaluate(Xi,{},vd);R_=zm[0]*c.dg,Fv=zm[1]*c.dg}else R_=fu.layout.get("text-radial-offset").evaluate(Xi,{},vd)*c.dg,Fv=at;if(Ia.allowVerticalPlacement&&Eu.vertical){const zm=Eu.vertical;if(ad)pu=Ds(zm),Ad&&(da=Ds(Ad));else{const xu=fu.layout.get("text-rotate").evaluate(Xi,{},vd)+90;kc=Ss(Zc,Bd,el,rd,ih,Pf,zm,Od,xu,Ph,Wg),Ad&&(Ro=Ss(Zc,Bd,el,rd,ih,Pf,Ad,zd,xu,null,Ci))}}if(iu){const zm=fu.layout.get("icon-rotate").evaluate(Xi,{},vd),xu=c.g6(iu,zm,ou,gu,Ed.iconScaleFactor),Ih=Ad?c.g6(Ad,zm,ou,gu,Ed.iconScaleFactor):void 0;Gu=Ss(Zc,Bd,el,rd,ih,Pf,iu,zd,zm,null,Ky);const yh=function(Kg,lh,Ic,Yg,P1,I1,L1,Kw,Yw){const D_=Kg.layers[0],Mk=D_.appearances;let Pb=lh.length;if(Ic&&(Pb=Math.max(Pb,Ic.length)),Mk.length===0)return Pb;const[Ov,N3]=Yg.get("icon-size-scale-range"),U2=c.b1(1,Ov,N3);for(const np of Mk)if(np.hasLayoutProperty("icon-image")){const Pk=gt(Kg,D_,np,P1,I1,L1,U2,Yw);Pk&&(Pb=Math.max(Pb,c.g8(Pk)))}return Pb}(Ia,xu,Ih,fu.layout,Xi,vd,Ia.iconAtlasPositions,0,Xc);Ao=4*yh;const Ui=fu.layout.get("icon-size").evaluate(Xi,{},vd,Xc),um=Ed.compositeIconSizes?Ed.compositeIconSizes[0].evaluate(Xi,{},vd,Xc):0,oh=Ed.compositeIconSizes?Ed.compositeIconSizes[1].evaluate(Xi,{},vd,Xc):0,sp=c.g7(Ia.layerIds[0],Ia.iconSizeData,Ui,iu.imagePrimary.usvg?1:Ed.iconScaleFactor,um,oh);Ia.addSymbols(Ia.icon,xu,sp,zl,dd,Xi,void 0,zo,el,Om.lineStartIndex,Om.lineLength,-1,Xc,vd,Ap,Dv,Ia.symbolInstances.length,yh),Wo=Ia.icon.placedSymbolArray.length-1,Ih&&(fl=4*yh,Ia.addSymbols(Ia.icon,Ih,sp,zl,dd,Xi,c.dt.vertical,zo,el,Om.lineStartIndex,Om.lineLength,-1,Xc,vd,Ap,Dv,Ia.symbolInstances.length,yh),B0=Ia.icon.placedSymbolArray.length-1)}for(const zm in Eu.horizontal){const xu=zm,Ih=Eu.horizontal[xu];Ix||(df=c.dF(Ih.text),ad?kl=Ds(Ih):Ix=Ss(Zc,Bd,el,rd,ih,Pf,Ih,Od,fu.layout.get("text-rotate").evaluate(Xi,{},vd),Ph,Wg));const yh=Ih.positionedLines.length===1;if(Qc+=yt(Ia,zo,el,Ih,dm,fu,ad,Xi,Ph,Om,Eu.vertical?c.dt.horizontal:c.dt.horizontalOnly,yh?qe(Eu.horizontal):[xu],xh,Wo,Ed,Xc,vd,Ia.symbolInstances.length,Ap),yh)break}Eu.vertical&&(ng+=yt(Ia,zo,el,Eu.vertical,dm,fu,ad,Xi,Ph,Om,c.dt.vertical,["vertical"],xh,B0,Ed,Xc,vd,Ia.symbolInstances.length,Ap));let Lx=-1;const Mb=(zm,xu)=>zm?Math.max(zm,xu):xu;Lx=Mb(kl,Lx),Lx=Mb(pu,Lx),Lx=Mb(da,Lx);const Ww=Lx>-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,Bd.x,Bd.y,Bd.z,xh.right>=0?xh.right:-1,xh.center>=0?xh.center:-1,xh.left>=0?xh.left:-1,xh.vertical>=0?xh.vertical:-1,Wo,B0,df,Ix!==void 0?Ix:Ia.collisionBoxArray.length,Ix!==void 0?Ix+1:Ia.collisionBoxArray.length,kc!==void 0?kc:Ia.collisionBoxArray.length,kc!==void 0?kc+1:Ia.collisionBoxArray.length,Gu!==void 0?Gu:Ia.collisionBoxArray.length,Gu!==void 0?Gu+1:Ia.collisionBoxArray.length,Ro||Ia.collisionBoxArray.length,Ro?Ro+1:Ia.collisionBoxArray.length,rd,Qc,ng,Ao,fl,Ww,0,R_,Fv,Lx,0,gu?1:0,ya)})(xt,Wr,gi,na,ct,Nt,$t,Rt,xt.layers[0],xt.collisionBoxArray,We.index,We.sourceLayerIndex,xt.index,nl,xr,Ns,0,Pl,au,er,We,Wt,Ms,hn,fn,Mn,ar,Jn,Xr,qa,et,Gt)};if(gr==="line")for(const na of c.dc(We.geometry,0,0,c.a6,c.a6)){const Wr=re(na,fo,Cd,ct.vertical||eo,Nt,Na,Ul,xt.overscaling,c.a6);for(const Ca of Wr)eo&&Bt(xt,eo.text,Vt,Ca)||nr(na,Ca,fn)}else if(gr==="line-center"){for(const na of We.geometry)if(na.length>1){const Wr=le(na,Cd,ct.vertical||eo,Nt,Na,Ul);Wr&&nr(na,Wr,fn)}}else if(We.type==="Polygon")for(const na of c.g4(We.geometry,0)){const Wr=Se(na,16);nr(na[0],new V(Wr.x,Wr.y,0,0,void 0),fn)}else if(We.type==="LineString")for(const na of We.geometry)nr(na,new V(na[0].x,na[0].y,0,0,void 0),fn);else if(We.type==="Point")for(const na of We.geometry)for(const Wr of na)nr([Wr],new V(Wr.x,Wr.y,0,0,void 0),fn)}function yt(xt,We,ct,Nt,Rt,$t,Wt,js,Ts,Ns,Ms,hn,fn,gn,Mn,ar,Jn,er,xr){const gr=c.g9(ct,Nt,Ts,$t,Wt,js,Rt,xt.allowVerticalPlacement,void 0,Mn.textScaleFactor),qa=$t.layout.get("text-size").evaluate(js,{},Jn),et=Mn.compositeTextSizes?Mn.compositeTextSizes[0].evaluate(js,{},Jn):0,Gt=Mn.compositeTextSizes?Mn.compositeTextSizes[1].evaluate(js,{},Jn):0,Es=c.g7(xt.layerIds[0],xt.textSizeData,qa,Mn.textScaleFactor,et,Gt);xt.addSymbols(xt.text,gr,Es,Ts,Wt,js,Ms,We,ct,Ns.lineStartIndex,Ns.lineLength,gn,ar,Jn,xr,!1,er,gr.length);for(const on of hn)fn[on]=xt.text.placedSymbolArray.length-1;return 4*gr.length}function gs(xt){for(const We in xt)return xt[We];return null}function Ss(xt,We,ct,Nt,Rt,$t,Wt,js,Ts,Ns,Ms){let hn,fn,gn,Mn;if(hn=Ms?Ms.top:Wt.top,fn=Ms?Ms.bottom:Wt.bottom,gn=Ms?Ms.left:Wt.left,Mn=Ms?Ms.right:Wt.right,ze(Wt)&&Wt.collisionPadding){const ar=Wt.collisionPadding;gn-=ar[0],hn-=ar[1],Mn+=ar[2],fn+=ar[3]}if(Ts){const ar=new c.P(gn,hn),Jn=new c.P(Mn,hn),er=new c.P(gn,fn),xr=new c.P(Mn,fn),gr=c.av(Ts);let qa=new c.P(0,0);Ns&&(qa=new c.P(Ns[0],Ns[1])),ar._rotateAround(gr,qa),Jn._rotateAround(gr,qa),er._rotateAround(gr,qa),xr._rotateAround(gr,qa),gn=Math.min(ar.x,Jn.x,er.x,xr.x),Mn=Math.max(ar.x,Jn.x,er.x,xr.x),hn=Math.min(ar.y,Jn.y,er.y,xr.y),fn=Math.max(ar.y,Jn.y,er.y,xr.y)}return xt.emplaceBack(We.x,We.y,We.z,ct.x,ct.y,gn,hn,Mn,fn,js,Nt,Rt,$t),xt.length-1}function Ds(xt){ze(xt)&&xt.collisionPadding&&(xt.top-=xt.collisionPadding[1],xt.bottom+=xt.collisionPadding[3]);const We=xt.bottom-xt.top;return We>0?Math.max(10,We):null}function Bt(xt,We,ct,Nt){const Rt=xt.compareText;if(We in Rt){const $t=Rt[We];for(let Wt=$t.length-1;Wt>=0;Wt--)if(Nt.dist($t[Wt])=We.maxzoom||We.visibility==="none")}parse(We,ct,Nt,Rt,$t,Wt){this._parseAfterHD(We,ct,Nt,Rt,$t,Wt)}_parseAfterHD(We,ct,Nt,Rt,$t,Wt){let js;if(this.status="parsing",this.data=We,this.renderSourceType===c.bS.HdRoadCoverage){const Jn=We.layers[c.bV];js=Jn&&m?m(Jn):[]}this.collisionBoxArray=new c.bu;const Ts=new c.gc(Object.keys(We.layers).sort()),Ns=new c.fG(this.tileID,this.promoteId);Ns.bucketLayerIDs=[];const Ms={},hn=new c.gd(256,256),fn={featureIndex:Ns,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:hn,availableImages:Nt,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&&(fn.activeFloors=g(We,this.indoor,$t,this.canonical));const gn=[],Mn=ct.familiesBySource[this.source];if(this.deferRoadStructure=!1,this.renderSourceType!==c.bS.HdRoadCoverage&&this.frcCoverage!=null&&!this.frcCoverage.resolved&&this.frcCoverage.frcMask===null){for(const Jn in Mn)if(c.ge&&c.ge(this.frcCoverage.sourceLayers,this.source,Jn)){this.deferRoadStructure=!0;break}}for(const Jn in Mn){const er=We.layers[Jn];if(!er)continue;let xr=!1,gr=!1,qa=!1,et=!1;for(const sr of Mn[Jn])sr[0].type==="symbol"?xr=!0:sr[0].type==="fill-extrusion"?gr=!0:qa=!0,sr[0].is3D()&&sr[0].type!=="model"&&(et=!0);if(this.extraShadowCaster&&!et||this.renderSourceType===c.bS.Symbol&&!xr||this.renderSourceType===c.bS.FillExtrusion&&!gr||(this.renderSourceType===c.bS.Other||this.renderSourceType===c.bS.HdRoadCoverage)&&!qa)continue;const Gt=this.frcCoverage!=null&&!!c.ge&&c.ge(this.frcCoverage.sourceLayers,this.source,Jn);if(this.deferRoadStructure&&Gt)continue;er.version===1&&c.w(`Vector tile source "${this.source}" layer "${Jn}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const Es=Ts.encode(Jn),on=[],en=this.localizableLayerIds&&this.localizableLayerIds.has(Jn);let tr=!1;for(let sr=0,Xr=0;src.m(Na.id,Na.scope)));const $a=()=>{ia(sr,this.zoom,fn.brightness,Nt,this.worldview,fn.activeFloors);const Na=Ms[Xr.id]=Xr.createBucket({index:sa,layers:sr,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Es,sourceLayerName:Jn,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Rt,worldview:this.worldview,localizable:en,availableImages:Nt,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords});E&&E(Na,this.frcCoverage?this.frcCoverage.sourceLayers:null),Na.populate(on,fn,this.tileID.canonical,this.tileTransform)};Xr.mayUse("HD")||Xr.mayUse("Standard")?gn.push(Xr.prepare().then(()=>$a())):$a()}}const ar=()=>{hn.trim();const Jn=!(!fn.elevationFeatures||!fn.elevationFeatures.some(Xr=>Xr.heightRange.min<0));let er,xr,gr,qa,et,Gt,Es,on=fn.elevationFeatures;this.crossSourceElevationEnabled&&u&&(on=on||u(We,this.canonical)||[]);const en={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},tr=()=>{if(er)return this.status="done",Wt(er);if(this.extraShadowCaster){this.status="done";const Xr=Object.values(Ms).filter(sa=>!sa.isEmpty());Wt(null,{buckets:Xr,containsHdExt:dn(Xr),containsStandardExt:Ks(Xr),featureIndex:Ns,collisionBoxArray:null,hasTunnelGeometry:Jn,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:fn.brightness,hasDeferredElevationFeatures:!!I&&I(Ms),parsedElevationFeatures:on,glyphMap:null,iconMap:null,glyphPositions:null})}else if(xr&&gr&&qa&&Es){const sa=new vs(xr),$a=new Map;for(const[La,eo]of gr.entries()){const{imagePosition:xo}=c.g0(La,eo,c.g1);$a.set(La,xo)}const Na={};for(const La in Ms){const eo=Ms[La];if(eo instanceof c.bv){ia(eo.layers,this.zoom,fn.brightness,Nt,this.worldview,fn.activeFloors);const xo=Cn(this.frcCoverage,this.source,eo.layers[0].sourceLayer);Na[La]=Ke(eo,xr,sa.positions,gr,$a,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,et,this.worldview,Nt,xo.frcMask,xo.polygons,xo.tileZoom,c.gf||null,f||null)}}et.size||Gt.size?this.rasterizeTask=$t.sendCancelable("rasterizeImages",{scope:this.scope,iconTasks:et,patternTasks:Gt},{},(La,eo)=>{if(!La)for(const[xo,io]of eo.entries())gr.has(xo)&&gr.set(xo,Object.assign(gr.get(xo),{data:io})),qa.has(xo)&&qa.set(xo,Object.assign(qa.get(xo),{data:io}));sr(Na,sa,void 0,Es)}):sr(Na,sa,void 0,Es)}},sr=(Xr,sa,$a,Na)=>{const La=gr.size>0||qa.size>0,eo=Object.keys(Xr).length>0;if(!La&&!eo){this.status="done";const io=Object.values(Ms).filter(Lo=>!Lo.isEmpty());return void Wt(null,{buckets:io,containsHdExt:dn(io),containsStandardExt:Ks(io),featureIndex:Ns,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Jn,glyphAtlasImage:sa.image,lineAtlas:hn,imageAtlas:null,brightness:fn.brightness,hasDeferredRoadStructure:this.deferRoadStructure,frcCoveragePolygons:js,hasDeferredElevationFeatures:!!I&&I(Ms),parsedElevationFeatures:on})}const xo=(io,Lo)=>{for(const fo in Ms){const nl=Ms[fo];if(fo in Xr)bs(nl,Xr[fo],this.showCollisionBoxes,Nt,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,gr,Lo);else if(nl.hasPattern&&(nl instanceof c.bA||nl instanceof c.bB||nl instanceof c.aD)){ia(nl.layers,this.zoom,fn.brightness,Nt,this.worldview,fn.activeFloors);const Pl=Object.fromEntries(Lo.patternPositions);nl.addFeatures(fn,this.tileID.canonical,Pl,Nt,this.tileTransform,this.brightness)}}this.status="done";const Ul=Object.values(Ms).filter(fo=>!fo.isEmpty());Wt(null,{buckets:Ul,containsHdExt:dn(Ul),containsStandardExt:Ks(Ul),featureIndex:Ns,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Jn,glyphAtlasImage:sa.image,lineAtlas:hn,imageAtlas:io,brightness:fn.brightness,hasDeferredRoadStructure:this.deferRoadStructure,frcCoveragePolygons:js,hasDeferredElevationFeatures:!!I&&I(Ms),parsedElevationFeatures:on})};if(La){const io=new Map,Lo=c.gh(gr,io),Ul=c.gh(qa,io),fo=new c.gi(Lo,Ul,Na,this.lut,this.scope,io);$t.send("checkAtlasCache",{descriptor:fo,scope:this.scope}).then(nl=>{let Pl,Cd;if(nl)Pl=new c.gj(nl.sourceHash),Cd=nl;else{const au=new c.gk(gr,qa,this.lut,Na,this.scope);Pl=au,Cd=au}xo(Pl,Cd)}).catch(nl=>{nl.name!=="AbortError"&&c.w(`[Worker] Error checking atlas cache: ${nl.message}`);const Pl=new c.gk(gr,qa,this.lut,Na,this.scope);xo(Pl,Pl)})}else xo(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const Xr=c.gg(fn.glyphDependencies,Na=>Object.keys(Na).map(Number));Object.keys(Xr).length?$t.send("getGlyphs",{uid:this.uid,stacks:Xr},{metadata:en}).then(Na=>{er||(xr=Na,tr())}).catch(Na=>{er||(er=Na,tr())}):xr={},Es=new Map;const sa=Array.from(fn.iconDependencies.keys()).map(Na=>c.I.parse(Na)),$a=Array.from(fn.patternDependencies.keys()).map(Na=>c.I.parse(Na));sa.length||$a.length?$t.send("getImages",{icons:sa,patterns:$a,source:this.source,scope:this.scope,tileID:this.tileID},{metadata:en}).then(Na=>{if(!er){gr=new Map,qa=new Map,et=this.updateImageMapAndGetImageTaskQueue(gr,Na.images,fn.iconDependencies),Gt=this.updateImageMapAndGetImageTaskQueue(qa,Na.images,fn.patternDependencies);for(const[La,eo]of Na.versions.entries())Es.set(La,eo);tr()}}).catch(Na=>{er||(er=Na,tr())}):(gr=new Map,qa=new Map,et=new Map,Gt=new Map)}h&&h({buckets:Ms,data:We,sourceLayerCoder:Ts,canonical:this.tileID.canonical,options:fn}),tr()};gn.length>0?Promise.allSettled(gn).then(ar).catch(Wt):ar()}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,ct,Nt){const Rt=new Map;for(const $t of ct.keys()){const Wt=Nt.get($t)||[];for(const js of Wt){const Ts=js.toString(),Ns=ct.get(js.id.toString());Ns.usvg?Rt.has(Ts)||(Rt.set(Ts,js),We.set(Ts,{...Ns})):We.set(Ts,Ns)}}return Rt}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.abort()}}function ia(xt,We,ct,Nt,Rt,$t){const Wt=new c.aj(We,{brightness:ct,worldview:Rt,activeFloors:$t});for(const js of xt)js.recalculate(Wt,Nt)}class Hs extends c.E{constructor({actor:We,layerIndex:ct,availableImages:Nt,availableModels:Rt,isSpriteLoaded:$t,tileProvider:Wt,brightness:js,maxUniformBufferBindings:Ts,maxUniformBlockSizeDwords:Ns}){super(),this.actor=We,this.layerIndex=ct,this.availableImages=Nt,this.availableModels=Rt,this.loadVectorData=c.cH,this.tileProvider=Wt,this.loading={},this.loaded={},this.deduped=new c.cC(We.scheduler),this.isSpriteLoaded=$t,this.scheduler=We.scheduler,this.brightness=js,this.maxUniformBufferBindings=Ts,this.maxUniformBlockSizeDwords=Ns}loadTileData(We,ct){if(!this.tileProvider)return this.loadVectorData(We,ct);const Nt=new AbortController;return this.loadTileWithProvider(this.tileProvider,We,Nt,ct),()=>Nt.abort()}async loadTileWithProvider(We,ct,Nt,Rt){const{z:$t,x:Wt,y:js}=ct.tileID.canonical;try{const Ts=await We.loadTile({z:$t,x:Wt,y:js},{request:ct.request,signal:Nt.signal});if(Nt.signal.aborted)return;if(Ts==null){const Ms=new Error("Tile not found");return Ms.status=404,Rt(Ms)}if(Ts.data==null)return Rt(null,null);if(Ts.data instanceof ImageBitmap)return Rt(new Error("Vector tiles require ArrayBuffer data"));const Ns=new Headers;Ts.expires&&Ns.set("expires",Ts.expires),Ts.cacheControl&&Ns.set("cache-control",Ts.cacheControl),Rt(null,{rawData:Ts.data,headers:Ns})}catch(Ts){if(Nt.signal.aborted)return;Rt(Ts instanceof Error?Ts:new Error(String(Ts)))}}_fetchTileData(We,ct){return new Promise((Nt,Rt)=>{We.abort=this.loadTileData(ct,($t,Wt)=>{$t?Rt($t):Nt(Wt)})})}async _parse(We,ct){const Nt=!this.isSpriteLoaded;return Nt&&await this.once("isSpriteLoaded"),new Promise((Rt,$t)=>{const Wt=()=>We.parse(We.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(js,Ts)=>{js?$t(js):Rt(Ts)});Nt&&this.scheduler?this.scheduler.add(Wt,{type:"parseTile",renderSourceType:ct.renderSourceType,zoom:ct.tileZoom}):Wt()})}async loadTile(We){const ct=We.uid,Nt=We&&We.request,Rt=Nt&&Nt.collectResourceTiming,$t=this.loading[ct]=new Rr(We);$t.maxUniformBufferBindings=this.maxUniformBufferBindings,$t.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords;const Wt=(Mn,ar)=>{const Jn=$t.reloadCallback;Jn&&(delete $t.reloadCallback,Mn||!ar?Jn(Mn,null):$t.parse($t.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Jn))};let js,Ts;try{js=await this._fetchTileData($t,We)}catch(Mn){Ts=Mn}const Ns=!this.loading[ct];if(delete this.loading[ct],$t.cancelRasterize(),Ts||Ns||!js){if($t.status="done",Ns||(this.loaded[ct]=$t),Ts)throw Ts;return null}const Ms=js.rawData;let hn;$t.vectorTile=js.vectorTile||new c.gl(new c.c$(Ms)),this.loaded=this.loaded||{},this.loaded[ct]=$t;try{hn=await this._parse($t,We)}catch(Mn){throw Wt(Mn),Mn}if(!hn)return Wt(null,null),null;const fn={};if(Rt){const Mn=d(Nt);Mn.length>0&&(fn.resourceTiming=JSON.parse(JSON.stringify(Mn)))}const gn={rawTileData:Ms.slice(0),headers:js.headers,...hn,...fn};return Wt(null,hn),gn}async reloadTile(We){const ct=this.loaded,Nt=We.uid;if(ct&&ct[Nt])return new Promise((Rt,$t)=>{const Wt=ct[Nt];Wt.updateParameters(We);const js=(Ts,Ns)=>{const Ms=Wt.reloadCallback;Ms&&(delete Wt.reloadCallback,Wt.parse(Wt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Ms)),Ts?$t(Ts):Rt(Ns)};Wt.status==="parsing"?Wt.reloadCallback=js:Wt.status==="done"?Wt.vectorTile?Wt.parse(Wt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,js):js():Rt(void 0)})}abortTile(We){const ct=We.uid,Nt=this.loading[ct];Nt&&(Nt.abort&&Nt.abort(),delete this.loading[ct])}removeTile(We){const ct=this.loaded,Nt=We.uid;ct&&ct[Nt]&&delete ct[Nt]}}class Br{constructor(We){this.tileProvider=We.tileProvider,this.loading={}}async loadTile(We){const ct=We.uid,Nt=new AbortController;if(this.loading[ct]={cancel:()=>Nt.abort()},this.tileProvider)return this.loadTileWithProvider(this.tileProvider,ct,We,Nt);try{const{data:Rt,headers:$t}=await c.d0(We.request,Nt.signal);if(!Rt)return null;const Wt=await this.decodeTile(ct,Rt,We.encoding);return Wt.headers=$t,Wt}catch(Rt){if(Nt.signal.aborted)return null;throw Rt}finally{delete this.loading[ct]}}async decodeTile(We,ct,Nt){const Rt=ct instanceof ImageBitmap?ct:await createImageBitmap(new Blob([new Uint8Array(ct)],{type:"image/png"})),$t=1-(Rt.width-c.gm(Rt.width))/2,Wt=$t<1,js=this.getImageData(Rt,$t);return Rt.close(),{dem:new c.gn(We,js,Nt,Wt),borderReady:Wt}}async loadTileWithProvider(We,ct,Nt,Rt){const{z:$t,x:Wt,y:js}=Nt.tileID.canonical;try{const Ts=await We.loadTile({z:$t,x:Wt,y:js},{request:Nt.request,signal:Rt.signal});if(Rt.signal.aborted)return null;if(Ts==null){const hn=new Error("Tile not found");throw hn.status=404,hn}if(Ts.data==null)return null;const Ns=await this.decodeTile(ct,Ts.data,Nt.encoding);if(Rt.signal.aborted)return null;const Ms=new Headers;return Ts.expires&&Ms.set("expires",Ts.expires),Ts.cacheControl&&Ms.set("cache-control",Ts.cacheControl),Ns.headers=Ms,Ns}catch(Ts){if(Rt.signal.aborted)return null;throw Ts}finally{delete this.loading[ct]}}async reloadTile(We){}abortTile(We){const ct=We.uid,Nt=this.loading[ct];Nt&&(Nt.cancel(),delete this.loading[ct])}removeTile(We){}getImageData(We,ct){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 Nt=this.offscreenCanvasContext.getImageData(-ct,-ct,We.width+2*ct,We.height+2*ct);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),Nt}}const Ur=c.go.prototype.toGeoJSON;class Wn{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,ct=[];if(We.type===4)ct.push([new c.P(We.x,We.y)]);else if(We.type===1)for(let Nt=0;Nt($t-bn)/Rt&&Nt>(Wt-bn)/Rt}function Lr(xt){const{id:We,geometry:ct,properties:Nt}=xt;if(ct.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:Rt,coordinates:$t}=ct,Wt={id:We,type:1,geometry:[],tags:Nt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},js=Wt.geometry;if(Rt==="Point")la($t,js,Wt);else if(Rt==="MultiPoint")for(const Ts of $t)la(Ts,js,Wt);else if(Rt==="LineString")Wt.type=2,Xn($t,js,Wt);else if(Rt==="MultiLineString")Wt.type=2,wr($t,js,Wt);else if(Rt==="Polygon")Wt.type=3,wr($t,js,Wt,!0);else{if(Rt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");Wt.type=3;for(const Ts of $t)wr(Ts,js,Wt,!0)}return Wt}function la([xt,We],ct,Nt){const Rt=c.a7(xt);let $t=c.a8(We);$t=$t<0?0:$t>1?1:$t,ct.push(Rt,$t),Nt.minX=Math.min(Nt.minX,Rt),Nt.minY=Math.min(Nt.minY,$t),Nt.maxX=Math.max(Nt.maxX,Rt),Nt.maxY=Math.max(Nt.maxY,$t)}function Xn(xt,We,ct,Nt=!1,Rt=!1){const $t=[];for(const Wt of xt)la(Wt,$t,ct);We.push($t),Nt&&function(Wt,js){let Ts=0;for(let Ns=0,Ms=Wt.length,hn=Ms-2;Ns0===js)for(let Ns=0,Ms=Wt.length;Ns=Wt&&hn>=Wt||(Ns>=Wt?(Ms+=Math.round(Mn*((Wt-Ns)/gn)),Ns=Wt):hn>=Wt&&(fn=Ms+Math.round(Mn*((Wt-Ns)/gn)),hn=Wt),Ms>=Wt&&fn>=Wt||(Ms>=Wt?(Ns+=Math.round(gn*((Wt-Ms)/Mn)),Ms=Wt):fn>=Wt&&(hn=Ns+Math.round(gn*((Wt-Ms)/Mn)),fn=Wt),js&&Ns===js.at(-2)&&Ms===js.at(-1)||(js=[Ns,Ms],Rt.push(js)),js.push(hn,fn)))))}}function ii(xt,We,ct,Nt,Rt){const $t=(ct-bn)/We,Wt=(Nt-bn)/We,js=(ct+1+bn)/We,Ts=(Nt+1+bn)/We;function Ns(fn,gn){let Mn=0;return fn<$t?Mn|=1:fn>js&&(Mn|=2),gnTs&&(Mn|=8),Mn}let Ms=[];for(let fn=1;fn<=8;fn*=2){let gn=xt.at(-2),Mn=xt.at(-1),ar=!(Ns(gn,Mn)&fn);for(let Jn=0;Jn>31}function Tc(xt,We){if(xt.type===4)return We.writeVarint(Ka(1,1)),We.writeVarint(uo(xt.x)),void We.writeVarint(uo(xt.y));let ct=0,Nt=0;if(xt.type===1){const{geometry:Rt}=xt;We.writeVarint(Ka(1,Rt.length>>1));for(let $t=0;$t>1)-(Rt?1:0);for(let js=0;jsxt},Ho=1073741824,ti=1/Ho,Yr=xt=>(xt-.5)*Ho,Eo=xt=>xt*ti+.5;class Th{constructor(We){const ct=this.options=Object.assign(Object.create(Nl),We);ct.maxZoom=Math.min(ct.maxZoom,30),ct.minZoom=Math.min(ct.minZoom,ct.maxZoom),this.trees=new Array(ct.maxZoom+1),this.stride=ct.reduce?7:6,this.clusterProps=[]}load(We){const{log:ct,minZoom:Nt,maxZoom:Rt}=this.options;ct&&console.time("total time");const $t=Rt+1,Wt=`z${$t}: ${We.length} points`;ct&&console.time(Wt);const js=this.stride;let Ts=We.length;for(const xr of We){const gr=xr.geometry;gr&&gr.type==="MultiPoint"&&(Ts+=gr.coordinates.length-1)}this.numPoints=Ts;const Ns=this.props=new Array(Ts),Ms=this.coords=new Float64Array(2*Ts);let hn=null;const fn=new Int32Array(Ts*js);let gn=0,Mn=0;for(const xr of We){const gr=xr.geometry;if(!gr){Mn++;continue}const qa=gr.coordinates,et=gr.type==="MultiPoint";for(let Gt=0,Es=et?qa.length:1;Gt=Nt;xr--){const gr=performance.now(),qa=er||new Int32Array(Jn*js);er=null;const et=this._cluster(ar,Jn,xr,qa);et===Jn?(this.trees[xr]=this.trees[xr+1],er=qa):(this.trees[xr]=this._createTree(qa,et),ar=qa,Jn=et),ct&&console.log(`z${xr}: ${this.trees[xr].numItems} clusters in ${(performance.now()-gr).toFixed(2)}ms`)}return ct&&console.timeEnd("total time"),this}getClusters(We,ct){let Nt=((We[0]+180)%360+360)%360-180;const Rt=Math.max(-90,Math.min(90,We[1]));let $t=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)Nt=-180,$t=180;else if(Nt>$t){const hn=this.getClusters([Nt,Rt,180,Wt],ct),fn=this.getClusters([-180,Rt,$t,Wt],ct);return hn.concat(fn)}const js=this.trees[this._limitZoom(ct)],Ts=js.range(Yr(ro(Nt)),Yr(ea(Wt)),Yr(ro($t)),Yr(ea(Rt))),Ns=js.data,Ms=[];for(const hn of Ts)Ms.push(this._featureJSON(Ns,this.stride*hn));return Ms}getChildren(We){const ct=this._getOriginId(We),Nt=this._getOriginZoom(We),Rt="No cluster with the specified id.",$t=this.trees[Nt];if(!$t)throw new Error(Rt);const Wt=$t.data;if(ct>=$t.numItems)throw new Error(Rt);const js=this.options.radius/(this.options.extent*Math.pow(2,Nt-1)),Ts=$t.within(Wt[ct*this.stride],Wt[ct*this.stride+1],js*Ho),Ns=[];for(const Ms of Ts){const hn=Ms*this.stride;Wt[hn+4]===We&&Ns.push(this._featureJSON(Wt,hn))}if(Ns.length===0)throw new Error(Rt);return Ns}getLeaves(We,ct,Nt){const Rt=[];return this._appendLeaves(Rt,We,ct=ct||10,Nt=Nt||0,0),Rt}getTile(We,ct,Nt){return this._getTile(We,ct,Nt,!1)}getTileRaw(We,ct,Nt){return this._getTile(We,ct,Nt,!0)}_getTile(We,ct,Nt,Rt){const $t=this.trees[this._limitZoom(We)],Wt=Math.pow(2,We),{extent:js,radius:Ts}=this.options,Ns=Ts/js,Ms=Yr((Nt-Ns)/Wt),hn=Yr((Nt+1+Ns)/Wt),fn={features:[]};return this._addTileFeatures($t.range(Yr((ct-Ns)/Wt),Ms,Yr((ct+1+Ns)/Wt),hn),$t.data,ct,Nt,Wt,fn,Rt),ct===0&&this._addTileFeatures($t.range(Yr(1-Ns/Wt),Ms,Yr(1),hn),$t.data,Wt,Nt,Wt,fn,Rt),ct===Wt-1&&this._addTileFeatures($t.range(Yr(0),Ms,Yr(Ns/Wt),hn),$t.data,-1,Nt,Wt,fn,Rt),fn.features.length?fn:null}getClusterExpansionZoom(We){let ct=this._getOriginZoom(We)-1;for(;ct<=this.options.maxZoom;){const Nt=this.getChildren(We);if(ct++,Nt.length!==1)break;We=Nt[0].properties.cluster_id}return ct}_appendLeaves(We,ct,Nt,Rt,$t){const Wt=this.getChildren(ct);for(const js of Wt){const Ts=js.properties;if(Ts&&Ts.cluster?$t+Ts.point_count<=Rt?$t+=Ts.point_count:$t=this._appendLeaves(We,Ts.cluster_id,Nt,Rt,$t):$t1;let hn,fn,gn;if(Ms)hn=rh(ct,Ns,this.clusterProps),fn=Eo(ct[Ns]),gn=Eo(ct[Ns+1]);else{const gr=ct[Ns+3];hn=this.props[gr],fn=this.coords[2*gr],gn=this.coords[2*gr+1]}const Mn=Math.round(this.options.extent*(fn*$t-Nt)),ar=Math.round(this.options.extent*(gn*$t-Rt)),Jn=js?{type:4,x:Mn,y:ar,tags:hn}:{type:1,geometry:[[Mn,ar]],tags:hn},er=ct[Ns+3],xr=Ms||this.options.generateId?er:this.ids?this.ids[er]:void 0;xr!==void 0&&(Jn.id=xr),Wt.features.push(Jn)}}_limitZoom(We){return Math.max(this.options.minZoom,Math.min(Math.floor(+We),this.options.maxZoom+1))}_cluster(We,ct,Nt,Rt){const{radius:$t,extent:Wt,reduce:js,minPoints:Ts,maxZoom:Ns}=this.options,Ms=$t/(Wt*(1<Nt&&(Gt+=We[on+5])}if(Gt>et&&Gt>=Ts){let Es,on=xr*et,en=gr*et,tr=-1;const sr=(er/gn<<5)+(Nt+1)+this.numPoints;for(let Xr=0;Xr1)for(let Es=0;Es>5}_getOriginZoom(We){return(We-this.numPoints)%32}_featureJSON(We,ct){const Nt=We[ct+3],Rt=We[ct+5]>1,$t=Rt?Nt:this.ids?this.ids[Nt]:void 0,Wt={type:"Feature",properties:Rt?rh(We,ct,this.clusterProps):this.props[Nt],geometry:{type:"Point",coordinates:Rt?[pc(Eo(We[ct])),ml(Eo(We[ct+1]))]:[pc(this.coords[2*Nt]),ml(this.coords[2*Nt+1])]}};return $t!==void 0&&(Wt.id=$t),Wt}_map(We,ct,Nt){if(We[ct+5]>1){const Wt=this.clusterProps[We[ct+6]];return Nt?Object.assign({},Wt):Wt}const Rt=this.props[We[ct+3]],$t=this.options.map(Rt);return Nt&&$t===Rt?Object.assign({},$t):$t}}function rh(xt,We,ct){const Nt=xt[We+5],Rt=Nt>=1e4?`${Math.round(Nt/1e3)}k`:Nt>=1e3?Math.round(Nt/100)/10+"k":Nt,$t=xt[We+6],Wt=$t===-1?{}:Object.assign({},ct[$t]);return Object.assign(Wt,{cluster:!0,cluster_id:xt[We+3],point_count:Nt,point_count_abbreviated:Rt})}function ro(xt){return xt/360+.5}function ea(xt){const We=Math.sin(xt*Math.PI/180),ct=.5-.25*Math.log((1+We)/(1-We))/Math.PI;return ct<0?0:ct>1?1:ct}function pc(xt){return 360*(xt-.5)}function ml(xt){const We=(180-360*xt)*Math.PI/180;return 360*Math.atan(Math.exp(We))/Math.PI-90}const Co=2147483647;function mu(xt,We,ct,Nt){return{id:xt,type:4,x:We,y:ct,tags:Nt}}function cc(xt,We,ct,Nt){const Rt={id:xt,type:We,geometry:ct,tags:Nt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(We===1)nd(Rt,ct,0,ct.length);else{const $t=We===3;for(let Wt=0;Wt=0)&&nd(Rt,ct,js,Ts),Wt=Ts}}return Rt}function nd(xt,We,ct,Nt){for(let Rt=ct;Rtxt.maxX&&(xt.maxX=$t),Wt>xt.maxY&&(xt.maxY=Wt)}}function Dr(xt,We,ct,Nt){let Rt=Nt;const $t=We+(ct-We>>1);let Wt,js=ct-We;const Ts=xt[We],Ns=xt[We+1],Ms=xt[ct],hn=xt[ct+1];for(let fn=We+3;fnRt)Wt=fn,Rt=gn;else if(gn===Rt){const Mn=Math.abs(fn-$t);MnNt){const fn=Wt;fn-We>3&&Dr(xt,We,fn,Nt),xt[fn+2]=Math.min(Math.sqrt(Rt),Co),ct-fn>3&&Dr(xt,fn,ct,Nt)}}function Hi(xt,We,ct,Nt,Rt,$t){let Wt=Rt-ct,js=$t-Nt;if(Wt!==0||js!==0){const Ts=((xt-ct)*Wt+(We-Nt)*js)/(Wt*Wt+js*js);Ts>1?(ct=Rt,Nt=$t):Ts>0&&(ct+=Wt*Ts,Nt+=js*Ts)}return Wt=xt-ct,js=We-Nt,Wt*Wt+js*js}const zc="Input data is not a valid GeoJSON object.";function Bc(xt,We,ct,Nt){var Mn;const Rt=We.geometry;if(!Rt)return;const $t=Rt.type==="GeometryCollection"?Rt.geometries:Rt.coordinates;if(!$t)throw new Error(zc);if(!$t.length)return;const Wt=ct.tolerance*ct.worldScale/((1<0&&(We+=2+3*ct.length);return We}let $l=0;function sg(xt,We,ct,Nt,Rt,$t,Wt){const js=cc(We,ct,Nt,Rt);ct===2&&$t.lineMetrics&&(js.start=0,js.end=js.size=Wt),xt.push(js)}function Mx(xt,We,ct,Nt,Rt,$t){const Wt=new $t.CoordArray(2+3*ct.length);Yo(Wt,0,ct,Rt,!1,!1,$t.worldScale,$t.originShift,$t.useInt32),sg(xt,We,2,Wt,Nt,$t,$l)}function Yo(xt,We,ct,Nt,Rt,$t,Wt,js,Ts){if(ct.length===0)return We;const Ns=We,Ms=We+=2;let hn=0,fn=0,gn=0;for(let Jn=0;Jn0)if(Rt)gn+=(hn*xr-er*fn)/2;else{const gr=er-hn,qa=xr-fn;gn+=Math.sqrt(gr*gr+qa*qa)}hn=er,fn=xr}const Mn=We;if(Rt&&($t&&gn<0||!$t&&gn>=0)){const Jn=Mn-Ms;for(let er=0;er1?1:Rt)-ct)*We}function Yc(xt,We,ct,Nt,Rt,$t,Wt){if(Rt>=We&&$t=ct)return null;const js=Wt.lineMetrics,Ts=Wt.CoordArray;let Ns=null;for(let Ms=0;Ms=We&&Jn=We&&ar=ct?Ns===null&&(Ns=xt.slice(0,Ms)):(Ns===null&&(Ns=xt.slice(0,Ms)),fn!==1?Xa(gn,fn,We,ct,Nt,hn,Ns,js,Ts):ws(gn,We,ct,Nt,hn,Ns,Ts))}return Ns===null?xt:Ns.length?Ns:null}function ws(xt,We,ct,Nt,Rt,$t,Wt){let js=0;for(let Ms=0;Ms=We&&xt[Ms+Nt]=We&&xt[Ms+Nt]=Nt&&(Ns++,Ms++):gn>Rt?Mn<=Rt&&(Ns++,Ms++):Ns++,Mn=Nt&&(Ns++,Ms++,ar=!0),Mn>Rt&&gn<=Rt&&(Ns++,Ms++,ar=!0),!Wt&&ar&&(Ns>0&&(Ts+=Ns,js++),Ns=0)}const hn=xt[ct-3+$t];return hn>=Nt&&hn<=Rt&&Ns++,Wt&&Ns>=2&&Ms>=1&&Ns++,Ns>0&&(Ts+=Ns,js++),3*Ts+2*js}function Ba(xt,We,ct,Nt,Rt,$t,Wt,js,Ts,Ns,Ms,hn,fn){const gn=hn!==null;let Mn=$t;Rt[$t]=0,Rt[$t+1]=Nt;let ar=$t+=2,Jn=fn,er=Jn,xr=0,gr=0;for(let tr=We;tr=Wt&&(gr=ao(Rt,$t,sr,Xr,$a,Na,Wt,Ts,Ms),$t+=3,gn&&(er=Jn+xr*gr)):La>js?eo<=js&&(gr=ao(Rt,$t,sr,Xr,$a,Na,js,Ts,Ms),$t+=3,gn&&(er=Jn+xr*gr)):(Rt[$t]=sr,Rt[$t+1]=Xr,Rt[$t+2]=sa,$t+=3),eo=Wt&&(gr=ao(Rt,$t,sr,Xr,$a,Na,Wt,Ts,Ms),$t+=3,xo=!0),eo>js&&La<=js&&(gr=ao(Rt,$t,sr,Xr,$a,Na,js,Ts,Ms),$t+=3,xo=!0),!Ns&&xo){const io=($t-ar)/3;io>0&&(Rt[Mn]=io,gn&&hn.push(er,Jn+xr*gr),Mn=$t,Rt[$t]=0,Rt[$t+1]=Nt,ar=$t+=2)}gn&&(Jn+=xr)}const qa=ct-3,et=xt[qa],Gt=xt[qa+1],Es=xt[qa+2],on=Ts===0?et:Gt;on>=Wt&&on<=js&&(Rt[$t]=et,Rt[$t+1]=Gt,Rt[$t+2]=Es,$t+=3),Ns&&$t-ar>=6&&(Rt[$t-3]!==Rt[ar]||Rt[$t-2]!==Rt[ar+1])&&(Rt[$t]=Rt[ar],Rt[$t+1]=Rt[ar+1],Rt[$t+2]=Rt[ar+2],$t+=3);const en=($t-ar)/3;return en>0?(Rt[Mn]=en,gn&&hn.push(er,Jn)):$t=Mn,$t}function ao(xt,We,ct,Nt,Rt,$t,Wt,js,Ts){let Ns;if(js===0){Ns=(Wt-ct)/(Rt-ct);const Ms=Nt+($t-Nt)*Ns;xt[We]=Wt,xt[We+1]=Ts?Math.floor(Ms+.5):Ms}else{Ns=(Wt-Nt)/($t-Nt);const Ms=ct+(Rt-ct)*Ns;xt[We]=Ts?Math.floor(Ms+.5):Ms,xt[We+1]=Wt}return xt[We+2]=Co,Ns}function ko(xt,We){const ct=[];for(const Nt of xt){if(Nt.type===4){ct.push(mu(Nt.id,Nt.x+We,Nt.y,Nt.tags));continue}const Rt=qi(Nt.geometry,Nt.type,We),$t=cc(Nt.id,Nt.type,Rt,Nt.tags);Nt.start!==void 0&&($t.start=Nt.start,$t.end=Nt.end,$t.size=Nt.size),ct.push($t)}return ct}function qi(xt,We,ct){const Nt=xt.slice();if(We===1)for(let Rt=0;Rtxt.maxX&&(xt.maxX=Jn),er>xt.maxY&&(xt.maxY=er),xt.numPoints++,xt.numSimplified++;const xr={x:Zo(Jn,Rt,$t,js,Ns,Ms),y:Zo(er,Rt,Wt,js,Ns,Ms),type:4,tags:We.tags||null};return We.id!==void 0&&(xr.id=We.id),void xt.features.push(xr)}const fn=We.geometry;let gn;if(We.minXxt.maxX&&(xt.maxX=We.maxX),We.maxY>xt.maxY&&(xt.maxY=We.maxY),hn===1){const Jn=fn.length/3;gn=new Ts(2*Jn);for(let er=0,xr=0;er0?Math.max(0,Jn/xr):0,Mn.mapbox_clip_end=er>=xr?1:er/xr}const ar={geometry:gn,type:hn,tags:Mn};We.id!==void 0&&(ar.id=We.id),xt.features.push(ar)}function Gg(xt,We,ct,Nt,Rt,$t,Wt,js,Ts,Ns,Ms,hn,fn,gn,Mn){const ar=(Nt-ct)/3;if(Math.abs(Rt)Wt&&Jn++;$t.numPoints+=ar,$t.numSimplified+=Jn;const er=new fn(2*Jn);let xr=0;for(let gr=ct;grWt)&&(er[xr++]=Zo(We[gr],Ts,Ns,hn,gn,Mn),er[xr++]=Zo(We[gr+1],Ts,Ms,hn,gn,Mn));xt.push(er)}const Fl={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,promoteId:null,generateId:!1,debug:0};class Ol{constructor(We,ct){const Nt=this.options=Object.assign(Object.create(Fl),ct),Rt=Nt.debug;if(Rt&&console.time("preprocess data"),Nt.maxZoom<0||Nt.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");if(Nt.promoteId&&Nt.generateId)throw new Error("promoteId and generateId cannot be used together.");const $t=(Nt.extent+2*Nt.buffer)*(1<1&&console.time("creation"),Mn=this.tiles[gn]=cm(We,ct,Nt,Rt,Ms),this.tileCoords.push({z:ct,x:Nt,y:Rt}),this.stats[ct]=(this.stats[ct]||0)+1,this.total++,hn>1&&(console.log(`tile z${ct}-${Nt}-${Rt} (features: ${Mn.numFeatures}, points: ${Mn.numPoints}, simplified: ${Mn.numSimplified})`),console.timeEnd("creation"))),Mn.source=We,$t==null){if(ct===Ms.indexMaxZoom||Mn.numPoints<=Ms.indexMaxPoints)continue}else{if(ct===Ms.maxZoom||ct===$t)continue;{const sr=$t-ct;if(Nt!==Wt>>sr||Rt!==js>>sr)continue}}if(Mn.source=null,We.length===0)continue;hn>1&&console.time("clipping");const ar=Ms.worldScale,Jn=Ms.originShift,er=ar/fn,xr=.5*Ms.buffer*ar/(fn*Ms.extent),gr=(Nt/fn-Jn)*ar,qa=(Rt/fn-Jn)*ar;let et=null,Gt=null,Es=null,on=null;const en=Yc(We,gr-xr,gr+er/2+xr,0,Mn.minX,Mn.maxX,Ms),tr=Yc(We,gr+er/2-xr,gr+er+xr,0,Mn.minX,Mn.maxX,Ms);en&&(et=Yc(en,qa-xr,qa+er/2+xr,1,Mn.minY,Mn.maxY,Ms),Gt=Yc(en,qa+er/2-xr,qa+er+xr,1,Mn.minY,Mn.maxY,Ms)),tr&&(Es=Yc(tr,qa-xr,qa+er/2+xr,1,Mn.minY,Mn.maxY,Ms),on=Yc(tr,qa+er/2-xr,qa+er+xr,1,Mn.minY,Mn.maxY,Ms)),hn>1&&console.timeEnd("clipping"),Ts.push(et||[],Gt||[],Es||[],on||[]),Ns.push(ct+1,2*Nt,2*Rt,ct+1,2*Nt,2*Rt+1,ct+1,2*Nt+1,2*Rt,ct+1,2*Nt+1,2*Rt+1)}}getTile(We,ct,Nt){const Rt=this.findTile(We,ct,Nt);return Rt?function($t){const Wt=[];for(const js of $t.features){let Ts;Ts=js.type===4?{type:1,geometry:[[js.x,js.y]],tags:js.tags??null}:js.type===1?{type:1,geometry:fy(js.geometry),tags:js.tags??null}:{type:js.type,geometry:js.geometry.map(fy),tags:js.tags??null},js.id!=null&&(Ts.id=js.id),Wt.push(Ts)}return{features:Wt}}(Rt):null}getTileRaw(We,ct,Nt){const Rt=this.findTile(We,ct,Nt);return Rt?{features:Rt.features}:null}findTile(We,ct,Nt){const Rt=this.options.debug;if((We=+We)<0||We>24)return null;const $t=1<1&&console.log("drilling down to z%d-%d-%d",We,ct,Nt);let js,Ts=We,Ns=ct,Ms=Nt;for(;!js&&Ts>0;)Ts--,Ns>>=1,Ms>>=1,js=this.tiles[Kd(Ts,Ns,Ms)];return js&&js.source?(Rt>1&&(console.log("found parent tile z%d-%d-%d",Ts,Ns,Ms),console.time("drilling down")),this.splitTile(js.source,Ts,Ns,Ms,We,ct,Nt),Rt>1&&console.timeEnd("drilling down"),this.tiles[Wt]??null):null}}function fy(xt){const We=[];for(let ct=0;ctNs.tags&&"3d_elevation_id"in Ns.tags&&"source"in Ns.tags&&Ns.tags.source==="elevation",$t=Nt.features.filter(Rt);let Wt={_geojsonTileLayer:Nt.features};$t.length>0&&(Wt={_geojsonTileLayer:Nt.features.filter(Ns=>!Rt(Ns)),hd_road_elevation:$t});const js=new Fn(Wt),Ts=function(Ns){const Ms=new c.gp;for(const hn of Object.keys(Ns))Ms.writeMessage(3,$i,{name:hn,features:Ns[hn]});return Ms.finish()}(Wt).buffer;We(null,{vectorTile:js,rawData:Ts,headers:new Headers})}class cf extends Hs{constructor(We){super(We),this.loadVectorData=Vh,this._dynamicIndex=new xs}async loadData(We){const ct=We&&We.request,Nt=ct&&ct.collectResourceTiming;this._geoJSONIndex=null;let Rt=await new Promise((Wt,js)=>{this.loadGeoJSON(We,(Ts,Ns)=>{Ts?js(Ts):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(js=>`${js.key}: ${js.message}`).join(", "));Rt.features=Rt.features.filter(js=>Wt.value.evaluate({zoom:0},js))}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 Th(function({superclusterOptions:Wt,clusterProperties:js}){if(!js||!Wt)return Wt;const Ts={},Ns={},Ms={accumulated:null,zoom:0},hn={properties:null},fn=Object.keys(js);for(const gn of fn){const[Mn,ar]=js[gn],Jn=c.c(ar),er=c.c(typeof Mn=="string"?[Mn,["accumulated"],["get",gn]]:Mn);Ts[gn]=Jn.value,Ns[gn]=er.value}return Wt.map=gn=>{hn.properties=gn;const Mn={};for(const ar of fn)Mn[ar]=Ts[ar].evaluate(Ms,hn);return Mn},Wt.reduce=(gn,Mn)=>{hn.properties=Mn;for(const ar of fn)Ms.accumulated=gn[ar],gn[ar]=Ns[ar].evaluate(Ms,hn)},Wt}(We)).load(Rt.features):We.dynamic?this._dynamicIndex:new Ol(Rt,We.geojsonVtOptions);const $t={};if(Nt){const Wt=d(ct);Wt&&($t.resourceTiming={},$t.resourceTiming[We.source]=JSON.parse(JSON.stringify(Wt)))}return $t}async reloadTile(We){const ct=this.loaded;return ct&&ct[We.uid]?We.partial?void 0:super.reloadTile(We):this.loadTile(We)}loadGeoJSON(We,ct){if(We.request)c.g(We.request).then(({data:Nt})=>ct(null,Nt)).catch(Nt=>ct(Nt));else{if(typeof We.data!="string")return ct(new Error(`Input data given to '${We.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return ct(null,JSON.parse(We.data))}catch{return ct(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 Wy{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 ct=this._mrt;this.status="parsing",this._entireBuffer=We,ct.parseHeader(We),this._isHeaderLoaded=!0;const Nt=[];for(const Rt in ct.layers){const $t=ct.getLayer(Rt),Wt=$t.getDataRange($t.getBandList()),js=ct.createDecodingTask(Wt),Ts=We.slice(Wt.firstByte,Wt.lastByte+1);Nt.push(c.c_.performDecoding(Ts,js).then(Ns=>js.complete(null,Ns)).catch(Ns=>js.complete(Ns,null)))}return await Promise.allSettled(Nt),ct}}class ah{constructor({actor:We}){this.actor=We,this.loading={},this.loaded={}}async loadTile(We){const ct=We.uid,Nt=new AbortController,Rt=this.loading[ct]=new Wy(We);Rt.abort=()=>Nt.abort();try{const{data:$t,headers:Wt}=await c.d0(We.request,Nt.signal);return $t?(this.loaded[ct]=Rt,{mrt:await Rt.parse($t),headers:Wt}):(Rt.status="done",this.loaded[ct]=Rt,null)}catch($t){if(Nt.signal.aborted)return null;throw Rt.status="done",this.loaded[ct]=Rt,$t}finally{delete this.loading[ct]}}async reloadTile(We){}abortTile(We){const ct=We.uid,Nt=this.loading[ct];Nt&&(Nt.abort&&Nt.abort(),delete this.loading[ct])}removeTile(We){const ct=We.uid;this.loaded[ct]&&delete this.loaded[ct]}async decodeRasterArray(We){return c.c_.performDecoding(We.buffer,We.task)}}class gh{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:Hs,geojson:cf,"raster-dem":Br},this.workerSources={},this.self.registerRTLTextPlugin=ct=>{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=ct.applyArabicShaping,c.fN.processBidirectionalText=ct.processBidirectionalText,c.fN.processStyledBidirectionalText=ct.processStyledBidirectionalText;for(const{resolve:Nt}of this.rtlPluginParsingListeners)Nt(!0);this.rtlPluginParsingListeners=[]}}clearCaches(We,ct){delete this.layerIndexes[We],delete this.availableImages[We],delete this.availableModels[We],delete this.workerSources[We],delete this.isSpriteLoaded[We]}checkIfReady(We,ct){}spriteLoaded(We,ct){const{scope:Nt}=ct;if(this.isSpriteLoaded[We]||(this.isSpriteLoaded[We]={}),this.isSpriteLoaded[We][Nt]=!0,this.workerSources[We]&&this.workerSources[We][Nt])for(const Rt in this.workerSources[We][Nt]){const $t=this.workerSources[We][Nt][Rt];for(const Wt in $t){const js=$t[Wt];js instanceof Hs&&(js.isSpriteLoaded=!0,js.fire(new c.h("isSpriteLoaded")))}}}setImages(We,ct){this.availableImages[We]||(this.availableImages[We]={});const{scope:Nt,images:Rt}=ct;if(this.availableImages[We][Nt]=Rt,ct.isSpriteLoaded&&this.spriteLoaded(We,{scope:Nt}),this.workerSources[We]&&this.workerSources[We][Nt])for(const $t in this.workerSources[We][Nt]){const Wt=this.workerSources[We][Nt][$t];for(const js in Wt)Wt[js].availableImages=Rt}}setModels(We,{scope:ct,models:Nt}){if(this.availableModels[We]||(this.availableModels[We]={}),this.availableModels[We][ct]=Nt,this.workerSources[We]&&this.workerSources[We][ct])for(const Rt in this.workerSources[We][ct]){const $t=this.workerSources[We][ct][Rt];for(const Wt in $t)$t[Wt].availableModels=Nt}}setProjection(We,ct){this.projections[We]=c.gr(ct)}setGlobalParams(We,ct){if(this.referrer=ct.referrer,Object.assign(c.eS,ct.config),ct.contextOptions){const{maxBindingPoints:Nt,maxUniformBlockSizeDwords:Rt}=ct.contextOptions;this.maxUniformBufferBindings=Nt,this.maxUniformBlockSizeDwords=Rt}}upsertRenderParams(We,ct){ct.brightness!==void 0&&(this.brightness=ct.brightness),ct.worldview!==void 0&&(this.worldview=ct.worldview)}setLayers(We,ct){this.getLayerIndex(We,ct.scope).replace(ct.layers,ct.options)}updateLayers(We,ct){this.getLayerIndex(We,ct.scope).update(ct.layers,ct.removedIds,ct.options)}async loadTile(We,ct){if(ct.projection=this.projections[We]||this.defaultProjection,ct.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 ct.type==="raster-array"&&await this.ensureRasterArrayWorkerSource(),this.getWorkerSource(We,ct).loadTile(ct)}async ensureRasterArraySource(We,ct){await this.ensureRasterArrayWorkerSource()}async ensureRasterArrayWorkerSource(){if(!this.workerSourceTypes["raster-array"]){if(await async function(){return Promise.resolve()}(),!ah)throw new Error('Could not load raster-array module for "raster-array" source.');this.workerSourceTypes["raster-array"]=ah}}async decodeRasterArray(We,ct){return await this.ensureRasterArrayWorkerSource(),this.getWorkerSource(We,ct).decodeRasterArray(ct)}reloadTile(We,ct){return ct.projection=this.projections[We]||this.defaultProjection,this.getWorkerSource(We,ct).reloadTile(ct)}abortTile(We,ct){const Nt=this.getExistingWorkerSource(We,ct);return Nt?Nt.abortTile(ct):void 0}removeTile(We,ct){const Nt=this.getExistingWorkerSource(We,ct);return Nt?Nt.removeTile(ct):void 0}getExistingWorkerSource(We,ct){const{type:Nt,source:Rt,scope:$t}=ct,Wt=this.workerSources[We];if(Wt&&Wt[$t]&&Wt[$t][Nt])return Wt[$t][Nt][Rt]}async removeSource(We,ct){const{type:Nt,source:Rt,scope:$t}=ct,Wt=this.workerSources[We]&&this.workerSources[We][$t]&&this.workerSources[We][$t][Nt],js=Wt&&Wt[Rt];js&&(delete Wt[Rt],js.removeSource&&await js.removeSource({source:Rt}))}async loadTileProvider(We,ct){const Nt=new(await c.cN(ct.name,ct.url))(ct.options);return this.getWorkerSource(We,{type:ct.type,source:ct.source,scope:ct.scope},Nt),Nt.load&&ct.request?Nt.load({request:ct.request}):null}async syncRTLPluginState(We,ct){if(c.fN.isParsed())return!0;if(c.fN.isParsing())return new Promise((Rt,$t)=>{this.rtlPluginParsingListeners.push({resolve:Rt,reject:$t})});c.fN.setState(ct);const Nt=c.fN.getPluginURL();if(!c.fN.isLoaded()||c.fN.isParsed()||c.fN.isParsing())return!1;c.fN.setState({pluginStatus:c.gs.parsing,pluginURL:Nt});try{return await self.__mapboxImport(Nt),!!c.fN.isParsed()||new Promise((Rt,$t)=>{this.rtlPluginParsingListeners.push({resolve:Rt,reject:$t})})}catch(Rt){c.fN.setState({pluginStatus:c.gs.error,pluginURL:Nt});for(const{reject:$t}of this.rtlPluginParsingListeners)$t(Rt);throw this.rtlPluginParsingListeners=[],Rt}}getAvailableImages(We,ct){this.availableImages[We]||(this.availableImages[We]={});let Nt=this.availableImages[We][ct];return Nt||(Nt=[]),Nt}getAvailableModels(We,ct){this.availableModels[We]||(this.availableModels[We]={});let Nt=this.availableModels[We][ct];return Nt||(Nt={}),Nt}getLayerIndex(We,ct){this.layerIndexes[We]||(this.layerIndexes[We]={});let Nt=this.layerIndexes[We][ct];return Nt||(Nt=this.layerIndexes[We][ct]=new W,Nt.scope=ct),Nt}getWorkerSource(We,ct,Nt){const{type:Rt,source:$t,scope:Wt}=ct,js=this.workerSources;if(js[We]||(js[We]={}),js[We][Wt]||(js[We][Wt]={}),js[We][Wt][Rt]||(js[We][Wt][Rt]={}),this.isSpriteLoaded[We]||(this.isSpriteLoaded[We]={}),this.getExistingWorkerSource(We,ct))Nt&&(js[We][Wt][Rt][$t].tileProvider=Nt);else{const Ts=this.actor.getWorkerSourceActor(We),Ns=this.workerSourceTypes[Rt];if(!Ns)throw new Error(`Unknown worker source type "${Rt}".`);js[We][Wt][Rt][$t]=new Ns({actor:Ts,layerIndex:this.getLayerIndex(We,Wt),availableImages:this.getAvailableImages(We,Wt),availableModels:this.getAvailableModels(We,Wt),isSpriteLoaded:this.isSpriteLoaded[We][Wt],tileProvider:Nt,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords})}return js[We][Wt][Rt][$t]}enforceCacheSizeLimit(We,ct){c.gu(ct)}}return c.gq(self)&&(self.worker=new gh(self)),gh}),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 v=typeof document<"u"?document.documentElement&&document.documentElement.style:null,y=v&&v.userSelect!==void 0?"userSelect":"WebkitUserSelect";let b;function w(){v&&y&&(b=v[y],v[y]="none")}function S(){v&&y&&(v[y]=b)}function A(L){L.preventDefault(),L.stopPropagation(),window.removeEventListener("click",A,!0)}function E(){window.addEventListener("click",A,!0),window.setTimeout(()=>{window.removeEventListener("click",A,!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(ke(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 ke(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=be(L.readVarint()));return T}function Ie(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(ke(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 Ne(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 Be{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,oe]of Object.entries(k))K.has(Q)?B.set(K.get(Q).toString(),oe):console.warn(`Ignoring unknown image variable "${Q}"`);return B}}function Se(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 Ve(L,k,T,B,K){for(const Q of B.children)ht(L,k,T,Q,K)}function ht(L,k,T,B,K){B.group?(L.save(),function(Q,oe,he,we,Me){const Re=we.mask_idx!=null?he.masks[we.mask_idx]:null,Ze=we.clip_path_idx!=null?he.clip_paths[we.clip_path_idx]:null;if(we.transform&&(oe=Ht(we.transform).preMultiplySelf(oe)),!function(dt,_t,bt){return dt.opacity!==255||_t||bt}(we,Ze!=null,Re!=null))return void Ve(Q,oe,he,we,Me);const Xe=qe(Q.canvas.width,Q.canvas.height);Ve(Xe,oe,he,we,Me),Ze&>(Xe,oe,he,Ze),Re&&es(Xe,oe,he,Re,Me),Q.globalAlpha=we.opacity/255,Q.drawImage(Xe.canvas,0,0),ze()}(L,k,T,B.group,K),L.restore()):B.path&&(L.save(),function(Q,oe,he,we,Me){Q.setTransform(oe),we.paint_order===1?(Qe(Q,he,we,Me),rt(Q,he,we,Me)):(rt(Q,he,we,Me),Qe(Q,he,we,Me))}(L,k,T,B.path,K),L.restore())}function Qe(L,k,T,B){const K=T.fill;if(!K)return;const Q=K.opacity/255;switch(L.save(),L.beginPath(),as(T,L),K.paint){case"rgb_color":L.fillStyle=Se(K.rgb_color,K.opacity,B);break;case"linear_gradient_idx":{const oe=k.linear_gradients[K.linear_gradient_idx];oe.transform&&L.setTransform(Ht(oe.transform).preMultiplySelf(L.getTransform())),L.fillStyle=Ke(L,oe,Q,B);break}case"radial_gradient_idx":{const oe=k.radial_gradients[K.radial_gradient_idx];oe.transform&&L.setTransform(Ht(oe.transform).preMultiplySelf(L.getTransform())),L.fillStyle=Je(L,oe,Q,B)}}L.fill(at(T)),L.restore()}function at(L){return L.rule===1?"nonzero":L.rule===2?"evenodd":void 0}function rt(L,k,T,B){const K=T.stroke;if(!K)return;const Q=bs(T);L.lineWidth=K.width,L.miterLimit=K.miterlimit,L.setLineDash(K.dasharray),L.lineDashOffset=K.dashoffset;const oe=K.opacity/255;switch(K.paint){case"rgb_color":L.strokeStyle=Se(K.rgb_color,K.opacity,B);break;case"linear_gradient_idx":L.strokeStyle=Ke(L,k.linear_gradients[K.linear_gradient_idx],oe,B,!0);break;case"radial_gradient_idx":L.strokeStyle=Je(L,k.radial_gradients[K.radial_gradient_idx],oe,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 Xe=k.stops[0];return Se(Xe.rgb_color,Xe.opacity*T,B)}const{x1:Q,y1:oe,x2:he,y2:we}=k;let Me=new DOMPoint(Q,oe),Re=new DOMPoint(he,we);if(K){const Xe=Ht(k.transform);Me=Xe.transformPoint(Me),Re=Xe.transformPoint(Re)}const Ze=L.createLinearGradient(Me.x,Me.y,Re.x,Re.y);for(const Xe of k.stops)Ze.addColorStop(Xe.offset,Se(Xe.rgb_color,Xe.opacity*T,B));return Ze}function Je(L,k,T,B,K=!1){if(k.stops.length===1){const ss=k.stops[0];return Se(ss.rgb_color,ss.opacity*T,B)}const Q=Ht(k.transform),{fx:oe,fy:he,fr:we,cx:Me,cy:Re,r:Ze}=k;let Xe=new DOMPoint(oe,he),dt=new DOMPoint(Me,Re),_t=we,bt=Ze;if(K){Xe=Q.transformPoint(Xe),dt=Q.transformPoint(dt);const ss=(Q.a+Q.d)/2;_t=we*ss,bt=k.r*ss}const Mt=L.createRadialGradient(Xe.x,Xe.y,_t,dt.x,dt.y,bt);for(const ss of k.stops)Mt.addColorStop(ss.offset,Se(ss.rgb_color,ss.opacity*T,B));return Mt}function ft(L,k,T,B){const K=B.transform?Ht(B.transform).preMultiplySelf(k):k,Q=qe(L.canvas.width,L.canvas.height);for(const he of B.children)if(he.group)ft(Q,K,T,he.group);else if(he.path){const we=he.path,Me=new Path2D;Me.addPath(bs(we),K),Q.fill(Me,at(we))}const oe=B.clip_path_idx!=null?T.clip_paths[B.clip_path_idx]:null;oe&>(Q,K,T,oe),L.globalCompositeOperation="source-over",L.drawImage(Q.canvas,0,0),ze()}function gt(L,k,T,B){const K=qe(L.canvas.width,L.canvas.height);ft(K,k,T,B),L.globalCompositeOperation="destination-in",L.drawImage(K.canvas,0,0),ze()}function es(L,k,T,B,K){if(B.children.length===0)return;const Q=B.mask_idx!=null?T.masks[B.mask_idx]:null;Q&&es(L,k,T,Q,K);const oe=L.canvas.width,he=L.canvas.height,we=qe(oe,he),Me=B.width,Re=B.height,Ze=B.left,Xe=B.top,dt=new Path2D,_t=new Path2D;_t.rect(Ze,Xe,Me,Re),dt.addPath(_t,k),we.clip(dt);for(const ss of B.children)ht(we,k,T,ss,K);const bt=we.getImageData(0,0,oe,he),Mt=bt.data;if(B.mask_type===1)for(let ss=0;sso.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=[],oe=this.imageProviders.get(T);for(const Re of k){if(!Re.iconsetId){K.push(Re);continue}const Ze=oe.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 he=!0;const we=!!this.loaded.get(T),Me=this.images.get(T);if(!we)for(const Re of K)Me.has(Re.toString())||(he=!1);we||he?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:oe}=k;for(const he of[K,Q])for(const[we,Me]of he.entries()){const Re=this.getImage(Me.id,oe);Re&&B.set(we,{image:Re,imageVariant:Me})}T(null,this._rasterizeImages(oe,B))}_rasterizeImages(k,T){const B=new Map;for(const[K,{image:Q,imageVariant:oe}]of T.entries())B.set(K,this.imageRasterizer.rasterize(oe,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 oe of k){if(!K.get(oe.toString())){if(oe.iconsetId)continue;this.fire(new o.h("styleimagemissing",{id:oe.name}))}const he=K.get(oe.toString());if(!he){o.w(`Image "${oe.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:he.usvg?null:he.data.clone(),pixelRatio:he.pixelRatio,sdf:he.sdf,usvg:he.usvg,stretchX:he.stretchX,stretchY:he.stretchY,content:he.content,hasRenderCallback:!!(he.userImage&&he.userImage.render)};he.usvg&&Object.assign(we,{width:he.icon.usvg_tree.width,height:he.icon.usvg_tree.height}),Q.set(o.I.toString(oe),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),oe=Q.get(K),he=this.getImage(k,T);if(!he)return null;if(oe){if(oe.position.version===he.version)return oe.position;oe.position.version=he.version}else{if(he.usvg&&!he.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:he,imageVariant:Me}]]),Ze=this._rasterizeImages(T,Re);return this.storePatternImage(Me,T,he,B,Ze),null}this.storePattern(k,T,he)}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 oe=k.toString(),he=Q?Q.get(oe):void 0;he&&(B.data=he,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:oe}=o.p(K),he=this.atlasImage.get(k);he.resize({width:Q||1,height:oe||1});const we=this.images.get(k);for(const[Me,{bin:Re,position:Ze}]of B.entries()){let Xe=Ze.padding;const dt=Re.x+Xe,_t=Re.y+Xe,bt=we.get(Me).data,Mt=bt.width,ss=bt.height;Xe=Xe>1?Xe-1:Xe,o.b.copy(bt,he,{x:0,y:0},{x:dt,y:_t},{width:Mt,height:ss},T),o.b.copy(bt,he,{x:0,y:ss-Xe},{x:dt,y:_t-Xe},{width:Mt,height:Xe},T),o.b.copy(bt,he,{x:0,y:0},{x:dt,y:_t+ss},{width:Mt,height:Xe},T),o.b.copy(bt,he,{x:Mt-Xe,y:0},{x:dt-Xe,y:_t},{width:Xe,height:ss},T),o.b.copy(bt,he,{x:0,y:0},{x:dt+Mt,y:_t},{width:Xe,height:ss},T),o.b.copy(bt,he,{x:Mt-Xe,y:ss-Xe},{x:dt-Xe,y:_t-Xe},{width:Xe,height:Xe},T),o.b.copy(bt,he,{x:0,y:ss-Xe},{x:dt+Mt,y:_t-Xe},{width:Xe,height:Xe},T),o.b.copy(bt,he,{x:0,y:0},{x:dt+Mt,y:_t+ss},{width:Xe,height:Xe},T),o.b.copy(bt,he,{x:Mt-Xe,y:0},{x:dt-Xe,y:_t+ss},{width:Xe,height:Xe},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 is{constructor(k,T,B,K){this.message=(k?`${k}: `:"")+B,K&&(this.identifier=K),T!=null&&T.__line__&&(this.line=T.__line__)}}class jt extends is{}function zs(L){const k=L.value,T=L.valueSpec,B=L.style,K=L.styleSpec,Q=L.key,oe=L.arrayElementValidator||cr;if(!Array.isArray(k))return[new is(Q,k,`array expected, ${o.n(k)} found`)];if(T.length&&k.length!==T.length)return[new is(Q,k,`array length ${T.length} expected, length ${k.length} found`)];if(T["min-length"]&&k.lengthK)return[new is(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 is(k,T,`object expected, ${o.n(T)} found`)];const B=L.valueSpec,K=o.u(T.type);let Q,oe,he,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),Xe=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 is(bt.key,bt.value,'identity function may not have a "stops" property')];let Mt=[];const ss=bt.value;return Mt=Mt.concat(zs({key:bt.key,value:ss,valueSpec:bt.valueSpec,style:bt.style,styleSpec:bt.styleSpec,arrayElementValidator:dt})),Array.isArray(ss)&&ss.length===0&&Mt.push(new is(bt.key,ss,"array must have at least one stop")),Mt},default:function(bt){return cr({key:bt.key,value:bt.value,valueSpec:B,style:bt.style,styleSpec:bt.styleSpec})}}});return K==="identity"&&Me&&Xe.push(new is(L.key,L.value,'missing required property "property"')),K==="identity"||T.stops||Xe.push(new is(L.key,L.value,'missing required property "stops"')),K==="exponential"&&B.expression&&!o.r(B)&&Xe.push(new is(L.key,L.value,"exponential functions not supported")),L.styleSpec.$version>=8&&(Re&&!o.t(B)?Xe.push(new is(L.key,L.value,"property functions not supported")):Me&&!o.v(B)&&Xe.push(new is(L.key,L.value,"zoom functions not supported"))),K!=="categorical"&&!Ze||T.property!==void 0||Xe.push(new is(L.key,L.value,'"property" property is required')),Xe;function dt(bt){let Mt=[];const ss=bt.value,Jt=bt.key;if(!Array.isArray(ss))return[new is(Jt,ss,`array expected, ${o.n(ss)} found`)];if(ss.length!==2)return[new is(Jt,ss,`array length 2 expected, length ${ss.length} found`)];if(Ze){if(!o.l(ss[0]))return[new is(Jt,ss,`object expected, ${o.n(ss[0])} found`)];const Lt=ss[0];if(Lt.zoom===void 0)return[new is(Jt,ss,"object stop key must have zoom")];if(Lt.value===void 0)return[new is(Jt,ss,"object stop key must have value")];const ps=o.u(Lt.zoom);if(typeof ps!="number")return[new is(Jt,Lt.zoom,"stop zoom values must be numbers")];if(he&&he>ps)return[new is(Jt,Lt.zoom,"stop zoom values must appear in ascending order")];ps!==he&&(he=ps,oe=void 0,we={}),Mt=Mt.concat(Pa({key:`${Jt}[0]`,value:ss[0],valueSpec:{zoom:{}},style:bt.style,styleSpec:bt.styleSpec,objectElementValidators:{zoom:yt,value:_t}}))}else Mt=Mt.concat(_t({key:`${Jt}[0]`,value:ss[0],style:bt.style,styleSpec:bt.styleSpec},ss));return o.x(o.y(ss[1]))?Mt.concat([new is(`${Jt}[1]`,ss[1],"expressions are not allowed in function stops.")]):Mt.concat(cr({key:`${Jt}[1]`,value:ss[1],valueSpec:B,style:bt.style,styleSpec:bt.styleSpec}))}function _t(bt,Mt){const ss=o.n(bt.value),Jt=o.u(bt.value),Lt=bt.value!==null?bt.value:Mt;if(Q){if(ss!==Q)return[new is(bt.key,Lt,`${ss} stop domain type must match previous stop domain type ${Q}`)]}else Q=ss;if(ss!=="number"&&ss!=="string"&&ss!=="boolean"&&typeof Jt!="number"&&typeof Jt!="string"&&typeof Jt!="boolean")return[new is(bt.key,Lt,"stop domain value must be a number, string, or boolean")];if(ss!=="number"&&K!=="categorical"){let ps=`number expected, ${ss} found`;return o.t(B)&&K===void 0&&(ps+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new is(bt.key,Lt,ps)]}return K!=="categorical"||ss!=="number"||typeof Jt=="number"&&isFinite(Jt)&&Math.floor(Jt)===Jt?K!=="categorical"&&ss==="number"&&typeof Jt=="number"&&typeof oe=="number"&&oe!==void 0&&Jtnew is(`${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 is(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 is(L.key,L.value,'"feature-state" data expressions are not supported with layout properties.')];if(L.expressionContext==="filter")return Ds(T,L);if(L.expressionContext==="appearance")return vs(T,L);if(L.expressionContext&&L.expressionContext.indexOf("cluster")===0){if(!o.B(T,["zoom","feature-state"]))return[new is(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 is(L.key,L.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Ds(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 is(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(...Ds(K,k))}),B)}const Bt=new Set(["get","has","properties","geometry-type","id"]),zt=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 vs(L,k){if(k.valueSpec&&k.valueSpec.expression)for(const B of k.valueSpec.expression.parameters)zt.delete(B);if(zt.size===0)return[];const T=[];if(L instanceof o.F){const B=Bt.has(L.name)?"feature":L.name;if(zt.has(B))return[new is(k.key,k.value,`["${L.name}"] is not an allowed parameter`)]}return L.eachChild(B=>{T.push(...vs(B,k))}),T}function dn(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 is(k,T,`expected one of [${B.values.join(", ")}], ${JSON.stringify(T)} found`)):Object.keys(B.values).includes(o.u(T))||K.push(new is(k,T,`expected one of [${Object.keys(B.values).join(", ")}], ${JSON.stringify(T)} found`)),K}function Ks(L){if(o.J(o.y(L.value))){const k=L.layerType||"fill";return Ss({...L,expressionContext:"filter",valueSpec:L.styleSpec[`filter_${k}`]})}return Cn(L)}function Cn(L){const k=L.value,T=L.key;if(!Array.isArray(k))return[new is(T,k,`array expected, ${o.n(k)} found`)];if(k.length<1)return[new is(T,k,"filter array must have at least 1 element")];const B=L.styleSpec;let K=dn({key:`${T}[0]`,value:k[0],valueSpec:B.filter_operator});const Q=()=>{k.length>=2&&(o.H(k[1])||K.push(new is(`${T}[1]`,k[1],`string expected, ${o.n(k[1])} found`)));for(let oe=2;oe":case">=":k.length>=2&&o.u(k[1])==="$type"&&K.push(new is(T,k,`"$type" cannot be use with operator "${k[0]}"`)),k.length!==3&&K.push(new is(T,k,`filter array for operator "${k[0]}" must have 3 elements`)),Q();break;case"==":case"!=":k.length!==3&&K.push(new is(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 oe=1;oe{Me in T&&k.push(new is(B,T[Me],`"${Me}" is prohibited for ref layers`))}),K.layers.forEach(Me=>{o.u(Me.id)===he&&(we=Me)}),we?we.ref?k.push(new is(B,T.ref,"ref cannot reference another ref layer")):oe=o.u(we.type):typeof he=="string"&&k.push(new is(B,T.ref,`ref layer "${he}" not found`))}else if(oe!=="background"&&oe!=="sky"&&oe!=="slot"&&oe!=="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"&&oe==="raster"?k.push(new is(B,T.source,`layer "${T.id}" requires a raster source`)):Me==="raster"&&oe!=="raster"?k.push(new is(B,T.source,`layer "${T.id}" requires a vector source`)):Me!=="vector"||T["source-layer"]?Me==="raster-dem"&&oe!=="hillshade"?k.push(new is(B,T.source,"raster-dem source can only be used with layer type 'hillshade'.")):Me!=="raster-array"||["raster","raster-particle"].includes(oe)?oe==="line"&&T.paint&&T.paint["line-gradient"]&&Me==="geojson"&&!we.lineMetrics?k.push(new is(B,T,`layer "${T.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):oe==="line"&&T.paint&&T.paint["line-trim-offset"]&&Me==="geojson"&&!we.lineMetrics?k.push(new is(B,T,`layer "${T.id}" specifies a line-trim-offset, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):oe==="raster-particle"&&Me!=="raster-array"&&k.push(new is(B,T.source,`layer "${T.id}" requires a 'raster-array' source.`)):k.push(new is(B,T.source,"raster-array source can only be used with layer type 'raster'.")):k.push(new is(B,T,`layer "${T.id}" must specify a "source-layer"`)):k.push(new is(B,T.source,`source "${T.source}" not found`))}else k.push(new is(`${B}.source`,T.source,'"source" must be a string'));else k.push(new is(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:()=>cr({key:`${B}.type`,value:T.type,valueSpec:Q.layer.type,style:L.style,styleSpec:L.styleSpec,object:T,objectKey:"type"}),filter:we=>Ks({layerType:oe,...we}),layout:we=>Pa({layer:T,key:we.key,value:we.value,valueSpec:{},style:we.style,styleSpec:we.styleSpec,objectElementValidators:{"*":Me=>Br({layerType:oe,...Me})}}),paint:we=>Pa({layer:T,key:we.key,value:we.value,valueSpec:{},style:we.style,styleSpec:we.styleSpec,objectElementValidators:{"*":Me=>Hs({layerType:oe,layer:T,...Me})}}),appearances(we){const Me=zs({key:we.key,value:we.value,valueSpec:we.valueSpec,style:we.style,styleSpec:we.styleSpec,arrayElementValidator:Xe=>function(dt){const{key:_t,layer:bt,layerType:Mt}=dt,ss=o.u(dt.value),Jt=o.u(ss.name),Lt=o.u(ss.condition),ps=Pa({key:_t,value:ss,valueSpec:dt.styleSpec.appearance,style:dt.style,styleSpec:dt.styleSpec,objectElementValidators:{condition:Gs=>function(Ls){const sn=[];return sn.push(...Ss({key:Ls.key,value:Ls.object.condition,valueSpec:o.s.appearance.condition,expressionContext:"appearance"})),sn}({...Gs}),properties:Gs=>function(Ls){const sn=[],{styleSpec:Bs,layer:nn,layerType:yn}=Ls,Tn=Bs[`paint_${yn}`],Gn=Bs[`layout_${yn}`],zn=Ls.object[Ls.objectKey];for(const Dn in zn){const Mr=Dn in Tn?"paint":Dn in Gn?"layout":void 0;if(!Mr){sn.push(new is(Ls.key,Dn,`unknown property "${Dn}" for layer type "${yn}"`));continue}const kn={...Ls,key:`${Ls.key}.${Dn}`,objectKey:Dn,layer:nn,layerType:yn,value:zn[Dn],valueSpec:Mr==="paint"?Tn[Dn]:Gn[Dn]};sn.push(...ia(kn,Mr))}return sn}({layer:bt,layerType:Mt,...Gs})}});return Jt!=="hidden"&&Lt===void 0&&ps.push(new is(dt.key,"name",'Appearance with name different than "hidden" must have a condition')),ps}({layerType:oe,layer:T,...Xe})}),Re=Array.isArray(we.value)?we.value:[],Ze=new Set;return Re.forEach((Xe,dt)=>{const _t=o.u(Xe.name);if(_t)if(Ze.has(_t)){const bt=o.u(T.id);Me.push(new is(we.key,_t,`Duplicated appearance name "${_t}" for layer "${bt}"`))}else Ze.add(_t)}),Me}}})),k}function Wn({key:L,value:k}){return o.H(k)?[]:[new is(L,k,`string expected, ${o.n(k)} found`)]}const Sn={promoteId:function L({key:k,value:T}){if(o.H(T))return Wn({key:k,value:T});if(Array.isArray(T)){const K=[],Q=o.y(T),oe=o.c(Q);return oe.result==="error"?(oe.value.forEach(he=>{K.push(new is(`${k}${he.key}`,null,`${he.message}`))}),K):(o.B(oe.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 is(`${k}`,null,"promoteId expression should be only feature dependent")),K)}if(!o.l(T))return[new is(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 is(T,k,`object expected, ${o.n(k)} found`)];if(!("type"in k))return[new is(T,k,'"type" is required')];const Q=o.u(k.type);let oe=[];switch(["vector","raster","raster-dem","raster-array"].includes(Q)&&("url"in k||"tiles"in k||oe.push(new jt(T,k,'Either "url" or "tiles" is required.'))),Q){case"vector":case"raster":case"raster-dem":case"raster-array":return oe=oe.concat(Pa({key:T,value:k,valueSpec:B[`source_${Q.replace("-","_")}`],style:L.style,styleSpec:B,objectElementValidators:Sn})),oe;case"geojson":if(oe=Pa({key:T,value:k,valueSpec:B.source_geojson,style:K,styleSpec:B,objectElementValidators:Sn}),"cluster"in k&&"clusterProperties"in k){if(!o.l(k.clusterProperties))return[new is(`${T}.clusterProperties`,k,`object expected, ${o.n(k)} found`)];for(const he in k.clusterProperties){const we=k.clusterProperties[he];if(!Array.isArray(we))return[new is(`${T}.clusterProperties.${he}`,we,"array expected")];const[Me,Re]=we,Ze=typeof Me=="string"?[Me,["accumulated"],["get",he]]:Me;oe.push(...Ss({key:`${T}.${he}.map`,value:Re,expressionContext:"cluster-map"})),oe.push(...Ss({key:`${T}.${he}.reduce`,value:Ze,expressionContext:"cluster-reduce"}))}}return oe;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 is(T,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return dn({key:`${T}.type`,value:k.type,valueSpec:{values:bn(B)}})}}function bn(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 Tr(L){const k=L.value;return k?o.H(k)?xs(k,!0)?[]:[new is(L.key,k,`invalid url "${k}"`)]:[new is(L.key,k,`string expected, "${o.n(k)}" found`)]:[]}function Lr(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 is("light",k,`object expected, ${o.n(k)} found`)];let Q=[];for(const oe in k){const he=oe.match(o.K),we=oe.match(o.U);Q=Q.concat(we&&B[we[1]]?cr({key:oe,value:k[oe],valueSpec:{type:"string"},style:K,styleSpec:T}):he&&B[he[1]]&&B[he[1]].transition?cr({key:oe,value:k[oe],valueSpec:T.transition,style:K,styleSpec:T}):B[oe]?cr({key:oe,value:k[oe],valueSpec:B[oe],style:K,styleSpec:T}):[new is(oe,k[oe],`unknown property "${oe}"`)])}return Q}function la(L){const k=L.value;if(!k)return[];const T=L.key;if(!o.l(k))return[new is(T,k,`object expected, ${o.n(k)} found`)];let B=[];const K=L.styleSpec,Q=K["light-3d"],oe=L.style,he=L.style.lights;for(const Re of["type","id"])if(!(Re in k))return B=B.concat([new is(T,k,`missing property "${Re}"`)]),B;if(!o.H(k.type))return B=B.concat([new is(`${T}.type`,k.type,"string expected")]),B;if(he)for(let Re=0;Re[],array:zs,boolean:function(L){const k=L.value,T=L.key;return o.G(k)?[]:[new is(T,k,`boolean expected, ${o.n(k)} found`)]},number:yt,color:function({key:L,value:k}){return o.H(k)?o.C.parse(o.u(k))===void 0?[new is(L,k,`color expected, "${k}" found`)]:[]:[new is(L,k,`color expected, ${o.n(k)} found`)]},enum:dn,filter:Ks,function:gs,layer:Ur,object:Pa,source:Fn,model:Tr,light:Lr,"light-3d":la,terrain:Xn,fog:wr,string:Wn,formatted:function(L){return Wn(L).length===0?[]:Ss(L)},resolvedImage:function(L){return Wn(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 oe in k)Q=Q.concat(cr({key:oe,value:k[oe],valueSpec:B[oe],style:K,styleSpec:T}));return Q}return o.H(k)?[]:[new is("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 is(k,T,"import must be an object")];const{data:K,...Q}=T;Object.defineProperty(Q,"__line__",{value:T.__line__,enumerable:!1});let oe=Pa({...L,value:Q,valueSpec:B.import});o.u(Q.id)===""&&oe.push(new is(`${L.key}.id`,Q,"import id can't be an empty string"));const he=o.u(Q.id);return he!=="__proto__"&&he!=="constructor"&&he!=="prototype"||oe.push(new is(`${L.key}.id`,Q,`import id can't be "${String(he)}"`)),K&&(oe=oe.concat($i(K,B,{key:`${L.key}.data`}))),oe},iconset:function(L){const k=L.value,T=L.key,B=L.styleSpec,K=L.style;if(!o.l(k))return[new is(T,k,"object expected")];if(!k.type)return[new is(T,k,'"type" is required')];const Q=o.u(k.type);let oe=[];if(oe=oe.concat(Pa({key:T,value:k,valueSpec:B[`iconset_${Q}`],style:K,styleSpec:B})),function(he,we){return!(he!=="source"||!we.source)}(Q,k)){const he=K.sources&&Object.hasOwn(K.sources,k.source)?K.sources[k.source]:void 0,we=he&&o.u(he.type);he?we!=="raster-array"&&oe.push(new is(T,k.source,`iconset cannot be used with a source of type ${String(we)}, it only be used with a "raster-array" source type`)):oe.push(new is(T,k.source,`source "${k.source}" not found`))}return oe},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)?cr({...K,valueSpec:{...K.valueSpec,type:"*",expression:void 0}}):B&&Array.isArray(Q)?cr({...K,valueSpec:{...K.valueSpec,type:B}}):cr(K)}}})}};function cr(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&&Bn[B.type]){const Q=Bn[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,oe=L.styleSpec;if(!o.l(T))return[new is(k,T,`object expected, ${o.n(T)} found`)];let he=[];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,"*"),Xe=Re?B[Me]:Ze?B["*"]:void 0;let dt;Object.hasOwn(K,Me)?dt=K[Me]:Re?dt=cr:Object.hasOwn(K,"*")?dt=K["*"]:Ze&&(dt=cr),dt?he=he.concat(dt({key:(k&&`${k}.`)+we,value:T[we],valueSpec:Xe,style:Q,styleSpec:oe,object:T,objectKey:we},T)):he.push(new jt(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||he.push(new is(k,T,`missing required property "${we}"`))}return he}function ii({key:L,value:k}){const T=Wn({key:L,value:k});if(T.length)return T;const B=k;return B.includes("{fontstack}")||T.push(new is(L,k,'"glyphs" url must include a "{fontstack}" token')),B.includes("{range}")||T.push(new is(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 Ln(L){return L.slice().sort((k,T)=>k.line&&T.line?k.line-T.line:0)}const xa="setStyle",Ka="addLayer",uo="removeLayer",Tc="setPaintProperty",Fd="setLayerProperty",Nl="setTerrain",Ho="removeImport",ti="addIconset",Yr="removeIconset";function Eo(L,k,T){T.push({command:"addSource",args:[L,k[L]]})}function Th(L,k,T){k.push({command:"removeSource",args:[L]}),T[L]=!0}function rh(L,k,T,B){Th(L,T,B),Eo(L,k,T)}function ro(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 ea(L,k,T,B,K,Q){let oe;for(oe in k=k||{},L=L||{})Object.hasOwn(L,oe)&&(o.O(L[oe],k[oe])||T.push({command:Q,args:[B,oe,k[oe],K]}));for(oe in k)Object.hasOwn(k,oe)&&!Object.hasOwn(L,oe)&&(o.O(L[oe],k[oe])||T.push({command:Q,args:[B,oe,k[oe],K]}))}function pc(L){return L.id}function ml(L,k){return L[k.id]=k,L}const Co=new o.C(1,0,0,1),mu=new o.C(0,1,0,1),cc=new o.C(0,0,1,1),nd=new o.C(1,0,1,1),Dr=new o.C(0,1,1,1);function Hi(L,k,T,B,K,Q,oe){const he=L.context,we=L.transform,Me=he.gl,Re=we.projection.name==="globe",Ze=Re?["PROJECTION_GLOBE_VIEW"]:[];let Xe=o.Q(T.projMatrix);if(Re&&o.S(we.zoom)>0){const Gn=o.V(T.canonical,we),zn=o.W(Gn);Xe=o.X(new Float32Array(16),we.globeMatrix,zn),o.X(Xe,we.projMatrix,Xe)}const dt=o.Y();dt[12]+=2*K/(o.e.devicePixelRatio*we.width),dt[13]+=2*Q/(o.e.devicePixelRatio*we.height),o.X(Xe,dt,Xe);const _t=L.getOrCreateProgram("debug",{defines:Ze}),bt=k.getTileByID(T.key);L.terrain&&L.terrain.setupElevationDraw(bt,_t);const Mt=o.Z.disabled,ss=o._.disabled,Jt=L.colorModeForRenderPass(),Lt="$debug";he.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,Gs=bt._tileDebugIndexBuffer||L.debugIndexBuffer,Ls=bt._tileDebugSegments||L.debugSegments;if(_t.draw(L,Me.LINE_STRIP,Mt,ss,Jt,o.$.disabled,o.a0(Xe,B.toPremultipliedRenderColor(null)),Lt,ps,Gs,Ls,null,null,null,[bt._globeTileDebugBorderBuffer]),oe){const Gn=bt.latestRawTileData,zn=Math.floor((Gn&&Gn.byteLength||0)/1024);let Dn=T.canonical.toString();T.overscaledZ!==T.canonical.z&&(Dn+=` => ${T.overscaledZ}`),Dn+=` ${bt.state}`,Dn+=` ${zn}kb`,function(Mr,kn){Mr.initDebugOverlayCanvas();const pr=Mr.debugOverlayCanvas,ta=Mr.context.gl,ka=Mr.debugOverlayCanvas.getContext("2d");ka.clearRect(0,0,pr.width,pr.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(kn,5,5),ka.strokeText(kn,5,5),Mr.debugOverlayTexture.update(pr),Mr.debugOverlayTexture.bind(ta.LINEAR,ta.CLAMP_TO_EDGE)}(L,Dn)}const sn=k.getTile(T).tileSize,Bs=512/Math.min(sn,512)*(T.overscaledZ/we.zoom)*.5,nn=bt._tileDebugTextBuffer||L.debugBuffer,yn=bt._tileDebugTextIndexBuffer||L.quadTriangleIndexBuffer,Tn=bt._tileDebugTextSegments||L.debugSegments;_t.draw(L,Me.TRIANGLES,Mt,ss,o.a1.alphaBlended,o.$.disabled,o.a0(Xe,o.C.transparent.toPremultipliedRenderColor(null),Bs),Lt,nn,yn,Tn,null,null,null,[bt._globeTileDebugTextBuffer])}function zc(L,k,T,B){gc(L,0,k+T/2,L.transform.width,T,B)}function Bc(L,k,T,B){gc(L,k-T/2,0,T,L.transform.height,B)}function gc(L,k,T,B,K,Q){const oe=L.context,he=oe.gl;he.enable(he.SCISSOR_TEST),he.scissor(k*o.e.devicePixelRatio,T*o.e.devicePixelRatio,B*o.e.devicePixelRatio,K*o.e.devicePixelRatio),oe.clear({color:Q}),he.disable(he.SCISSOR_TEST)}function $l(L,k,T){const B=L.context,K=B.gl,Q=T.projMatrix,oe=L.getOrCreateProgram("debug"),he=k.getTileByID(T.key);L.terrain&&L.terrain.setupElevationDraw(he,oe);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 Xe=he.queryGeometryDebugViz,dt=he.queryBoundsDebugViz;if(Xe&&Xe.vertices.length>0){Xe.lazyUpload(B);const _t=Xe.vertexBuffer,bt=Xe.indexBuffer,Mt=Xe.segments;_t!=null&&bt!=null&&Mt!=null&&oe.draw(L,K.LINE_STRIP,we,Me,Re,o.$.disabled,o.a0(Q,Xe.color.toPremultipliedRenderColor(null)),Ze,_t,bt,Mt)}if(dt&&dt.vertices.length>0){dt.lazyUpload(B);const _t=dt.vertexBuffer,bt=dt.indexBuffer,Mt=dt.segments;_t!=null&&bt!=null&&Mt!=null&&oe.draw(L,K.LINE_STRIP,we,Me,Re,o.$.disabled,o.a0(Q,dt.color.toPremultipliedRenderColor(null)),Ze,_t,bt,Mt)}}const sg=(L,k,T,B,K,Q,oe,he)=>{const we=o.a6/Q.tileSize;return{u_matrix:L,u_inv_rot_matrix:k,u_camera_to_center_distance:T.getCameraToCenterDistance(he),u_extrude_scale:[T.pixelsToGLUnits[0]/we,T.pixelsToGLUnits[1]/we],u_zoom_transition:B,u_tile_id:oe,u_merc_center:K}},Mx=(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 Mc={loaded:!0,validateStyle:function(L,k=o.s){return Ln($i(L,k))},validateSource:L=>Ln(Fn(L)),validateLight:L=>Ln(Lr(L)),validateLights:L=>Ln(la(L)),validateTerrain:L=>Ln(Xn(L)),validateFog:L=>Ln(wr(L)),validateSnow:L=>Ln(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 is("snow",T,`object expected, ${o.n(T)} found`)];let oe=[];for(const he in T){const we=he.match(o.K);oe=oe.concat(we&&Q[we[1]]&&Q[we[1]].transition?cr({key:he,value:T[he],valueSpec:K.transition,style:B,styleSpec:K}):Q[he]?cr({key:he,value:T[he],valueSpec:Q[he],style:B,styleSpec:K}):[new jt(he,T[he],`unknown property "${he}"`)])}return oe}(L)),validateRain:L=>Ln(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 is("rain",T,`object expected, ${o.n(T)} found`)];let oe=[];for(const he in T){const we=he.match(o.K);oe=oe.concat(we&&Q[we[1]]&&Q[we[1]].transition?cr({key:he,value:T[he],valueSpec:K.transition,style:B,styleSpec:K}):Q[he]?cr({key:he,value:T[he],valueSpec:Q[he],style:B,styleSpec:K}):[new jt(he,T[he],`unknown property "${he}"`)])}return oe}(L)),validateLayer:L=>Ln(Ur(L)),validateFilter:L=>Ln(Ks(L)),validatePaintProperty:L=>Ln(Hs(L)),validateLayoutProperty:L=>Ln(Br(L)),validateModel:L=>Ln(Tr(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(he=[],we=[],Me){we=we||[];const Re=(he=he||[]).map(pc),Ze=we.map(pc),Xe=he.reduce(ml,{}),dt=we.reduce(ml,{}),_t=Re.slice();let bt,Mt,ss,Jt;for(bt=0,Mt=0;bt{he.source&&B[he.source]?T.push({command:uo,args:[he.id]}):Q.push(he)});let oe=L.terrain;oe&&B[oe.source]&&(T.push({command:Nl,args:[void 0]}),oe=void 0),T=T.concat(K),o.O(oe,k.terrain)||T.push({command:Nl,args:[k.terrain]}),function(he,we,Me){we=we||[];const Re=(he=he||[]).map(pc),Ze=we.map(pc),Xe=he.reduce(ml,{}),dt=we.reduce(ml,{}),_t=Re.slice(),bt=Object.create(null);let Mt,ss,Jt,Lt,ps,Gs,Ls;for(Mt=0,ss=0;Mt0){const $r=o.Y(),Ya=Gr;o.aa($r,Tn.placementInvProjMatrix,Me.glCoordMatrix),o.aa($r,$r,Tn.placementViewportMatrix),Mt.push({circleArray:Hr,circleOffset:Jt,transform:Ya,invTransform:$r,projection:Tn.getProjection()}),ss+=Hr.length/4,Jt=ss}if(!Sr)continue;L.terrain&&L.terrain.setupElevationDraw(yn,si);const Ha=qr?[nn.canonical.x,nn.canonical.y,1<{const T=Mc[L];return T?T(...k):[]}}const ws=Yc("validateStyle"),Xa=Yc("validateSource"),No=Yc("validateLight"),Ba=Yc("validateLights"),ao=Yc("validateTerrain"),ko=Yc("validateFog"),qi=Yc("validateSnow"),cm=Yc("validateRain"),Zo=Yc("validateLayer"),vo=Yc("validateFilter"),Gg=Yc("validatePaintProperty"),Fl=Yc("validateLayoutProperty"),Ol=Yc("validateModel"),fy=o.s.light;let Kd;class Vh extends o.E{constructor(k,T="flat"){super(),this._transitionable=new o.af(Kd||(Kd=new o.ag({anchor:new o.ah(fy.anchor),position:new o.ai(fy.position),color:new o.ah(fy.color),intensity:new o.ah(fy.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)&&lm(this,k.call(ws,{value:T,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}}const cf=o.s.terrain;let Wy=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(cf.source),exaggeration:new o.ah(cf.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 ah(L,k){const T=L?L.terrain:null;return!!T&&(!k||!!k.projection.requiresDraping||!T.isZoomDependent()||T.getExaggeration(k.zoom)>0)}const gh=o.s.fog;class xt extends o.E{constructor(k,T,B,K){super();const Q=new o.ag({range:new o.ah(gh.range),color:new o.ah(gh.color),"color-use-theme":new o.ah({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ah(gh["high-color"]),"high-color-use-theme":new o.ah({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ah(gh["space-color"]),"space-color-use-theme":new o.ah({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ah(gh["horizon-blend"]),"star-intensity":new o.ah(gh["star-intensity"]),"vertical-range":new o.ah(gh["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],oe=.5/Math.tan(.5*k._fov),he=[K[0]+oe,K[1]+oe];return{range:T?[o.am(Q[0],he[0],B),o.am(Q[1],he[1],B)]:he,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(gh))K[Q]===void 0&&(K[Q]=gh[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 oe=k.points[B-4];Q=o.as(oe,K,oe[2]/(oe[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)&&lm(this,k.call(ws,{value:T,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}}let We,ct,Nt=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)],oe=this.properties.get("vignette"),he=this.properties.get("vignette-color"),we=new o.C(he.r,he.g,he.b,oe);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)&&lm(this,L.call(ws,{value:k,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}},Rt=class extends o.E{constructor(L,k,T,B){super();const K=ct||(ct=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)],oe=this.properties.get("vignette-color"),he=new o.C(oe.r,oe.g,oe.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:he}}get(){return this._transitionable.serialize()}set(L,k,T={}){if(this._validate(cm,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)&&lm(this,L.call(ws,{value:k,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}};const $t={workerUrl:"",workerClass:null,workerParams:void 0};function Wt(L){return $t.workerClass!=null?new $t.workerClass:new self.Worker($t.workerUrl,{name:L,type:"module",...$t.workerParams})}const js="mapboxgl_preloaded_worker_pool";class Ts{constructor(k){this.active={},this.workers=null,this.name=k}acquire(k,T=Ts.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{T.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[js]}numActive(){return Object.keys(this.active).length}}Ts.workerCount=2;class Ns{constructor(k,T,B="Worker",K=Ts.workerCount){this.workerPool=k,this.actors=[],this.currentActor=0,this.id=o.aw();const Q=this.workerPool.acquire(this.id,K);for(let oe=0;oe{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 Ms 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 hn;const fn=()=>hn||(hn=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 gn;const Mn=()=>gn||(gn=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"])})),ar=(L,k,T,B,K,Q,oe,he,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:oe,u_flood_light_color:he,u_flood_light_intensity:we,u_front_cutoff_params:Me}),Jn=L=>({u_matrix:L}),er=L=>({u_matrix:L}),xr=o.az;async function gr(){return Promise.resolve()}function qa(L,k,T,B,K,Q,oe,he){T.resetLayerRenderingStats(L);const we=L.context,Me=we.gl,Re=L.transform,Ze=T.paint.get("fill-extrusion-pattern"),Xe=T.paint.get("fill-extrusion-pattern-cross-fade"),dt=Ze.constantOr(null),_t=Ze.constantOr(1),bt=T.paint.get("fill-extrusion-opacity"),Mt=L.style.enable3dLights(),ss=T.paint.get(Mt&&!_t?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Jt=[T.paint.get("fill-extrusion-ambient-occlusion-intensity"),ss],Lt=T.layout.get("fill-extrusion-edge-radius"),ps=Lt>0&&!T.paint.get("fill-extrusion-rounded-roof"),Gs=ps?0:Lt,Ls=Re.projection.name==="globe"?o.aE():0,sn=Re.projection.name==="globe",Bs=sn?o.S(Re.zoom):0,nn=[o.a7(Re.center.lng),o.a8(Re.center.lat)],yn=T.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Tn=T.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(yn?null:T.lut).toArray01().slice(0,3),Gn=T.paint.get("fill-extrusion-flood-light-intensity"),zn=T.paint.get("fill-extrusion-vertical-scale"),Dn=T.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Mr=T.paint.get("fill-extrusion-height-alignment"),kn=T.paint.get("fill-extrusion-base-alignment"),pr=o.aF(L,T.paint.get("fill-extrusion-cutoff-fade-range")),ta=T.paint.get("fill-extrusion-front-cutoff"),ka=Gt(Re.pitch,ta,!!L.terrain),qr=ka[2]<1;qr&&(L.maxFrontCutoffRawStart=Math.max(L.maxFrontCutoffRawStart,ta[0]));const Jr=[];let si;sn&&Jr.push("PROJECTION_GLOBE_VIEW"),Jt[0]>0&&Jr.push("FAUX_AO"),ps&&Jr.push("ZERO_ROOF_RADIUS"),he&&Jr.push("HAS_CENTROID"),Gn>0&&Jr.push("FLOOD_LIGHT"),pr.shouldRenderCutoff&&Jr.push("RENDER_CUTOFF"),qr&&Jr.push("RENDER_FRONT_CUTOFF"),Dn&&Jr.push("RENDER_WALL_MODE");const Gr=L.renderPass==="shadow",Sr=L.shadowRenderer,Hr=Gr&&!!Sr,Ha=Gr?o.$.disabled:o.$.backCCW;L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!0);let $r=[0,0,0];if(Sr){const Do=L.style.directionalLight,to=L.style.ambientLight;Do&&to&&($r=o.aG(L.style,Do,to)),Gr||(Jr.push("RENDER_SHADOWS"),Sr.useNormalOffset&&Jr.push("NORMAL_OFFSET")),si=Jr.concat(["SHADOWS_SINGLE_CASCADE"])}const Ya=Hr?"fillExtrusionDepth":_t?"fillExtrusionPattern":"fillExtrusion",Oi=T.getLayerRenderingStats();for(const Do of B){const to=k.getTile(Do),ql=to.getBucket(T);if(!ql||ql.projection.name!==Re.projection.name)continue;let yu=!1;Sr&&(yu=Sr.getMaxCascadeForTile(Do.toUnwrapped())===0);const Uc=L.isTileAffectedByFog(Do),Ko=ql.programConfigurations.get(T.id);let so=!1;if(dt&&to.imageAtlas){const dc=to.imageAtlas,Dh=o.aH.from(dt),Wh=Dh.getPrimary().scaleSelf(o.e.devicePixelRatio).toString(),Pd=Dh.getSecondary(),vc=dc.patternPositions.get(Wh),Kh=Pd?dc.patternPositions.get(Pd.scaleSelf(o.e.devicePixelRatio).toString()):null;so=!!vc&&!!Kh,vc&&Ko.setConstantPatternPositions(vc,Kh)}Xe>0&&(so||Ko.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&Jr.push("FILL_EXTRUSION_PATTERN_TRANSITION");const _d=L.getOrCreateProgram(Ya,{config:Ko,defines:yu?si:Jr,overrideFog:Uc});if(L.terrain&&L.terrain.setupElevationDraw(to,_d,{useMeterToDem:!0}),!ql.centroidVertexBuffer){const dc=_d.getAttributeLocation(Me,"a_centroid_pos");dc!==-1&&Me.vertexAttribI4ui(dc,0,0,0,0)}!Gr&&Sr&&Sr.setupShadows(to.tileID.toUnwrapped(),_d,"vector-tile"),_t&&(L.context.activeTexture.set(Me.TEXTURE0),to.imageAtlasTexture&&to.imageAtlasTexture.bind(Me.LINEAR,Me.CLAMP_TO_EDGE),Ko.updatePaintBuffers());const Gh=T.paint.get("fill-extrusion-vertical-gradient"),_h=1/ql.tileToMeter;let Vl;if(Gr&&Sr){if(sr(to.tileID,ql.maxHeight,L))continue;const dc=Sr.calculateShadowPassMatrixFromTile(to.tileID.toUnwrapped());Vl=o.aN(dc,Gs,_h,zn,Mr,kn)}else{const dc=L.translatePosMatrix(Do.expandedProjMatrix,to,T.paint.get("fill-extrusion-translate"),T.paint.get("fill-extrusion-translate-anchor")),Dh=Re.projection.createInversionMatrix(Re,Do.canonical),Wh=_d.fixedDefines.includes("LIGHTING_3D_MODE");Vl=_t?o.aI(dc,L,Gh,bt,Jt,Gs,_h,Do,to,Ls,Mr,kn,Bs,nn,Dh,Tn,zn,Xe,Wh):o.aJ(dc,L,Gh,bt,Jt,Gs,_h,Do,Ls,Mr,kn,Bs,nn,Dh,Tn,zn,Gn,$r,ka,Wh)}L.uploadCommonUniforms(we,_d,Do.toUnwrapped(),null,pr);let mm=ql.segments;if(Re.projection.name==="mercator"&&!Gr&&(mm=ql.getVisibleSegments(to.tileID,L.terrain,L.transform.getFrustum(0)),!mm.get().length))continue;if(Oi)if(Gr)for(const dc of mm.get())Oi.numRenderedVerticesInShadowPass+=dc.primitiveLength;else for(const dc of mm.get())Oi.numRenderedVerticesInTransparentPass+=dc.primitiveLength;const yc=[];(L.terrain||he)&&yc.push(ql.centroidVertexBuffer),sn&&yc.push(ql.layoutVertexExtBuffer),Dn&&yc.push(ql.wallVertexBuffer),_d.draw(L,we.gl.TRIANGLES,K,Q,oe,Ha,Vl,T.id,ql.layoutVertexBuffer,ql.indexBuffer,mm,T.paint,L.transform.zoom,Ko,yc)}L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!1)}class et{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function Gt(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 Es(L,k,T,B,K,Q,oe){B.centroidVertexArray.length===0&&B.createCentroidsBuffer();const he=Q?Q.findDEMTileFor(T):null;if(!(he&&he.dem||oe))return;Q&&he&&he.dem&&B.selfDEMTileTimestamp!==he.dem._timestamp&&(B.borderDoneWithNeighborZ=[-1,-1,-1,-1],B.selfDEMTileTimestamp=he.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,Gs)=>{const Ls=Math.ceil((Lt+o.aL)*o.aM),sn=Math.floor(Math.max(0,Math.min(o.a6-1,Gs))/4);return new o.P(Ls,sn<<5|(3&ps)<<3|7)},Ze=(Lt,ps)=>{const Gs=Number.MAX_VALUE,Ls=ps[0][0]!==Gs,sn=ps[1][0]!==Gs,Bs=ps[2][0]!==Gs,nn=ps[3][0]!==Gs;if(!((Ls?1:0)+(sn?1:0)+(Bs?1:0)+(nn?1:0)>2))return Lt<2?Bs===nn?void 0:Bs?0:o.a6-1:Ls===sn?void 0:Ls?0:o.a6-1},Xe=(Lt,ps,Gs,Ls)=>(ps?Ze(Lt,ps):void 0)??(Ls?Ze(Gs,Ls):void 0),dt=Lt=>{const ps=k.getSource().minzoom,Gs=sn=>{const Bs=k.getTileByID(sn);if(Bs&&Bs.hasData())return Bs.getBucket(K)},Ls=[0,-1,1];for(const sn of Ls){if(Lt.overscaledZ+sn(_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),ss=[(Lt,ps)=>bt(Lt,ps),(Lt,ps)=>bt(ps,Lt),(Lt,ps)=>Mt(Lt,ps),(Lt,ps)=>Mt(ps,Lt)],Jt=(Lt,ps,Gs,Ls,sn,Bs,nn)=>{if(!Q)return 0;const yn=[[Bs?Gs:Lt,Bs?Lt:Gs,0],[Bs?Gs:ps,Bs?ps:Gs,0]],Tn=nn<0?o.a6+nn:nn,Gn=[Bs?Tn:(Lt+ps)/2,Bs?(Lt+ps)/2:Tn,0];return Gs===0&&nn<0||Gs!==0&&nn>0?Q.getForTilePoints(sn,[Gn],!0,Ls):yn.push(Gn),Q.getForTilePoints(T,yn,!0,he),Math.max(yn[0][2],yn[1][2],Gn[2])/Q.exaggeration()};for(let Lt=0;Lt<4;Lt++){const ps=B.borderFeatureIndices[Lt];if(ps.length===0)continue;const Gs=o.aC[Lt](T),Ls=dt(Gs);if(!(Ls&&Ls instanceof o.aD))continue;const sn=Q?Q.findDEMTileFor(Gs):null;if(!(sn&&sn.dem||oe)||(Q&&sn&&sn.dem&&B.borderDEMTileTimestamp[Lt]!==sn.dem._timestamp&&(B.borderDoneWithNeighborZ[Lt]=-1,B.borderDEMTileTimestamp[Lt]=sn.dem._timestamp),B.borderDoneWithNeighborZ[Lt]===Ls.canonical.z))continue;Ls.centroidVertexArray.length===0&&Ls.createCentroidsBuffer();const Bs=(Lt<2?1:5)-Lt,nn=Ls.borderDoneWithNeighborZ[Bs]!==B.canonical.z,yn=Ls.borderFeatureIndices[Bs];let Tn=0;if(B.canonical.z!==Ls.canonical.z){for(const Mr of ps)B.showCentroid(B.featuresOnBorder[Mr],"discard");if(nn)for(const Mr of yn)Ls.showCentroid(Ls.featuresOnBorder[Mr],"discard");B.borderDoneWithNeighborZ[Lt]=Ls.canonical.z,Ls.borderDoneWithNeighborZ[Bs]=B.canonical.z;continue}const Gn=new Map,zn=new Set,Dn=new Set;for(let Mr=0;Mr1||ka.intersectsCount()>1;{let Ha=0;if(sn&&sn.dem&&!Hr){const $r=ss[Lt](pr,qr),Ya=Lt%2?o.a6-1:0;Ha=Jt($r[0],Math.min(o.a6-1,$r[1]),Ya,sn,Gs,Lt<2,$r[2])}pr.centroidXY=Re(Ha,Lt,Sr),qr.centroidXY=Re(Ha,Bs,Sr)}if(B.writeCentroidToBuffer(pr),Ls.writeCentroidToBuffer(qr),kn.buildingId!==void 0){for(const Ha of B.centroidData)Ha.buildingId===kn.buildingId&&Ha!==pr&&(Ha.centroidXY=pr.centroidXY,B.writeCentroidToBuffer(Ha));for(const Ha of Ls.centroidData)Ha.buildingId===kn.buildingId&&Ha!==qr&&(Ha.centroidXY=qr.centroidXY,Ls.writeCentroidToBuffer(Ha))}}for(const Mr of ps){if(zn.has(Mr))continue;const kn=B.featuresOnBorder[Mr],pr=B.centroidData.get(kn.centroidDataIndex),ta=kn.borders[Lt];let ka;for(;Tnta[0]+3||qr[0]>ta[0]-3)break;Ls.showCentroid(ka,"keep"),Tn++}if(ka&&Tnta[1]-3||(Jr++,++Tn===yn.length))break;ka=Ls.featuresOnBorder[yn[Tn]]}for(;qr=yn.length){B.showCentroid(kn,"keep");continue}ka=Ls.featuresOnBorder[yn[qr]];let si=!1;if(Jr>=1){const Hr=ka.borders[Bs];Math.abs(ta[0]-Hr[0])<3&&Math.abs(ta[1]-Hr[1])<3&&(Jr=1,si=!0,Tn=qr+1)}else if(Jr===0){B.showCentroid(kn,"keep");continue}const Gr=Ls.centroidData.get(ka.centroidDataIndex);oe&&si&&we(pr,Gr);const Sr=kn.intersectsCount()>1||ka.intersectsCount()>1;if(Jr>1)Tn=qr,pr.centroidXY=Gr.centroidXY=new o.P(0,0);else if(sn&&sn.dem&&!Sr){const Hr=ss[Lt](pr,Gr),Ha=Lt%2?o.a6-1:0,$r=Jt(Hr[0],Math.min(o.a6-1,Hr[1]),Ha,sn,Gs,Lt<2,Hr[2]);pr.centroidXY=Gr.centroidXY=Me($r)}else if(Sr){const Hr=Q?void 0:Xe(Lt,kn.borders,Bs,ka.borders);Hr!==void 0?(pr.centroidXY=Re(0,Lt,Hr),Gr.centroidXY=Re(0,Bs,Hr)):pr.centroidXY=Gr.centroidXY=new o.P(0,0)}else pr.centroidXY=B.encodeBorderCentroid(kn),Gr.centroidXY=Ls.encodeBorderCentroid(ka);B.writeCentroidToBuffer(pr),Ls.writeCentroidToBuffer(Gr)}else B.showCentroid(kn,"keep")}B.borderDoneWithNeighborZ[Lt]=Ls.canonical.z,Ls.borderDoneWithNeighborZ[Bs]=B.canonical.z}(B.needsCentroidUpdate||!B.centroidVertexBuffer&&B.centroidVertexArray.length!==0)&&B.uploadCentroid(L)}const on=[1,0,0],en=[0,1,0],tr=[0,0,1];function sr(L,k,T){const B=T.transform,K=T.shadowRenderer;if(!K)return!0;const Q=T.frameCounter,oe=T.currentShadowCascade;let he=T._shadowCullCache;if(!he||he.frame!==Q||he.cascade!==oe){const ss=B.tileSize*K._cascades[oe].scale,Jt=B.scaleZoom(ss),Lt=K.shadowDirection,ps=[Lt[0],Lt[1],-Lt[2]],Gs=[on,en,tr,ps,[ps[0],0,ps[2]],[0,ps[1],ps[2]]];he={frame:Q,cascade:oe,cameraFrustum:o.aA.fromInvProjectionMatrix(B.invProjMatrix,B.worldSize,Jt,B.projection.name!=="globe"),edges:Gs,shadowDir:ps,ws:ss,zoom:Jt},T._shadowCullCache=he}const{cameraFrustum:we,edges:Me,shadowDir:Re,ws:Ze,zoom:Xe}=he;let dt=k;if(B.elevation){const ss=B.elevation.getMinMaxForTile(L);ss&&(dt+=ss.max)}dt/=o.aB(B.center.lat,Xe);const _t=K.computeSimplifiedTileShadowVolume(L.toUnwrapped(),dt,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 Xr=new Float32Array(16),sa=new Float32Array(16);function $a(L){const{painter:k,source:T,layer:B,coords:K}=L;let Q=L.defines;const oe=k.context,he=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 Xe=B.paint.get("building-front-cutoff"),dt=Xe[2]<1&&!k.terrain,_t=Gt(k.transform.pitch,Xe,!!k.terrain);dt&&(Q=Q.concat("RENDER_FRONT_CUTOFF"),k.maxFrontCutoffRawStart=Math.max(k.maxFrontCutoffRawStart,Xe[0])),L.floodLightIntensity>0&&(Q=Q.concat("FLOOD_LIGHT"));for(const bt of K){const Mt=T.getTile(bt),ss=Mt.getBucket(B);if(!ss)continue;Me&&Me.getMaxCascadeForTile(bt.toUnwrapped())===0&&(Q=Q.concat("SHADOWS_SINGLE_CASCADE"));const Jt=ss.programConfigurations.get(B.id);let Lt,ps;const Gs=k.translatePosMatrix(bt.expandedProjMatrix,Mt,[0,0],"map");o.aO(Xr,Gs,[1,1,L.verticalScale]);const Ls=Xr;let sn;if(he&&Me){if(sr(Mt.tileID,ss.maxHeight*Re,k))continue;const nn=Me.calculateShadowPassMatrixFromTile(Mt.tileID.toUnwrapped());o.aO(nn,nn,[1,1,L.verticalScale]),sn=er(nn),Lt=ps=k.getOrCreateProgram("buildingDepth",{config:Jt,defines:Q,overrideFog:!1})}else if(we)Lt=ps=k.getOrCreateProgram("buildingBloom",{config:Jt,defines:Q,overrideFog:!1}),sn=Jn(Ls);else{const nn=k.transform.calculatePosMatrix(bt.toUnwrapped(),k.transform.worldSize);o.aO(nn,nn,[1,1,L.verticalScale]),o.aO(sa,nn,[1,-1,1/Re]),o.aP(sa,sa),o.aQ(sa,sa);const yn=sa,Tn=k.transform.getFreeCameraOptions().position,Gn=1<{if(we){const Tn=nn.entranceBloom;yn.draw(k,oe.gl.TRIANGLES,L.depthMode,o._.disabled,L.blendMode,o.$.disabled,sn,B.id,Tn.layoutVertexBuffer,Tn.indexBuffer,Tn.segmentsBucket,B.paint,k.transform.zoom,Jt,[Tn.layoutAttenuationBuffer,Tn.layoutColorBuffer])}else{const Tn=nn.segmentsBucket;let Gn=[nn.layoutNormalBuffer,nn.layoutCentroidBuffer,nn.layoutColorBuffer,nn.layoutFloodLightDataBuffer];nn.layoutFacadePaintBuffer&&(Gn=Gn.concat([nn.layoutFacadeDataBuffer,nn.layoutFacadeVerticalRangeBuffer,nn.layoutFacadePaintBuffer])),yn.draw(k,oe.gl.TRIANGLES,L.depthMode,o._.disabled,L.blendMode,he?o.$.disabled:o.$.backCW,sn,B.id,nn.layoutVertexBuffer,nn.indexBuffer,Tn,B.paint,k.transform.zoom,Jt,Gn)}};k.uploadCommonUniforms(oe,ps,bt.toUnwrapped(),null,Ze),ss.buildingWithoutFacade&&Bs(ss.buildingWithoutFacade,ps),ss.buildingWithFacade&&(Lt!==ps&&k.uploadCommonUniforms(oe,Lt,bt.toUnwrapped(),null,Ze),Bs(ss.buildingWithFacade,Lt))}}function Na(L,k,T,B,K,Q,oe,he,we,Me,Re,Ze,Xe,dt){const _t=L.context.gl,bt=L.depthModeForSublayer(1,o.Z.ReadOnly,_t.LEQUAL,!0),Mt=o.am(.1,3,Re),ss=L._showOverdrawInspector,Jt=Ze,Lt=new et;if(!ss){const ps=new o._({func:_t.ALWAYS,mask:255},255,255,_t.KEEP,_t.KEEP,_t.REPLACE),Gs=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,Gs,o.$.disabled,K,"sdf",Q,oe,he,we,Me,Mt,Jt,!1,void 0)}{const ps=ss?o._.disabled:new o._({func:_t.EQUAL,mask:255},255,255,_t.KEEP,_t.DECR,_t.DECR),Gs=ss?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,Gs,o.$.disabled,K,"color",Q,oe,he,we,Me,Mt,Jt,!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&&(oe=this._previousClosestBuildingId):Me&&!oe&&(oe=this._previousClosestBuildingId),this._previousClosestBuildingId=oe,oe}_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 oe=Q.geometry;if(oe.type==="Polygon"){const he=this._convertRingToPoints(oe.coordinates[0]);if(o.aU(he,B))return!0}else if(oe.type==="MultiPolygon"){const he=this._convertMultiPolygonToPoints(oe.coordinates);if(o.aV(B,he))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 eo=.05,xo=(L,k,T,B,K,Q,oe,he,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:oe,u_merc_center:he,u_cutoff_params:we}),io=(L,k,T,B,K,Q,oe,he,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:oe,u_uv_offset:he,u_data_scale:[255*we[0],255*we[1]],u_data_offset:Me,u_particle_pos_scale:1.1,u_particle_pos_offset:[eo,eo]}),Lo=(L,k,T,B,K,Q,oe,he,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:oe,u_rand_seed:Math.random(),u_uv_offset:he,u_data_scale:[255*we[0],255*we[1]],u_data_offset:Me,u_particle_pos_scale:1.1,u_particle_pos_offset:[eo,eo]});function Ul(L,[k,T,B,K],[Q,oe]){if(Q===oe)return[0,0,0,0];const he=255*(L-1)/(L*(oe-Q));return[k*he,T*he,B*he,K*he]}function fo(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 Pl{constructor(k,T,B,K){const Q={width:B[0],height:B[1],data:null},oe=k.gl;this.targetColorTexture=new o.T(k,Q,oe.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(k,Q,oe.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 oe=0;oe0){const Q=o.e.now(),oe=(Q-L.timeAdded)/K,he=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?oe:1-he,0,1);return k?{opacity:1,mix:1-Ze,isFading:oe<1}:{opacity:Ze,mix:0,isFading:oe<1}}return{opacity:1,mix:0,isFading:!1}}function au(L,k,T){if(!L)return null;const B=k.getTextureDescriptor(L,T,!0);if(!B)return null;let{texture:K,mix:Q,offset:oe,tileSize:he,buffer:we,format:Me}=B;if(!K||!Me)return null;let Re=!1;return Me==="uint32"&&(Re=!0,Q[3]=0,Q=Ul(o.ba,Q,[0,T.paint.get("raster-particle-max-speed")]),oe=fo(o.ba,oe,[0,T.paint.get("raster-particle-max-speed")])),{texture:K,textureOffset:[we/(he+2*we),he/(he+2*we)],tileSize:he,scalarData:Re,scale:Q,offset:oe,defines:["RASTER_ARRAY",{uint8:"DATA_FORMAT_UINT8",uint16:"DATA_FORMAT_UINT16",uint32:"DATA_FORMAT_UINT32"}[Me]]}}function Vt(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 Nn=`#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"]=Nn);var nr={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(Nn,"");const na=o.a$([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]),Wr=o.a$([{type:"Float32",name:"a_pos_2f",components:2}]);class Ca{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 oe=new o.bd,he=new o.ae;oe.emplaceBack(-1,-1),oe.emplaceBack(1,-1),oe.emplaceBack(1,1),oe.emplaceBack(-1,1),he.emplaceBack(0,1,2),he.emplaceBack(0,2,3),this.vignetteVx=k.context.createVertexBuffer(oe,Wr.members),this.vignetteIdx=k.context.createIndexBuffer(he)}const K=o.ad.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){k.uploadCommonUniforms(k.context,B);const oe={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,oe,"vignette",this.vignetteVx,this.vignetteIdx,K)}var Q}}class gi{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(k,T){const B=k.getFreeCameraOptions().position,K=B.toAltitude(),Q=B.toLngLat(),oe=o.av(Q.lng),he=o.av(Q.lat),we=k.pixelsPerMeter/T,Me=oe*o.bk,Re=o.bk*Math.log(Math.tan(Math.PI/4+he/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,Xe=-this._elevationPrev+K;this._accumulatedOffsetX+=(-this._offsetXPrev+Me)*we,this._accumulatedOffsetY+=Ze*we,this._accumulatedElevation+=Xe*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}),dm=(L,k)=>({u_matrix:L,u_ground_shadow_factor:k,u_opacity_multiplier:1}),Ad=(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}),fu={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 Zc(L,k){const T=1<0;--T){const B=Math.floor(k.x/(1<0;--Ze){const Xe=Math.floor(k.x/(1<he[Jt]!=bt>he[Jt]&&oe[Jt]B&&(Mt|=2),dtK&&(Mt|=8),_tB&&(ss|=2),btK&&(ss|=8),!(Mt&ss)&&(Mt===0||ss===0||Od(Xe,dt,_t,bt,k,T,B,K)))return!1}}for(let we=0;we<4;++we)if(!(1&Q[we]))return!1;return!0}function Od(L,k,T,B,K,Q,oe,he){const we=(Me,Re,Ze,Xe,dt,_t,bt,Mt)=>{const ss=(Ze-Me)*(_t-Re)-(Xe-Re)*(dt-Me),Jt=(Ze-Me)*(Mt-Re)-(Xe-Re)*(bt-Me);if(ss>0&&Jt>0||ss<0&&Jt<0)return!1;const Lt=(bt-dt)*(Re-_t)-(Mt-_t)*(Me-dt),ps=(bt-dt)*(Xe-_t)-(Mt-_t)*(Ze-dt);return!(Lt>0&&ps>0||Lt<0&&ps<0)};return!!(we(L,k,T,B,K,Q,oe,Q)||we(L,k,T,B,oe,Q,oe,he)||we(L,k,T,B,K,he,oe,he)||we(L,k,T,B,K,Q,K,he))}class ad{constructor(){this._tileCoverages=[],this._snapshot=new ih}clear(){this._tileCoverages=[]}addTileCoverage(k,T){this._tileCoverages.push({tileId:k,polygons:T,frcMask:rd(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 ih(k),this._snapshot}}function Ph(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(oe=>oe.id===Q)[0])),B.updateExpressions&&B.updateExpressions(K);for(const Q of K)T[Q.fqid]=B}}return T}const Hu=32,zd=33,dd=new Uint16Array(8184);for(let L=0;L<2046;L++){let k=L+2,T=0,B=0,K=0,Q=0,oe=0,he=0;for(1&k?K=Q=oe=Hu:T=B=he=Hu;(k>>=1)>1;){const Me=T+K>>1,Re=B+Q>>1;1&k?(K=T,Q=B,T=oe,B=he):(T=K,B=Q,K=oe,Q=he),oe=Me,he=Re}const we=4*L;dd[we+0]=T,dd[we+1]=B,dd[we+2]=K,dd[we+3]=Q}const zl=new Uint16Array(2178),Xi=new Uint8Array(1089),Ed=new Uint16Array(1089);function ou(L){return L===0?-.03125:L===32?.03125:0}var Xc=o.a$([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);const vd={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 Ap,Dv=0;class Px{constructor(k,T,B,K,Q,oe){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=oe,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=++Dv),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],oe=T.style.getOwnLayer(K);if(!oe)continue;const he=oe.queryRadius(Q)||0;this.queryPadding=Math.max(this.queryPadding,he)}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,...Ph(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 oe=this.buckets[Q];if(oe.uploadPending()){let he={},we=[],Me={zoom:0,pitch:0,brightness:0,worldview:""};if(T){if(T.style){we=T.style.listImages();const Re=oe.layers[0],Ze=Re.sourceLayer||"_geojsonTileLayer",Xe=T.style.getLayerSourceCache(Re);Xe&&(he=Xe._state.getState(Ze,void 0))}Me={zoom:T.transform.zoom||0,pitch:T.transform.pitch||0,brightness:T.style.getBrightness()||0,worldview:T.worldview||""}}oe.upload(k,this.tileID.canonical,he,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 Xe=T.style.getLut(B);this.imageAtlas.patchUpdatedImages(k,this.imageAtlasTexture,B,Xe)}if(!T||!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData)return;const K=T.style.getBrightness(),Q=T.style.listImages(),oe=Q.length,he=T.style._changes.getUpdatedPaintProperties(),we=Object.keys(this.buckets).some(Xe=>this.buckets[Xe].layers.some(dt=>he.has(dt.fqid))),Me=Object.keys(this.buckets).some(Xe=>this.buckets[Xe].layers.some(dt=>dt.hasTransition&&dt.hasTransition())),Re=this._firstPrepareComplete&&oe!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(T));const Ze=this._lastUpdatedBrightness!==K;this._lastAvailableImagesCount=oe,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,he,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,oe,he){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const we=this.evaluateQueryRenderedFeaturePadding(),Me=function(Re,Ze){const Xe=o.bM([],[.5*Re.width,.5*-Re.height,1]);return o.bN(Xe,Xe,[1,-1,0]),o.X(Xe,Xe,Re.calculateProjMatrix(Ze.toUnwrapped())),Float32Array.from(Xe)}(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:he})}querySourceFeatures(k,T){const B=this.latestFeatureIndex;if(!B||!B.rawTileData)return;const K=B.loadVTLayers(),Q=T?T.sourceLayer:"",oe=K._geojsonTileLayer||K[Q];if(!oe)return;const he=o.bw(T&&T.filter),{z:we,x:Me,y:Re}=this.tileID.canonical,Ze={z:we,x:Me,y:Re};for(let Xe=0;XeB)K=!1;else if(T)if(this.expirationTimeB.appearances&&B.appearances.length>0))return!0;return!1}updateBuckets(k,T,B,K,Q,oe){if(!this.latestFeatureIndex||!k.style)return;const he=oe||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],Xe=Ze.layers[0],dt=Xe.sourceLayer||"_geojsonTileLayer",_t=k.style.getLayerSourceCache(Xe),bt=Ze.layers.some(Ls=>Me.has(Ls.fqid)),Mt=(K||bt)&&Ze instanceof o.bv?k.style.getOwnLayer(Re):void 0;let ss=B&&B[dt]||{};_t&&!B&&(ss=_t._state.getState(dt,void 0));const Jt=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},Lt=Object.keys(ss).length>0&&!T;Ze.hasAppearances=Ze.layers.some(Ls=>Ls.appearances&&Ls.appearances.length>0);const ps=Lt?Ze.stateDependentLayers:Ze.layers;if(Lt&&Ze.stateDependentLayers.length!==0||T||bt||K){const Ls=this.latestFeatureIndex.loadVTLayers()[dt];if(Ze.update(ss,Ls,he,Jt,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 sn=Ze;sn.text&&sn.text.uboBinder&&sn.text.uboBinder.updateDynamicExpressions(Mt,Ls,this.tileID.canonical,he,ss,we),sn.icon&&sn.icon.uboBinder&&sn.icon.uboBinder.updateDynamicExpressions(Mt,Ls,this.tileID.canonical,he,ss,we)}if(Ze instanceof o.bv){const sn=Ze,Bs=k.context;sn.text&&sn.text.uboBinder&&sn.text.uboBinder.upload(Bs),sn.icon&&sn.icon.uboBinder&&sn.icon.uboBinder.upload(Bs)}}if(Lt&&Ze.stateDependentLayers.length!==0||T||Ze.hasAppearances){const Ls={zoom:k.transform.zoom,pitch:k.transform.pitch,brightness:k.style.getBrightness()||0,worldview:k.worldview},sn=Ze.updateAppearances(this.tileID.canonical,ss,he,Ls,k.imageManager,Lt&&Ze.stateDependentLayers.length!==0);if(sn&&sn.hasUboChanges){const Bs=k.context;Ze instanceof o.bv&&Ze.text&&Ze.text.uboBinder&&Ze.text.uboBinder.upload(Bs),Ze instanceof o.bv&&Ze.icon&&Ze.icon.uboBinder&&Ze.icon.uboBinder.upload(Bs)}}(Ze instanceof o.bA||Ze instanceof o.bB)&&k._terrain&&k._terrain.enabled&&_t&&Ze.uploadPending()&&k._terrain._clearRenderCacheForTile(_t.id,this.tileID);const Gs=k&&k.style&&k.style.getOwnLayer(Re);Gs&&(this.queryPadding=Math.max(this.queryPadding,Gs.queryRadius(Ze)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;Mt--){const ss=4*Mt,Jt=dd[ss+0],Lt=dd[ss+1],ps=dd[ss+2],Gs=dd[ss+3],Ls=Jt+ps>>1,sn=Lt+Gs>>1,Bs=Ls+sn-Lt,nn=sn+Jt-Ls,yn=Lt*zd+Jt,Tn=Gs*zd+ps,Gn=sn*zd+Ls,zn=Math.hypot((zl[2*yn+0]+zl[2*Tn+0])/2-zl[2*Gn+0],(zl[2*yn+1]+zl[2*Tn+1])/2-zl[2*Gn+1])>=16;Xi[Gn]=Xi[Gn]||(zn?1:0),Mt<1022&&(Xi[Gn]=Xi[Gn]||Xi[(Lt+nn>>1)*zd+(Jt+Bs>>1)]||Xi[(Gs+nn>>1)*zd+(ps+Bs>>1)])}const Ze=new o.bt,Xe=new o.ae;let dt=0;function _t(Mt,ss){const Jt=ss*zd+Mt;return Ed[Jt]===0&&(Ze.emplaceBack(zl[2*Jt+0],zl[2*Jt+1],Mt*o.a6/Hu,ss*o.a6/Hu),Ed[Jt]=++dt),Ed[Jt]-1}function bt(Mt,ss,Jt,Lt,ps,Gs){const Ls=Mt+Jt>>1,sn=ss+Lt>>1;if(Math.abs(Mt-ps)+Math.abs(ss-Gs)>1&&Xi[sn*zd+Ls])bt(ps,Gs,Mt,ss,Ls,sn),bt(Jt,Lt,ps,Gs,Ls,sn);else{const Bs=_t(Mt,ss),nn=_t(Jt,Lt),yn=_t(ps,Gs);Xe.emplaceBack(Bs,nn,yn)}}return bt(0,0,Hu,Hu,Hu,0),bt(Hu,Hu,0,0,0,Hu),{vertices:Ze,indices:Xe}}(this.tileID.canonical,T);K=oe.vertices,Q=oe.indices}else{K=new o.bt,Q=new o.ae;for(const{x:he,y:we}of B)K.emplaceBack(he,we,0,0);const oe=o.bG(K.int16.subarray(0,4*K.length),void 0,4);for(let he=0;he0&&(we=o.aP(new Float64Array(16),T.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(k,K,T,oe,we,he),this._makeGlobeTileDebugTextBuffer(k,K,T,oe,we,he)}_globePoint(k,T,B,K,Q,oe,he){let we=o.bH(k,T,B);if(oe){const Me=1<.5?dt=-1:Xe<-.5&&(dt=1);let _t=(k/o.a6+B.x)/Me+dt,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,oe),we=o.bJ(we,Mt,he)}return o.bI(we,we,Q)}_makeGlobeTileDebugBorderBuffer(k,T,B,K,Q,oe){const he=new o.bD,we=new o.bE,Me=new o.bK,Re=(Xe,dt,_t,bt,Mt)=>{const ss=(_t-Xe)/(Mt-1),Jt=(bt-dt)/(Mt-1),Lt=he.length;for(let ps=0;psZe*dt+_t;for(let dt=0;dt{this.remove(k,Q)},B)),this.data[K].push(Q),this.order.push(K),this.order.length>this.max){const oe=this._getAndRemoveByKey(this.order[0]);oe&&this.onRemove(oe)}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 Ky{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 he=String(T),we=Object.assign(Object.create(null),B[he],K[he]);if(Q){const Me=Q[T];if(Me===null)return Object.create(null);for(const Re in Me)delete we[Re]}return we}const oe=Object.assign(Object.create(null),B,K);if(Q)for(const he in Q)delete oe[he];return oe}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 oe in this.stateChanges[K])this.state[K][oe]||(this.state[K][oe]=Object.create(null)),Object.assign(this.state[K][oe],this.stateChanges[K][oe]),Q[oe]=this.state[K][oe];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 oe in this.state[K])Q[oe]=Object.create(null),this.state[K][oe]=Object.create(null);else for(const oe in this.deletedStates[K]){if(this.deletedStates[K][oe]===null)this.state[K][oe]=Object.create(null);else if(this.state[K][oe])for(const he of Object.keys(this.deletedStates[K][oe]))delete this.state[K][oe][he];Q[oe]=this.state[K][oe]}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 Ky,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(Wg).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 oe=K.tileID,he=Q.tileID,we=new o.P(oe.canonical.x,oe.canonical.y)._rotate(this.transform.angle),Me=new o.P(he.canonical.x,he.canonical.y)._rotate(this.transform.angle);return oe.overscaledZ-he.overscaledZ||Me.y-we.y||Me.x-we.x}).map(K=>K.tileID.key):B.map(K=>K.tileID).sort(Wg).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 he=this.map.painter.terrain;this.update(this.transform,he.getScaledDemTileSize(),!0),he.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 oe=new Headers;Q&&Q.headers&&(oe=Q.headers),this._source.fire(new o.h("data",{dataType:"source",tile:k,coord:k.tileID,sourceCacheId:this.id,responseHeaders:oe}))}_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(oe)>1&&(Math.abs(oe+we)===1?oe+=we:Math.abs(oe-we)===1&&(oe-=we)),Q.dem&&K.dem&&(K.dem.backfillBorder(Q.dem,oe,he),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 oe in this._tiles){let he=this._tiles[oe];if(K[oe]||!he.hasData()||he.tileID.overscaledZ<=T||he.tileID.overscaledZ>B||Q&&he.parentTile)continue;let we=he.tileID;for(;he&&he.tileID.overscaledZ>T+1;){const Re=he.tileID.scaledTo(he.tileID.overscaledZ-1);he=this._tiles[Re.key],he&&he.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),oe=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,Q):Q,he=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,oe):oe;this._cache.setMaxSize(he)}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 oe=this._source.type==="batched-model";let he,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 dt=Me.attenuationRange()[0],_t=Math.floor(dt)-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)he=k.getVisibleUnwrappedCoordinates(this._source.tileID).map(dt=>new o.bQ(dt.canonical.z,dt.wrap,dt.canonical.z,dt.canonical.x,dt.canonical.y));else if(this.tileCoverLift!==0){const dt=k.clone();dt.tileCoverLift=this.tileCoverLift,he=dt.coveringTiles({tileSize:T||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:we,roundZoom:this._source.roundZoom&&!B,reparseOverscaled:Re,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:oe}),this._source.minzoom<=1&&k.projection.name==="globe"&&(he.push(new o.bQ(1,0,1,0,0)),he.push(new o.bQ(1,0,1,1,0)),he.push(new o.bQ(1,0,1,0,1)),he.push(new o.bQ(1,0,1,1,1)))}else if(he=k.coveringTiles({tileSize:T||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:we,roundZoom:this._source.roundZoom&&!B,reparseOverscaled:Re,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:oe}),this._source.hasTile){const dt=this._source.hasTile.bind(this._source);he=he.filter(_t=>dt(_t))}}else he=[];if(he.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const dt=k.coveringZoomLevel({tileSize:T||this._source.tileSize,roundZoom:this._source.roundZoom&&!B}),_t=Math.min(dt,we);if(oe){const bt=k.extendTileCover(he,_t);for(const Mt of bt)he.push(Mt)}else if(Q){const bt=this.transform.getFrustum(_t),Mt=k.extendTileCoverToNearPlane(he,bt,_t);for(const ss of Mt)he.push(ss);if(_t>=18&&this._hasTunnelGeometry()){const ss=k.extendTileCoverForTunnels(he,bt,_t,20);for(const Jt of ss)he.push(Jt)}}else if(this.castsShadows&&K){const bt=k.extendTileCover(he,_t,K,16);for(const Mt of bt)this._shadowCasterTiles[Mt.key]=!0,he.push(Mt)}}for(const dt in this._tiles){const _t=this._tiles[dt];_t.dashIdealZ=_t.tileID.overscaledZ}const Ze=this._updateRetainedTiles(he);if(this._supportsFading&&he.length!==0){const dt={},_t={},bt=o.e.now(),Mt=Object.keys(Ze);for(const Jt of Mt){const Lt=Ze[Jt],ps=this._tiles[Jt];if(!ps||ps.fadeEndTime!==void 0&&ps.fadeEndTime<=bt)continue;const Gs=this.findLoadedParent(Lt,Math.max(Lt.overscaledZ-Ci.maxOverzooming,this._source.minzoom));Gs&&(this._addTile(Gs.tileID),dt[Gs.tileID.key]=Gs.tileID),_t[Jt]=Lt}const ss=he.at(-1).overscaledZ;for(const Jt in this._tiles){const Lt=this._tiles[Jt];if(Ze[Jt]||!Lt.hasData())continue;let ps=Lt.tileID;for(;ps.overscaledZ>ss;){ps=ps.scaledTo(ps.overscaledZ-1);const Gs=this._tiles[ps.key];if(Gs&&Gs.hasData()&&_t[ps.key]){Ze[Jt]=Lt.tileID;break}}}for(const Jt in dt)Ze[Jt]||(this._coveredTiles[Jt]=!0,Ze[Jt]=dt[Jt])}for(const dt in Ze)this._tiles[dt].clearFadeHold();const Xe=o.bR(this._tiles,Ze);for(const dt of Xe){const _t=this._tiles[dt];_t.hasSymbolBuckets&&!_t.holdingForFade()?_t.setHoldDuration(this.map._fadeDuration):_t.hasSymbolBuckets&&!_t.symbolFadeFinished()||this._removeTile(+dt)}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,oe=Math.max(Q-Ci.maxOverzooming,this._source.minzoom),he=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 Xe=Me.children(this._source.maxzoom)[0],dt=this.getTile(Xe);if(dt&&dt.hasData()){T[Xe.key]=Xe,dt.dashIdealZ=Me.overscaledZ;continue}}else{const Xe=Me.children(this._source.maxzoom);if(T[Xe[0].key]&&T[Xe[1].key]&&T[Xe[2].key]&&T[Xe[3].key])continue}let Ze=Re.wasRequested();for(let Xe=Me.overscaledZ-1;Xe>=oe;--Xe){const dt=Me.scaledTo(Xe);if(B[dt.key]||(B[dt.key]=!0,Re=this.getTile(dt),!Re&&Ze&&(Re=this._addTile(dt)),Re&&(T[dt.key]=dt,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(oe,he,we,Me,Re){if(!Ap)throw new Error("Raster-array module is not loaded.");return Ap(oe,he,we,Me,Re)}(k,Q,this.transform.tileZoom,K,this._isRaster):new Px(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 oe=Q.projection.name==="globe",he=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(oe){const Xe=Re.tileID.canonical;if(Xe.z===0){const dt=[Math.abs(o.b1(he,...Om(Xe,-1))-he),Math.abs(o.b1(he,...Om(Xe,1))-he)];Ze=[0,2*dt.indexOf(Math.min(...dt))-1]}else{const dt=[Math.abs(o.b1(he,...Om(Xe,-1))-he),Math.abs(o.b1(he,...Om(Xe,0))-he),Math.abs(o.b1(he,...Om(Xe,1))-he)];Ze=[dt.indexOf(Math.min(...dt))-1]}}else Ze=[0];for(const Xe of Ze){const dt=k.containsTile(Re,Q,T,Xe,we);dt&&K.push(dt)}}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 oe of T){const he=1/(1<Q[oe.key]-Q[he.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,oe=this.usedForTerrain&&Q?Q.getScaledDemTileSize():this._source.tileSize;for(const we of K){const Me=we.coveringTiles({tileSize:oe,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 he=Array.from(B.values());o.bU(he,(we,Me)=>{const Re=new Px(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 Wg(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 Om(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 Gu(L,k){return L.sourceFQID!==k.sourceFQID?L.sourceFQID{return!!he.hasDeferredElevationFeatures||oe&&(we=K,kl(B,Me=he.tileID.canonical)!==kl(we,Me));var we,Me})}const gu=L=>({u_matrix:L});function R_(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 Fv(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 Lx(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 Mb(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 oe of k){const he=Lx(L,oe);if(!he)continue;const we=he.buffers.frcLevelSegments[T];we&&Q.draw(L,K.TRIANGLES,o.Z.disabled,new o._({func:K.EQUAL,mask:255},L._tileClippingMaskIDs[oe.key]||0,255,K.KEEP,K.KEEP,K.INVERT),o.a1.disabled,o.$.disabled,gu(he.projMatrix),`$frc_coverage_${T}`,he.buffers.vertexBuffer,he.buffers.indexBuffer,we)}}function Ww(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 oe of k){const he=Lx(L,oe);if(!he)continue;const we=he.buffers.frcLevelSegments[T];we&&Q.draw(L,K.TRIANGLES,o.Z.disabled,new o._({func:K.EQUAL,mask:255},255&~(L._tileClippingMaskIDs[oe.key]||0),255,K.KEEP,K.KEEP,K.INVERT),o.a1.disabled,o.$.disabled,gu(he.projMatrix),`$frc_coverage_restore_${T}`,he.buffers.vertexBuffer,he.buffers.indexBuffer,we)}}function zm(L,k,T,B,K){if(k.length===0)return;let Q=0;for(const he of k)Q|=he.frcMask;const oe=k.map(he=>he.coord);for(let he=0;he<9;++he)if(Q&1<0&&K)for(const we of k)we.frcMask&1<0&&k.rings[0].length>0)return!0;return!1}function Ih(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 yh={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()),Xe=L.style.order.indexOf(T.fqid);if(function(dt,_t,bt,Mt,ss,Jt){for(const Lt of Jt){const ps=_t.getTile(Lt).getBucket(bt);ps&&(ss&&ps.updateReplacement(Lt,dt.replacementSource,Mt),ps.uploadUpdatedIndexBuffer(dt.context))}}(L,k,T,Xe,Ze,B),function(dt,_t,bt,Mt){for(const ss of Mt){const Jt=_t.getTile(ss).getBucket(bt);Jt&&Jt.needsEvaluation()&&Jt.uploadUpdatedColorBuffer(dt.context)}}(L,k,T,B),T.resetLayerRenderingStats(L),L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!0),L.renderPass==="shadow"&&L.shadowRenderer){const dt=[],_t=L.shadowRenderer.getShadowPassDepthMode();$a({painter:L,source:k,layer:T,coords:B,defines:dt,blendMode:o.a1.disabled,depthMode:_t,opacity:he,verticalScale:Re,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(L.renderPass==="translucent"){let dt=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];Me&&(dt=dt.concat("RENDER_SHADOWS")),L.shadowRenderer&&L.shadowRenderer.useNormalOffset&&(dt=dt.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"),ss=T.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",Jt=T.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(ss?null:T.lut).toArray01().slice(0,3),Lt=T.paint.get("building-flood-light-ground-attenuation"),ps=Mt>0,Gs=new o.Z(L.context.gl.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D);he<1&&$a({painter:L,source:k,layer:T,coords:B,defines:dt,blendMode:o.a1.disabled,depthMode:Gs,opacity:he,verticalScale:Re,facadeEmissiveChance:_t,facadeAOIntensity:bt,floodLightIntensity:Mt,floodLightColor:Jt,depthOnly:!0});const Ls=L.colorModeForRenderPass();$a({painter:L,source:k,layer:T,coords:B,defines:dt,blendMode:Ls,depthMode:Gs,opacity:he,verticalScale:Re,facadeEmissiveChance:_t,facadeAOIntensity:bt,floodLightIntensity:Mt,floodLightColor:Jt});const sn=T.paint.get("building-front-cutoff");Gt(L.transform.pitch,sn,!!L.terrain),we&&Na(L,k,T,B,!0,he,K,Q,Mt,Jt,oe,Ze),ps&&Na(L,k,T,B,!1,he,K,Q,Mt,Jt,Lt,Ze)}else if(L.renderPass==="light-beam"){const dt=["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:dt,blendMode:o.a1.alphaBlended,depthMode:_t,opacity:he,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 he of K){const we=L.getTile(he);if(!we.hasData())continue;const Me=we.getBucket(k);Me&&(Me.isEmpty()||(T.push(he.key),B.push({bucket:Me,tileID:he.canonical})))}let Q=T.length!==this.visibleTiles.length;if(!Q){T.sort();for(let he=0;hehe.tileID.z-we.tileID.z||he.tileID.x-we.tileID.x||he.tileID.y-we.tileID.y);for(const he of B){const we=new Array,Me=new Array,Re=he.bucket;for(const Ze of Re.featuresOnBorder)Re.footprints[Ze.footprintIndex].hiddenFlags&o.aS||(oe.has(Ze.featureId)?Me.push(Ze.footprintIndex):(oe.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(oe,he,we,Me){if(!Me.length)return;const Re=oe.context,Ze=Re.gl,Xe=he.getSource();if(Xe.type!=="raster-array")return;const dt=Math.ceil(Math.sqrt(we.paint.get("raster-particle-count")));let _t=we.particlePositionRGBAImage;if(!_t||_t.width!==dt){const Lt=function(ps){const Gs=ps*ps,Ls=new Uint8Array(4*Gs),sn=.9090909090909091;for(let Bs=0;Bso.aC[qr](zn));pr.push(zn);const ta=zn.canonical.x,ka=zn.canonical.y;for(const qr of pr){const Jr=ps.getTile(yn?qr.wrapped():qr);if(!Jr)continue;const si=Jr.rasterParticleState;if(!si)continue;const Gr=qr.canonical.x+(1<k.getTileByID(he));for(const he of oe)he.updateNeeded(L.id,Q)&&(he._isHeaderLoaded||he.parentTile)&&B.prepareTile(he,K,L.id,Q)},Rain:class extends Pc{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 oe=o.bj(1323123451230);for(let he=0;heoe)return;const he=zo(0,1,B.revealStart,B.revealStart+B.revealRange,oe);if(!this.particlesVx||!this.particlesIdx)return;Q.strength*=he;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 Xe=L.getOrCreateProgram("rainParticle");L.uploadCommonUniforms(Me,Xe),Me.activeTexture.set(Re.TEXTURE0),this.screenTexture.bind(Re.LINEAR,Re.CLAMP_TO_EDGE);const dt=[T.color.r,T.color.g,T.color.b,T.color.a],_t=(bt,Mt)=>{const ss=Ia(this._movement.getPosition(),bt),Jt=T.dropletSizeX,Lt=T.dropletSizeX*T.dropletSizeYScale,ps=L.width/2,Gs=L.height/2,Ls=zo(0,T.screenThinning.start,0,1,T.screenThinning.intensity),sn=zo(.001,T.screenThinning.range,0,1,T.screenThinning.intensity),Bs=zo(0,T.screenThinning.particleOffset,0,1,T.screenThinning.intensity),nn=(yn={modelview:we.modelviewMatrix,projection:we.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:ss,velocityConeAperture:T.velocityConeAperture,velocity:T.velocity,boxSize:bt,rainDropletSize:[Jt,Lt],distortionStrength:T.distortionStrength,rainDirection:K,color:dt,screenSize:[Ze.width,Ze.height],thinningCenterPos:[ps,Gs],thinningShape:[Ls,sn,Math.pow(10,T.screenThinning.fadePower)],thinningAffectedRatio:T.screenThinning.affectedRatio,thinningParticleOffset:Bs,shapeDirectionalPower:T.shapeDirPower,shapeNormalPower:T.shapeNormalPower,mode:Mt?0:1},{u_modelview:Float32Array.from(yn.modelview),u_projection:Float32Array.from(yn.projection),u_time:yn.time,u_cam_pos:yn.camPos,u_texScreen:0,u_velocityConeAperture:yn.velocityConeAperture,u_velocity:yn.velocity,u_boxSize:yn.boxSize,u_rainDropletSize:yn.rainDropletSize,u_distortionStrength:yn.distortionStrength,u_rainDirection:yn.rainDirection,u_color:yn.color,u_screenSize:yn.screenSize,u_thinningCenterPos:yn.thinningCenterPos,u_thinningShape:yn.thinningShape,u_thinningAffectedRatio:yn.thinningAffectedRatio,u_thinningParticleOffset:yn.thinningParticleOffset,u_shapeDirectionalPower:yn.shapeDirectionalPower,u_shapeNormalPower:yn.shapeNormalPower,u_mode:yn.mode});var yn;const Tn=Math.round(T.intensity*this.particlesCount),Gn=o.ad.simpleSegment(0,0,4*Tn,2*Tn);Xe.draw(L,Re.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.alphaBlended,o.$.disabled,nn,"rain_particles",this.particlesVx,this.particlesIdx,Gn)};T.distortionStrength>0&&_t(T.boxSize,!0),_t(T.boxSize,!1),this._vignette.draw(L,Q)}},Snow:class extends Pc{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 oe=o.bj(1323123451230);for(let he=0;heoe)return;const he=zo(0,1,B.revealStart,B.revealStart+B.revealRange,oe);Q.strength*=he;const we=this.updateOnRender(L,T.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const Me=L.context,Re=Me.gl,Ze=L.transform,Xe=L.getOrCreateProgram("snowParticle");L.uploadCommonUniforms(Me,Xe),((dt,_t,bt)=>{const Mt=Ia(this._movement.getPosition(),dt),ss=Ze.width/2,Jt=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),Gs=zo(0,bt.screenThinning.particleOffset,0,1,bt.screenThinning.intensity),Ls=(sn={modelview:we.modelviewMatrix,projection:we.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:Mt,velocityConeAperture:bt.velocityConeAperture,velocity:bt.velocity,horizontalOscillationRadius:bt.horizontalOscillationRadius,horizontalOscillationRate:bt.horizontalOscillationRate,boxSize:dt,billboardSize:1*bt.billboardSize,simpleShapeParameters:[bt.shapeFadeStart,bt.shapeFadePower],screenSize:[Ze.width,Ze.height],thinningCenterPos:[ss,Jt],thinningShape:[Lt,ps,Math.pow(10,bt.screenThinning.fadePower)],thinningAffectedRatio:bt.screenThinning.affectedRatio,thinningParticleOffset:Gs,color:[bt.color.r,bt.color.g,bt.color.b,bt.color.a],direction:K},{u_modelview:Float32Array.from(sn.modelview),u_projection:Float32Array.from(sn.projection),u_time:sn.time,u_cam_pos:sn.camPos,u_velocityConeAperture:sn.velocityConeAperture,u_velocity:sn.velocity,u_horizontalOscillationRadius:sn.horizontalOscillationRadius,u_horizontalOscillationRate:sn.horizontalOscillationRate,u_boxSize:sn.boxSize,u_billboardSize:sn.billboardSize,u_simpleShapeParameters:sn.simpleShapeParameters,u_screenSize:sn.screenSize,u_thinningCenterPos:sn.thinningCenterPos,u_thinningShape:sn.thinningShape,u_thinningAffectedRatio:sn.thinningAffectedRatio,u_thinningParticleOffset:sn.thinningParticleOffset,u_particleColor:sn.color,u_direction:sn.direction});var sn;const Bs=Math.round(bt.intensity*this.particlesCount),nn=o.ad.simpleSegment(0,0,4*Bs,2*Bs);this.particlesVx&&this.particlesIdx&&Xe.draw(L,Re.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.alphaBlended,o.$.disabled,Ls,"snow_particles",this.particlesVx,this.particlesIdx,nn)})(T.boxSize,0,T),this._vignette.draw(L,Q)}},shaders:nr,programUniforms:fu,drawElevatedStructures:function(L){const{painter:k,sourceCache:T,layer:B,coords:K,colorMode:Q}=L,oe=k.context.gl,he=L.painter.shadowRenderer,we=!!he&&he.enabled,Me=new o.Z(k.context.gl.LEQUAL,o.Z.ReadOnly,k.depthRangeFor3D);let Re=[0,0,0];if(we){const Xe=k.style.directionalLight,dt=k.style.ambientLight;Xe&&dt&&(Re=o.aG(k.style,Xe,dt))}const Ze=Xe=>{for(const dt of K){const _t=T.getTile(dt),bt=_t.getBucket(B);if(!bt)continue;const Mt=bt.hdExt?bt.hdExt.elevatedStructures:void 0;if(!Mt)continue;let ss,Jt;if(Xe?(ss=Mt.renderableBridgeSegments,Jt=Mt.bridgeProgramConfigurations.get(B.id)):(ss=Mt.renderableTunnelSegments,Jt=Mt.tunnelProgramConfigurations.get(B.id)),!ss||ss.segments[0].primitiveLength===0)continue;Jt.updatePaintBuffers(),k.prepareDrawTile();const Lt=k.isTileAffectedByFog(dt),ps=[];we&&ps.push("RENDER_SHADOWS","NORMAL_OFFSET");const Gs=k.getOrCreateProgram("elevatedStructures",{config:Jt,overrideFog:Lt,defines:ps}),Ls=k.translatePosMatrix(dt.projMatrix,_t,B.paint.get("fill-translate"),B.paint.get("fill-translate-anchor"));we&&he.setupShadows(_t.tileID.toUnwrapped(),Gs,"vector-tile");const sn=dm(Ls,Re);k.uploadCommonUniforms(k.context,Gs,dt.toUnwrapped()),Gs.draw(k,oe.TRIANGLES,Me,o._.disabled,Q,o.$.backCCW,sn,B.id,Mt.vertexBuffer,Mt.indexBuffer,ss,B.paint,k.transform.zoom,Jt,[Mt.vertexBufferNormal])}};Ze(!0),Ze(!1)},drawElevatedFillShadows:function(L){const{painter:k,sourceCache:T,layer:B,coords:K}=L,Q=k.context.gl,oe=L.painter.shadowRenderer;for(const he of K){const we=T.getTile(he),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),Xe=k.isTileAffectedByFog(he),dt=k.getOrCreateProgram("elevatedStructuresDepth",{config:Ze,overrideFog:Xe}),_t=oe.calculateShadowPassMatrixFromTile(we.tileID.toUnwrapped());k.uploadCommonUniforms(k.context,dt,he.toUnwrapped());const bt=iu(_t,0);dt.draw(k,Q.TRIANGLES,oe.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,oe=new o.Z(L.context.gl.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D),he=new o.Z(L.context.gl.GREATER,o.Z.ReadWrite,L.depthRangeFor3D),we=function(Xe){let dt=.01;return Xe.isOrthographic&&(dt=o.am(1e-4,dt,o.bp(Xe.pitch>=o.bo?1:Xe.pitch/o.bo))),2*dt}(L.transform),Me=L.transform.getFreeCameraOptions().position,Re="elevatedStructuresDepthReconstruct";let Ze;for(const Xe of B){const dt=k.getTile(Xe),_t=dt.getBucket(T);if(!_t||!_t.hdExt)continue;const bt=_t.hdExt.elevatedStructures,Mt=_t.hdExt.elevationBufferData;if(!bt||!bt.depthSegments||!Mt)continue;const ss=Mt.heightRange,Jt=Zc(Xe.toUnwrapped(),Me),Lt=L.translatePosMatrix(Xe.projMatrix,dt,T.paint.get("fill-translate"),T.paint.get("fill-translate-anchor"));let ps,Gs,Ls;if(K==="initialize"){if(!ss||ss.min>=1||bt.depthSegments.segments[0].primitiveLength===0)continue;ps=Ad(Lt,Jt,we,1,0),Gs=oe,Ls=bt.depthSegments,Ze=Ze||L.getOrCreateProgram(Re,{defines:["DEPTH_RECONSTRUCTION"]})}else if(K==="reset"){if(!ss||ss.min>=0||bt.maskSegments.segments[0].primitiveLength===0)continue;ps=Ad(Lt,Jt,0,0,1),Gs=he,Ls=bt.maskSegments,Ze=Ze||L.getOrCreateProgram(Re,{defines:["DEPTH_RECONSTRUCTION"]})}else if(K==="geometry"){if(bt.depthSegments.segments[0].primitiveLength===0)continue;ps=Ad(Lt,Jt,we,1,0),Gs=oe,Ls=bt.depthSegments,Ze=Ze||L.getOrCreateProgram(Re)}Ze.draw(L,Q.TRIANGLES,Gs,o._.disabled,o.a1.disabled,o.$.disabled,ps,T.id,bt.vertexBuffer,bt.indexBuffer,Ls,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),oe=new o._({func:K.ALWAYS,mask:255},255,255,K.KEEP,K.KEEP,K.REPLACE),he=L.transform.getFreeCameraOptions().position;let we;for(const Me of B){const Re=k.getTile(Me),Ze=Re.getBucket(T);if(!Ze)continue;const Xe=Ze.hdExt?Ze.hdExt.elevatedStructures:void 0;if(!Xe||!Xe.depthSegments||Xe.depthSegments.segments[0].primitiveLength===0)continue;const dt=Zc(Me.toUnwrapped(),he),_t=L.translatePosMatrix(Me.projMatrix,Re,T.paint.get("fill-translate"),T.paint.get("fill-translate-anchor"));we=we||L.getOrCreateProgram("elevatedStructuresDepthReconstruct");const bt=Ad(_t,dt,0,1,0);we.draw(L,K.TRIANGLES,Q,oe,o.a1.disabled,o.$.disabled,bt,T.id,Xe.vertexBuffer,Xe.indexBuffer,Xe.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,oe)=>oe.zIndex-Q.zIndex).filter((Q,oe,he)=>oe===0||Q.zIndex!==he[oe-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 ad}},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 oe=K[Q];if(!oe||!oe.loaded())continue;const he=oe.frcCoveragePolygons;k.manager.addTileCoverage(oe.tileID.canonical,he&&he.length>0?he:[])}}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 oe=K[Q];for(const he in oe._tiles){const we=oe._tiles[he];we&&we.hasDeferredRoadStructure&&(we.hasDeferredRoadStructure=!1,oe._reloadTile(+he,"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),oe=L._sourceCaches[K]=new Ci(Q,B,o.bS.HdRoadCoverage);k.coverageSourceCaches[T.source]=oe,oe.setMaxzoomOverride(14),oe.onAdd(L.map);const he=L._otherSourceCaches[T.source];he&&he._sourceLoaded&&(oe._sourceLoaded=!0)},updateFrcCoverageFadeRange:function(L,k){let T=null,B=null;const K={globals:{zoom:0}};L.forEachFragmentStyle(Q=>{if(T)return;const oe=Q.stylesheet?Q.stylesheet.schema:null;if(!oe||!oe.sdCoverageFadeRange)return;const he=o.m("sdCoverageFadeRange",Q.scope),we=Q.options?Q.options.get(he):void 0,Me=we?we.value||we.default:null;if(Me){const dt=Me.evaluate(K);Array.isArray(dt)&&dt.length===2&&(dt[0]>0||dt[1]>0)&&(T=[dt[0],dt[1]])}const Re=o.m("sdCoverageSourceLayers",Q.scope),Ze=Q.options?Q.options.get(Re):void 0,Xe=Ze?Ze.value||Ze.default:null;if(Xe){const dt=Xe.evaluate(K);Array.isArray(dt)&&dt.length>0&&(B=dt)}else{const dt=L.stylesheet&&L.stylesheet.imports||[];for(const _t of dt)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:B0,setupAndUpdateElevationCoverage:function(L){if(!function(K){for(const Q in K._mergedLayers)if(Ao(K._mergedLayers[Q]))return!0;return!1}(L))return void df(L);const k=ah(L,L.map&&L.map.transform);L._hdElevation||(L._hdElevation=new B0);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(!Qc(L))return void df(L);T===void 0&&Wo(L,void 0,!0);const B=L._hdElevation;B._needsCrossSourceElevation=!0,L._crossSourceElevationActive=!0,B._ingestFQIDs=ng(L),Bd(L,B)},updateElevationCoverage:Bd,updateCrossSourceElevationGate:function(L){L._crossSourceElevationActive=Qc(L)},buildElevationRequestParams:function(L,k,T){if(ah(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,oe,he){const we=Q.getTilesIntersecting(oe);if(we.length===0)return{registry:[],hasCoveringTile:!1,allProvidersReady:he};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:he}}(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 oe of B.polygons)if(oe.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 oe=this._createBuffers(L,B);oe&&this.tileBuffers.set(Q,oe)}}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 oe of k.polygons){if(!oe.hasGeometry()||oe.rings.length===0)continue;const he=T.length,we=B.length,Me=T.length,Re=[],Ze=[];let Xe=0;for(let _t=0;_t0&&Ze.push(Xe);for(const Mt of bt)T.emplaceBack(Mt.x,Mt.y),Re.push(Mt.x,Mt.y),Xe++}}const dt=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,Xe,L.programConfiguration,L.dynamicBuffers),"drawn"}return"fallthrough"},drawFillFrcCoverageSecondPass:function(L,k,T,B,K){if(T.length===0)return;const Q=Ih(L),oe=L.transform.zoom,he=(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,oe,we.programConfiguration,we.dynamicBuffers),Re!==1&&(we.uniformValues.u_opacity_multiplier=1)};zm(L,T,Q,(we,Me,Re)=>he(we,Re,1),(we,Me,Re)=>he(we,Re,Q))},drawLineFrcCoverageDetect:function(L,k,T,B,K,Q,oe,he,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 Xe=xu(Ze.polygons),dt=L.frcCoverageFadeRange,_t=dt!=null&&L.transform.zoom>=dt[0];if(Xe&&_t){let bt=!1;for(const Mt of Re.frcPerLevel.keys())if(Ze.frcMask&1<0&&B(T,oe)},drawLineFrcFadePass:function(L,k,T,B,K,Q,oe){if(B.hasPolygonGeometry)return;const he=k.hdExt&&k.hdExt.frcData;if(!he||!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),Xe=B.frcMask;for(const[dt,_t]of he.frcPerLevel)Xe&1<{const Ze=he.bucket.hdExt&&he.bucket.hdExt.frcData,Xe=Ze&&Ze.frcPerLevel.get(we);Xe&&Xe.segments.length!==0&&(Re!==1&&(he.uniformValues.u_opacity_multiplier=Re),he.program.draw(L,B.TRIANGLES,he.depthMode,Me,he.colorMode,o.$.disabled,he.uniformValues,k.id,he.bucket.layoutVertexBuffer,he.bucket.indexBuffer,Xe,k.paint,Q,he.programConfiguration,[he.bucket.layoutVertexBuffer2,he.bucket.patternVertexBuffer,he.bucket.zOffsetVertexBuffer,he.bucket.elevationIdColVertexBuffer,he.bucket.elevationGroundScaleVertexBuffer]),Re!==1&&(he.uniformValues.u_opacity_multiplier=1))};zm(L,T,K,(he,we,Me)=>oe(he,we,Me,1),(he,we,Me)=>oe(he,we,Me,K))}},Ui=yh;async function um(){return Promise.resolve()}function oh(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 sp(L,k,T,B,K,Q,oe){const he=L.context,we=he.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 Xe=L.getOrCreateProgram("hillshade",{overrideFog:Re,defines:Ze});he.activeTexture.set(we.TEXTURE0),we.bindTexture(we.TEXTURE_2D,Me.colorAttachment0.get());const dt=((ss,Jt,Lt,ps)=>{const Gs=Lt.paint.get("hillshade-shadow-color"),Ls=Lt.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",sn=Lt.paint.get("hillshade-highlight-color"),Bs=Lt.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",nn=Lt.paint.get("hillshade-accent-color"),yn=Lt.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",Tn=Lt.paint.get("hillshade-emissive-strength");let Gn=o.av(Lt.paint.get("hillshade-illumination-direction"));if(Lt.paint.get("hillshade-illumination-anchor")==="viewport")Gn-=ss.transform.angle;else if(ss.style&&ss.style.enable3dLights()&&ss.style.directionalLight){const Dn=ss.style.directionalLight.properties.get("direction"),Mr=o.b_(Dn.x,Dn.y,Dn.z);Gn=o.av(Mr[1])}const zn=!ss.options.moving;return{u_matrix:ps||ss.transform.calculateProjMatrix(Jt.tileID.toUnwrapped(),zn),u_image:0,u_latrange:oh(0,Jt.tileID),u_light:[Lt.paint.get("hillshade-exaggeration"),Gn],u_shadow:Gs.toPremultipliedRenderColor(Ls?null:Lt.lut),u_highlight:sn.toPremultipliedRenderColor(Bs?null:Lt.lut),u_emissive_strength:Tn,u_accent:nn.toPremultipliedRenderColor(yn?null:Lt.lut)}})(L,T,B,L.terrain?k.projMatrix:null);L.uploadCommonUniforms(he,Xe,k.toUnwrapped());const{tileBoundsBuffer:_t,tileBoundsIndexBuffer:bt,tileBoundsSegments:Mt}=L.getTileBoundsBuffers(T);Xe.draw(L,we.TRIANGLES,K,Q,oe,o.$.disabled,dt,B.id,_t,bt,Mt)}function Kg(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 lh(L,k,T){const B=L.context,K=B.gl;if(!k.dem)return;const Q=k.dem;if(B.activeTexture.set(K.TEXTURE1),Kg(L,k,Q),!k.demTexture)return;k.demTexture.bind(K.NEAREST,K.CLAMP_TO_EDGE);const oe=Q.dim;B.activeTexture.set(K.TEXTURE0);let he=k.hillshadeFBO;if(!he){const Xe=new o.T(B,{width:oe,height:oe,data:null},K.RGBA8);Xe.bind(K.LINEAR,K.CLAMP_TO_EDGE),he=k.hillshadeFBO=B.createFramebuffer(oe,oe,1,"renderbuffer"),he.colorAttachment0.set(Xe.texture)}B.bindFramebuffer.set(he.framebuffer),B.viewport.set([0,0,oe,oe]);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,((Xe,dt)=>{const _t=dt.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:Xe.overscaledZ}})(k.tileID,Q),T.id,we,Me,Re),k.needsHillshadePrepare=!1}class Ic{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 Yg extends Ic{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 P1 extends Ic{getDefault(){return 1}set(k){(k!==this.current||this.dirty)&&(this.gl.clearDepth(k),this.current=k,this.dirty=!1)}}class I1 extends Ic{getDefault(){return 0}set(k){(k!==this.current||this.dirty)&&(this.gl.clearStencil(k),this.current=k,this.dirty=!1)}}class L1 extends Ic{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 Kw extends Ic{getDefault(){return!0}set(k){(k!==this.current||this.dirty)&&(this.gl.depthMask(k),this.current=k,this.dirty=!1)}}class Yw extends Ic{getDefault(){return 255}set(k){(k!==this.current||this.dirty)&&(this.gl.stencilMask(k),this.current=k,this.dirty=!1)}}class D_ extends Ic{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 Mk extends Ic{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 Pb extends Ic{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 Ov extends Ic{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 N3 extends Ic{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 U2 extends Ic{getDefault(){return this.gl.LESS}set(k){(k!==this.current||this.dirty)&&(this.gl.depthFunc(k),this.current=k,this.dirty=!1)}}class np extends Ic{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 Pk extends Ic{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 R1 extends Ic{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 Zg extends Ic{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 rp extends Ic{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 Rx extends Ic{getDefault(){return this.gl.BACK}set(k){(k!==this.current||this.dirty)&&(this.gl.cullFace(k),this.current=k,this.dirty=!1)}}class $d extends Ic{getDefault(){return this.gl.CCW}set(k){(k!==this.current||this.dirty)&&(this.gl.frontFace(k),this.current=k,this.dirty=!1)}}let zv=class extends Ic{getDefault(){return null}set(L){(L!==this.current||this.dirty)&&(this.gl.useProgram(L),this.current=L,this.dirty=!1)}};class PC extends Ic{getDefault(){return this.gl.TEXTURE0}set(k){(k!==this.current||this.dirty)&&(this.gl.activeTexture(k),this.current=k,this.dirty=!1)}}class UT extends Ic{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 qT extends Ic{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 k3 extends Ic{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 Ib extends Ic{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 Ep extends Ic{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 $0 extends Ic{getDefault(){return null}set(k){const T=this.gl;T.bindBuffer(T.ELEMENT_ARRAY_BUFFER,k),this.current=k,this.dirty=!1}}class IC extends Ic{getDefault(){return null}set(k){this.gl&&(k!==this.current||this.dirty)&&(this.gl.bindVertexArray(k),this.current=k,this.dirty=!1)}}class S3 extends Ic{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 Lb extends Ic{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 ap extends Ic{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 Zw extends Ic{constructor(k,T){super(k),this.context=k,this.parent=T}getDefault(){return null}}class Pr extends Zw{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 Ik extends Zw{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 LC extends Zw{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 Xg extends Ik{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const uf=(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}),D1=(L,k,T,B,K,Q,oe,he,we,Me,Re,Ze,Xe,dt,_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:oe,u_frustum_tr:he,u_frustum_br:we,u_frustum_bl:Me,u_globe_pos:Re,u_globe_radius:Ze,u_viewport:Xe,u_grid_matrix:Mt?Float32Array.from(Mt):new Float32Array(9),u_skirt_height:dt,u_far_z_cutoff:_t,u_emissive_texture_available:bt});function U0(L,k){return L!=null&&k!=null&&!(!L.hasData()||!k.hasData())&&L.demTexture!=null&&k.demTexture!=null&&L.tileID.key!==k.tileID.key}const q0=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 Dx(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 Lk(L,k){const T=1<{if(Q[oe.key]="",!this._tiles[oe.key]){const he=new Px(oe,this._source.tileSize*oe.overscaleFactor(),k.tileZoom,void 0,void 0,this._source.worldview);he.state="loaded",this._tiles[oe.key]=he}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 Xw 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 O_(L,k){return k==="rgba8"?L.RGBA8:L.R8}class RC 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,Xe=o.a6+Ze/2,dt=Xe+Ze;for(let bt=-Ze;btXe||bt<0||bt>Xe?24575:0,Jt=o.b1(Math.round(Mt),0,o.a6),Lt=o.b1(Math.round(bt),0,o.a6);we.emplaceBack(Jt+ss,Lt)}const _t=(bt,Mt)=>{const ss=Mt*Re+bt;Me.emplaceBack(ss+1,ss,ss+Re),Me.emplaceBack(ss+Re,ss+Re+1,ss+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]}(),oe=k.context;this.gridBuffer=oe.createVertexBuffer(B,o.bF.members),this.gridIndexBuffer=oe.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 F_(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 he=oe.gl;this._overlapStencilMode=new o._({func:he.GEQUAL,mask:255},0,255,he.KEEP,he.KEEP,he.REPLACE),this._previousZoom=k.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=T,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Dk(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,oe=k.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.e.now();const he=k.terrain&&k.terrain.scope,we=K.get("source"),Me=Q?this._mockSourceCache:k.getSourceCache(we,he);if(!Me)return void o.w(`Couldn't find terrain source "${we}".`);if(this.sourceCache=Me,this._attenuationRange=k.terrain.getAttenuationRange(),this._exaggeration=oe?this.calculateExaggeration(T):K.get("exaggeration"),!T.projection.requiresDraping&&oe&&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,oe=this._style.terrain;if(!this._previousUpdateTimestamp)return oe.getExaggeration(Q);let he=Q-this._previousZoom;const we=this._previousUpdateTimestamp;let Me=Q;this._evaluationZoom!=null&&(Me=this._evaluationZoom,Math.abs(Q-Me)>.5&&(he=.5*(Q-Me+he)),he*K<0&&(Me+=he)),this._evaluationZoom=Me;const Re=oe.getExaggeration(Me),Ze=Re===oe.getExaggeration(Math.max(0,Me-.1));if(Ze&&Math.abs(Re-this._exaggeration)<.01)return Re;let Xe=Math.min(.1,.00375*(this._updateTimestamp-we));return(Ze||Re<.1||Math.abs(he)<1e-4)&&(Xe=Math.min(.2,4*Xe)),o.am(this._exaggeration,Re,Xe)}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((Xe,dt)=>{if(dt.overscaledZ-Xe.overscaledZ)return dt.overscaledZ-Xe.overscaledZ;const _t=new o.P(Xe.canonical.x+(1<{this.proxyToSource[we.key]={}}),this.terrainTileForTile={};const oe=this._style._mergedSourceCaches;for(const we in oe){const Me=oe[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 Xw(we,we.key,this.orthoMatrix)),this._assignTerrainTiles(K),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(Q),this.renderingToTexture=!1;const he={};this._visibleDemTiles=[];for(const we of this.proxyCoords){const Me=this.terrainTileForTile[we.key];if(!Me)continue;const Re=Me.tileID.key;Re in he||(this._visibleDemTiles.push(Me),he[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),Kg(this.painter,K,Q))}}_prepareDemTileUniforms(k,T,B,K){if(!T||T.demTexture==null)return!1;const Q=k.tileID.canonical,oe=Math.pow(2,T.tileID.canonical.z-Q.z),he=K||"";return B[`u_dem_tl${he}`]=[Q.x*oe%1,Q.y*oe%1],B[`u_dem_scale${he}`]=oe,!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,oe={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};oe.u_exaggeration=this.exaggeration();let he=null,we=null,Me=1;if(B&&B.morphing&&this._useVertexMorphing){const dt=B.morphing.srcDemTile,_t=B.morphing.dstDemTile;Me=B.morphing.phase,dt&&_t&&(this._prepareDemTileUniforms(k,dt,oe,"_prev")&&(we=dt),this._prepareDemTileUniforms(k,_t,oe)&&(he=_t))}const Re=dt=>dt&&dt.demTexture&&this.painter.linearFloatFilteringSupported()?Q.LINEAR:Q.NEAREST;let Ze=null;var Xe;if(this.enabled?we&&he?(Ze=he.demTexture,K.activeTexture.set(Q.TEXTURE4),we.demTexture.bind(Re(we),Q.CLAMP_TO_EDGE),oe.u_dem_lerp=Me):(he=this.terrainTileForTile[k.tileID.key],Ze=this._prepareDemTileUniforms(k,he,oe)?he.demTexture:this.emptyDEMTexture):Ze=this.emptyDEMTexture,K.activeTexture.set(Q.TEXTURE2),Ze&&(oe.u_dem_size=(Xe=Ze).size[0]===1?1:Xe.size[0]-2,Ze.bind(Re(he),Q.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(B&&B.useDepthForOcclusion,T,oe),B&&B.useMeterToDem&&he){const dt=(1<{if(ss===Dn)return;const Mr=[];Dn===1&&Mr.push("TERRAIN_VERTEX_MORPHING"),Mr.push("PROJECTION_GLOBE_VIEW"),Lt&&Mr.push("CUSTOM_ANTIALIASING");const kn=Me.isTileAffectedByFog(zn);Mt=Me.getOrCreateProgram("globeRaster",{defines:Mr,overrideFog:kn}),ss=Dn},Gs=Me.colorModeForRenderPass(),Ls=new o.Z(bt.LEQUAL,o.Z.ReadWrite,Me.depthRangeFor3D);q0.update(dt);const sn=o.b7(Jt),Bs=[o.a7(Jt.center.lng),o.a8(Jt.center.lat)],nn=Me.globeSharedBuffers,yn=[Jt.width*o.e.devicePixelRatio,Jt.height*o.e.devicePixelRatio],Tn=Float32Array.from(Jt.globeMatrix),Gn={useDenormalizedUpVectorScale:!0};{const zn=Me.transform,Dn=Dx(zn.zoom,Re.exaggeration(),Re.sourceCache._source.tileSize);ss=-1;const Mr=bt.TRIANGLES;for(const kn of Xe){const pr=Ze.getTile(kn),ta=o._.disabled,ka=Re.prevTerrainTileForTile[kn.key],qr=Re.terrainTileForTile[kn.key];U0(ka,qr)&&q0.newMorphing(kn.key,ka,qr,dt,250),q2(Me,pr.emissiveTexture),_t.activeTexture.set(bt.TEXTURE0),pr.texture&&pr.texture.bind(bt.LINEAR,bt.CLAMP_TO_EDGE);const Jr=q0.getMorphValuesForProxy(kn.key),si=Jr?1:0;Jr&&Object.assign(Gn,{morphing:{srcDemTile:Jr.from,dstDemTile:Jr.to,phase:o.b$(Jr.phase)}});const Gr=o.b3(kn.canonical),Sr=o.b4(Gr.getCenter().lat),Hr=o.b8(kn.canonical,Gr,Sr,zn.worldSize/zn._pixelsPerMercatorPixel),Ha=o.b5(o.b6(kn.canonical)),$r=Me.isEmissiveMrtActive()?1:0,Ya=D1(zn.expandedFarZProjMatrix,Tn,sn,Ha,o.S(zn.zoom),Bs,zn.frustumCorners.TL,zn.frustumCorners.TR,zn.frustumCorners.BR,zn.frustumCorners.BL,zn.globeCenterInViewSpace,zn.globeRadius,yn,Dn,zn._farZ,$r,Hr);if(ps(kn,si),Mt&&(Re.setupElevationDraw(pr,Mt,Gn),Me.uploadCommonUniforms(_t,Mt,kn.toUnwrapped()),nn)){const[Oi,Do,to]=nn.getGridBuffers(Sr,Dn!==0);Mt.draw(Me,Mr,Ls,ta,Gs,o.$.backCCW,Ya,"globe_raster",Oi,Do,to)}}}if(nn&&(Me.renderDefaultNorthPole||Me.renderDefaultSouthPole)){const zn=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Lt&&zn.push("CUSTOM_ANTIALIASING"),Mt=Me.getOrCreateProgram("globeRaster",{defines:zn});for(const Dn of Xe){const{x:Mr,y:kn,z:pr}=Dn.canonical,ta=kn===0,ka=kn===(1<Oi.draw(Me,bt.TRIANGLES,Ls,o._.disabled,Gs,o.$.disabled,D1(Jt.expandedFarZProjMatrix,Hr,Hr,Ha,0,Bs,Jt.frustumCorners.TL,Jt.frustumCorners.TR,Jt.frustumCorners.BR,Jt.frustumCorners.BL,Jt.globeCenterInViewSpace,Jt.globeRadius,yn,0,Jt._farZ,$r),"globe_pole_raster",Do,si,Gr);Re.setupElevationDraw(Sr,Mt,Gn),Me.uploadCommonUniforms(_t,Mt,Dn.toUnwrapped()),ta&&Me.renderDefaultNorthPole&&Ya(Mt,qr),ka&&Me.renderDefaultSouthPole&&(Hr=o.aO(o.Y(),Hr,[1,-1,1]),Ya(Mt,Jr))}}}})(K,Q,oe,he,we);else{const Me=K.context,Re=Me.gl;let Ze,Xe;const dt=K.shadowRenderer,_t=o.aF(K,K.longestCutoffRange),bt=Gs=>{if(Xe===Gs)return;const Ls=[];Gs===1&&Ls.push("TERRAIN_VERTEX_MORPHING"),_t.shouldRenderCutoff&&Ls.push("RENDER_CUTOFF"),dt&&(Ls.push("RENDER_SHADOWS"),dt.useNormalOffset&&Ls.push("NORMAL_OFFSET")),Ze=K.getOrCreateProgram("terrainRaster",{defines:Ls}),Xe=Gs},Mt=K.colorModeForRenderPass(),ss=new o.Z(Re.LEQUAL,o.Z.ReadWrite,K.depthRangeFor3D);q0.update(we);const Jt=K.transform,Lt=Dx(Jt.zoom,Q.exaggeration(),Q.sourceCache._source.tileSize);let ps=[0,0,0];if(dt){const Gs=K.style.directionalLight,Ls=K.style.ambientLight;Gs&&Ls&&(ps=o.aG(K.style,Gs,Ls))}{Xe=-1;const Gs=Re.TRIANGLES,[Ls,sn]=[Q.gridIndexBuffer,Q.gridSegments];for(const Bs of he){const nn=oe.getTile(Bs),yn=o._.disabled,Tn=Q.prevTerrainTileForTile[Bs.key],Gn=Q.terrainTileForTile[Bs.key];U0(Tn,Gn)&&q0.newMorphing(Bs.key,Tn,Gn,we,250),q2(K,nn.emissiveTexture),Me.activeTexture.set(Re.TEXTURE0),nn.texture&&nn.texture.bind(Re.LINEAR,Re.CLAMP_TO_EDGE);const zn=q0.getMorphValuesForProxy(Bs.key),Dn=zn?1:0;let Mr;zn&&(Mr={morphing:{srcDemTile:zn.from,dstDemTile:zn.to,phase:o.b$(zn.phase)}});const kn=K.isEmissiveMrtActive()?1:0,pr=uf(Bs.projMatrix,Lk(Bs.canonical,Jt.renderWorldCopies)?Lt/10:Lt,ps,kn);if(bt(Dn),!Ze)continue;Q.setupElevationDraw(nn,Ze,Mr);const ta=Bs.toUnwrapped();dt&&dt.setupShadows(ta,Ze),K.uploadCommonUniforms(Me,Ze,ta,null,_t),Ze.draw(K,Gs,ss,yn,Mt,o.$.backCCW,pr,"terrain_raster",Q.gridBuffer,Ls,sn)}}}}(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],oe=this._drapedRenderBatches.shift(),he=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),Xe=K.proxyCachedFBO[Re.key]?K.proxyCachedFBO[Re.key][k]:void 0,dt=Xe!==void 0?K.renderCache[Xe]:this.pool[Me++],_t=Xe!==void 0;if(Ze.texture=dt.tex,Ze.emissiveTexture=dt.emissiveTex,_t&&!dt.dirty){we.push(Ze.tileID);continue}B.bindFramebuffer.set(dt.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,dt.dirty&&(B.clear({color:o.C.transparent,stencil:0}),dt.dirty=!1);for(let ss=oe.start;ss<=oe.end;++ss){const Jt=T.style._mergedLayers[he[ss]];if(Jt.isHidden(T.transform.zoom))continue;const Lt=T.style.getLayerSourceCache(Jt),ps=Lt?this.proxyToSource[Re.key][Lt.id]:[Re];if(!ps)continue;const Gs=ps;B.viewport.set([0,0,dt.fb.width,dt.fb.height]),Mt!==(Lt?Lt.id:null)&&(this._setupStencil(dt,ps,Jt,Lt),Mt=Lt?Lt.id:null),T.renderLayer(T,Lt,Jt,Gs)}if(bt.drawBuffers([bt.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const ss of this._pendingGroundEffectLayers){const Jt=T.style._mergedLayers[he[ss]];if(Jt.isHidden(T.transform.zoom))continue;const Lt=T.style.getLayerSourceCache(Jt),ps=Lt?this.proxyToSource[Re.key][Lt.id]:[Re];if(!ps)continue;const Gs=ps;B.viewport.set([0,0,dt.fb.width,dt.fb.height]),Mt!==(Lt?Lt.id:null)&&(this._setupStencil(dt,ps,Jt,Lt),Mt=Lt?Lt.id:null),T.renderLayer(T,Lt,Jt,Gs)}this.renderedToTile?(dt.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]),oe.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 oe=Q.tileID,he=1<(Q.t!==null?Q.t:Number.MAX_VALUE)-(oe.t!==null?oe.t:Number.MAX_VALUE));for(const Q of K){if(Q.t==null)return null;const oe=Q.tile.dem.tree.raycast(Q.minx,Q.miny,Q.maxx,Q.maxy,k,T,B);if(oe!=null)return oe}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 oe;return Q.colorAttachment0.set(K.texture),this._emissiveTexture!=="none"&&(oe=new o.T(k,{width:B[0],height:B[1],data:null},O_(T,this._emissiveTexture)),oe.bind(T.LINEAR,T.CLAMP_TO_EDGE),Q.createColorAttachment(k,1),Q.colorAttachment1.set(oe.texture)),Q.depthAttachment=new Xg(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:oe,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,oe=this.drapeBufferSize;if(T!=="none"){const he=new o.T(K,{width:oe[0],height:oe[1],data:null},O_(Q,T));he.bind(Q.LINEAR,Q.CLAMP_TO_EDGE),k.emissiveTex=he,B.createColorAttachment(K,1),B.colorAttachment1.set(he.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>he.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 oe=Object.values(T.proxyCachedFBO);T.proxyCachedFBO={};for(let he=0;he=0;oe--){const he=B[oe];if(T.getTileByID(he.key),T.proxyCachedFBO[he.key]!==void 0){const we=k[he.key],Me=this.proxyToSource[he.key];let Re=0;for(const Ze in Me){const Xe=Me[Ze],dt=we[Ze];if(!dt||dt.length!==Xe.length||Xe.some((_t,bt)=>_t!==dt[bt]||K[Ze]&&Object.hasOwn(K[Ze],_t.key))){Re=-1;break}++Re}for(const Ze in T.proxyCachedFBO[he.key])T.renderCache[T.proxyCachedFBO[he.key][Ze]].dirty=Re<0||Re!==Object.values(we).length}}const Q=[...this._drapedRenderBatches];Q.sort((oe,he)=>he.end-he.start-(oe.end-oe.start));for(const oe of Q)for(const he of B){if(T.proxyCachedFBO[he.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[he.key]={},T.proxyCachedFBO[he.key][oe.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,oe=Q.gl;if(T.length<=1)return void(this._overlapStencilType=!1);let he;if(B.isTileClipped())he=T.length,this._overlapStencilMode.test={func:oe.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(T[0].overscaledZ>T.at(-1).overscaledZ))return void(this._overlapStencilType=!1);he=1,this._overlapStencilMode.test={func:oe.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+he>255&&(Q.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=he,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 oe=B.getOrCreateProgram("clippingMask");for(const he of k){const we=B._tileClippingMaskIDs[he.key]=--T;oe.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,gu(he.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),oe=[K[0],K[1],K[2]/Q,0],he=o.c8([],B.slice(0,3),oe);o.c9(he,he);const we=this.raycast(oe,he,this._exaggeration);return we!==null&&we?(o.ca(oe,oe,he,we),oe[3]=oe[2],oe[2]*=Q,oe):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,oe=k.getSource(),he=oe.tileID;if(!he)return;const we=new o.P(he.x,he.y)._div(1<(Ze.min.x=Math.min(Ze.min.x,Xe.x-we.x),Ze.min.y=Math.min(Ze.min.y,Xe.y-we.y),Ze.max.x=Math.max(Ze.max.x,Xe.x-we.x),Ze.max.y=Math.max(Ze.max.y,Xe.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,Xe)=>{const dt=Ze.wrap+Ze.canonical.x/(1<Mt+Me.max.x||_t+btss+Me.max.y};for(let Ze=0;Zeoe.key===T.tileID.key);if(Q)return Q}if(T.tileID.key!==k.key){const Q=k.canonical.z-T.tileID.canonical.z;let oe,he,we;K=o.Y();const Me=T.tileID.wrap-k.wrap<0?(oe=o.a6>>Q,he=oe*((T.tileID.canonical.x<=Ze){const Xe=k.canonical.z-Ze;T.getSource().reparseOverscaled?(he=Math.max(k.canonical.z+2,T.transform.tileZoom),oe=new o.bQ(he,k.wrap,Ze,k.canonical.x>>Xe,k.canonical.y>>Xe)):Xe!==0&&(he=Ze,oe=new o.bQ(he,k.wrap,Ze,k.canonical.x>>Xe,k.canonical.y>>Xe))}oe.key!==k.key&&(Me.push(oe.key),B=T.getTile(oe))}const Re=Ze=>{Me.forEach(Xe=>{K[Xe]=Ze}),Me.length=0};for(he-=1;he>=we&&(!B||!B.hasData());he--){B&&Re(B.tileID.key);const Ze=oe.calculateScaledKey(he);if(B=T.getTileByID(Ze),B&&B.hasData())break;const Xe=K[Ze];if(Xe===null)break;Xe===void 0?Me.push(Ze):B=T.getTileByID(Xe)}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 V2=null;const z_=[];function Qg(L,k){return V2?V2.create(L,k):null}const DC=(L,k,T)=>({u_matrix:L,u_emissive_strength:k,u_ground_shadow_factor:T,u_opacity_multiplier:1}),F1=(L,k,T,B,K,Q=0)=>Object.assign(DC(L,k,K),o.cb(T,B,Q)),Qw=(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,oe=0)=>Object.assign(F1(L,k,T,B,Q,oe),{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,oe)=>{const he=L.transform,we=he.projection.name==="globe",Me=we?o.cc(he.zoom,k.canonical)*he._pixelsPerMercatorPixel:o.cd(T,1,Q),Re={u_matrix:k.projMatrix,u_extrude_scale:Me,u_intensity:oe,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:oe,u_scale_parent:Re,u_fade_t:Ze.mix,u_opacity:Ze.opacity*Xe.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Xe.paint.get("raster-brightness-min"),u_brightness_high:Xe.paint.get("raster-brightness-max"),u_saturation_factor:o.cg(Xe.paint.get("raster-saturation")),u_contrast_factor:o.cf(Xe.paint.get("raster-contrast")),u_spin_weights:As(Xe.paint.get("raster-hue-rotate")),u_perspective_transform:dt,u_raster_elevation:_t,u_zoom_transition:he,u_merc_center:we,u_cutoff_params:Me,u_colorization_mix:Ul(o.ce,Mt,Jt),u_colorization_offset:fo(o.ce,ss,Jt),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:Gs,u_zbias_factor:cs(L)});function As(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 Is=o.Y(),qs=(L,k,T,B,K,Q,oe,he,we,Me,Re,Ze,Xe,dt,_t,bt,Mt,ss,Jt,Lt,ps,Gs,Ls,sn,Bs)=>{const nn=K.transform,yn={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:nn.getCameraToCenterDistance(Lt),u_rotate_symbol:+T,u_aspect_ratio:nn.width/nn.height,u_fade_change:K.options.fadeDuration?K.symbolFadeChange:1,u_matrix:Q,u_label_plane_matrix:oe,u_coord_matrix:he,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:Xe,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Is,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Is,u_up_vector:[0,-1,0],u_color_adj_mat:Ls,u_icon_transition:sn||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:Bs||1,u_ground_shadow_factor:ps,u_inv_matrix:o.aP(o.Y(),oe),u_normal_scale:Gs,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"&&(yn.u_tile_id=[_t.canonical.x,_t.canonical.y,1<<_t.canonical.z],yn.u_zoom_transition=bt,yn.u_inv_rot_matrix=ss,yn.u_merc_center=Mt,yn.u_camera_forward=nn._camera.forward(),yn.u_ecef_origin=o.ch(nn.globeMatrix,_t.toUnwrapped()),yn.u_tile_matrix=nn.globeMatrix,yn.u_up_vector=Jt),yn},an=(L,k,T,B)=>({u_matrix:L,u_emissive_strength:k,u_opacity:T,u_color:B}),Kn=(L,k,T,B,K,Q,oe,he,we)=>Object.assign(o.cj(K,Q,oe,B,he,we),{u_matrix:L,u_emissive_strength:k,u_opacity:T}),jr={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 Qs={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){V2=L;for(const k of z_.splice(0))k()})({create:(L,k)=>new RC(L,k)}),Object.assign(jr,{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 ir={shaders:Qs};class yr{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]),oe=o.P.convert(k[1]),he=Q.add(oe)._div(2);B=[Q,oe],K=o.cq(Q,oe).every(we=>T.isPointAboveHorizon(we))&&T.isPointAboveHorizon(he)}return new yr(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(),oe=+(Q.x>T.x)+ +(Q.x>B.x);switch(3*(+(Q.y>T.y)+ +(Q.y>B.y))+oe){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 oe=Math.max(k.queryPadding,k.evaluateQueryRenderedFeaturePadding())/T._pixelsPerMercatorPixel+1,he=B?this._bufferedCameraMercator(oe,T):this._bufferedScreenMercator(oe,T);let we=k.tileID.wrap+(he.unwrapped?K:0);const Me=he.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])),Xe=o.cu(k.tileTransform,Q,we),dt=Re.map(Mt=>{const ss=o.cv(Mt,Mt,Xe);return o.c9(ss,ss),new o.cw(Xe,ss)}),_t=o.cd(k,1,T.zoom)*T._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:Ze,tilespaceRays:dt,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=ua(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=ua(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,oe){const he=o.X([],oe.pixelMatrix,oe.globeMatrix),we=[0,-o.cy,0,1],Me=[0,o.cy,0,1],Re=[0,0,0,1];o.c6(we,we,he),o.c6(Me,Me,he),o.c6(Re,Re,he);const Ze=new o.P(we[0]/we[3],we[1]/we[3]),Xe=new o.P(Me[0]/Me[3],Me[1]/Me[3]),dt=o.cz(Q,Ze)&&we[3]1?ra(Q.slice(0,Mt),oe):[],Lt=Mtnew o.P(dr(Bs.x),Bs.y)),Lt=Lt.map(Bs=>new o.P(dr(Bs.x),Bs.y));const ps=[...Jt];ps.length===0&&ps.push(Lt.at(-1));const Gs=ps.at(-1),Ls=o.am(Gs.y,(Lt.length===0?Jt[0]:Lt[0]).y,ss);let sn;return sn=dt?[new o.P(0,Ls),new o.P(0,0),new o.P(1,0),new o.P(1,Ls)]:[new o.P(1,Ls),new o.P(1,1),new o.P(0,1),new o.P(0,Ls)],ps.push(...sn),Lt.length===0?ps.push(Jt[0]):ps.push(...Lt),{polygon:ps.map(Bs=>new o.bT(Bs.x,Bs.y)),unwrapped:!1}}(k,T);if(B)return B;const K=function(Q,oe){let he=!1,we=-1/0,Me=0;for(let Ze=0;Zewe&&(we=Q[Ze].x,Me=Ze);for(let Ze=0;Ze.5&&(dt.x<_t.x?(dt.x+=1,Xe===0&&(Q.at(-1).x+=1)):(_t.x+=1,Xe+1===Q.length-1&&(Q[0].x+=1)),he=!0)}const Re=o.a7(oe.center.lng);return he&&Re{Ze.x-=1}),{polygon:Q,unwrapped:he}}(ra(k,T).map(Q=>new o.P(dr(Q.x),Q.y)),T);return{polygon:K.polygon.map(Q=>new o.bT(Q.x,Q.y)),unwrapped:K.unwrapped}}}function ra(L,k){return o.cA(L,T=>{const B=k.pointCoordinate3D(T);T.x=B.x,T.y=B.y},1/256)}function dr(L){return L<0?1+L%1:L%1}function ua(L){return 100*L|0}class lr 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,oe)=>{this._tileJSONRequest=null,this._loaded=!0,Q?this.fire(new o.f(Q)):oe&&(Object.assign(this,oe),oe.raster_layers&&(this.rasterLayers=oe.raster_layers,this.rasterLayerIds=this.rasterLayers.map(he=>he.id)),this.tileBounds=o.cF.fromTileJSON(oe),o.cK(oe.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 oe=await o.cN(k.name,k.url);if(B.signal.aborted)return;const he=new oe(Q);let we=null;if(he.load&&K&&(we=await he.load({request:K}),B.signal.aborted))return;this._tileProvider=he;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 oe=await this.map._requestManager.transformRequest(K,o.R.Tile,Q.signal);if(Q.signal.aborted)return delete k.request,T(null);const{data:he,headers:we}=await o.a(oe,Q.signal);if(delete k.request,k.aborted)return T(null);const Me=o.cI(we);this.map._refreshExpiredTiles&&k.setExpiryData(Me),k.setTexture(he,this.map.painter),k.state="loaded",o.cJ(this.dispatcher),T(null)}catch(oe){if(delete k.request,Q.signal.aborted)return T(null);k.state="errored",T(oe)}}async loadTileWithProvider(k,T,B,K,Q){const{z:oe,x:he,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:oe,x:he,y:we},{request:Me,signal:K.signal});if(K.signal.aborted)return Q(null);if(Re==null){const Xe=new Error("Tile not found");return Xe.status=404,k.state="errored",Q(Xe)}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,oe,he){const we=[L,k,1,T,B,1,K,Q,1],Me=[oe,he,1],Re=o.cU([],we),[Ze,Xe,dt]=o.cT(Me,Me,Re);return o.cV(we,we,[Ze,0,0,0,Xe,0,0,0,dt])}function Aa(L,k,T,B,K,Q,oe,he){const we=function(Me,Re,Ze,Xe,dt,_t,bt,Mt){const ss=Ua(0,0,1,0,1,1,0,1),Jt=Ua(Me,Re,Ze,Xe,dt,_t,bt,Mt),Lt=o.cU([],ss);return o.cV(Jt,Jt,Lt)}(L,k,T,B,K,Q,oe,he);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(oe){let he=1/0,we=1/0,Me=-1/0,Re=-1/0;for(const bt of oe)he=Math.min(he,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-he,Re-we),Xe=Math.max(0,Math.floor(-Math.log2(Ze))),dt=Math.pow(2,Xe);let _t=Math.floor((he+Me)/2*dt);return _t>1&&(_t-=1),new o.bW(Xe,_t,Math.floor((we+Re)/2*dt))}(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 Gs in this.tiles){const Ls=this.tiles[Gs];Ls.state!=="loaded"&&(Ls.state="loaded",Ls.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(Gs){const Ls=Gs[1].x-Gs[0].x,sn=Gs[1].y-Gs[0].y,Bs=Gs[2].x-Gs[1].x,nn=Gs[2].y-Gs[1].y,yn=Gs[3].x-Gs[2].x,Tn=Gs[3].y-Gs[2].y,Gn=Gs[0].x-Gs[3].x,zn=Gs[0].y-Gs[3].y,Dn=Ls*nn-Bs*sn,Mr=Bs*Tn-yn*nn,kn=yn*zn-Gn*Tn,pr=Gn*sn-Ls*zn;return Dn>0&&Mr>0&&kn>0&&pr>0||Dn<0&&Mr<0&&kn<0&&pr<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,oe,he,we]=this.coordinates.map(Gs=>{const Ls=K.projection.project(Gs[0],Gs[1]);return o.cs(K,Ls)._round()});this.perspectiveTransform=Aa(Q.x,Q.y,oe.x,oe.y,he.x,he.y,we.x,we.y);const Me=this._boundsArray=new o.bt;Me.emplaceBack(Q.x,Q.y,0,0),Me.emplaceBack(oe.x,oe.y,o.a6,0),Me.emplaceBack(we.x,we.y,0,o.a6),Me.emplaceBack(he.x,he.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,Xc.members),this.boundsSegments=o.ad.simpleSegment(0,0,4,2);const Re=o.cS,Ze=Re+1,Xe=Re+1,dt=Ze*Xe,_t=Re*Re*2,bt=[],Mt=function(Gs){return[_o(Gs[0]),_o(Gs[1]),_o(Gs[2]),_o(Gs[3])]}(this.coordinates),[ss,Jt,Lt,ps]=function(Gs){let Ls=Gs[0][0],sn=Ls,Bs=Gs[0][1],nn=Bs;for(let yn=1;ynsn&&(sn=Gs[yn][0]),Gs[yn][1]nn&&(nn=Gs[yn][1]);return[Ls,Bs,sn-Ls,nn-Bs]}(Mt);{const Gs=new o.bt,[Ls,sn,Bs,nn]=function(Jr){let si=Jr[0].x,Gr=si,Sr=Jr[0].y,Hr=Sr;for(let Ha=1;HaGr&&(Gr=Jr[Ha].x),Jr[Ha].yHr&&(Hr=Jr[Ha].y);return[si,Sr,Gr-si,Hr-Sr]}(B),yn=Jr=>[(Jr.x-Ls)/Bs,(Jr.y-sn)/nn],[Tn,Gn,zn,Dn]=B.map(yn),Mr=function(Jr,si,Gr,Sr,Hr,Ha,$r,Ya){const Oi=Ua(0,0,1,0,1,1,0,1),Do=Ua(Jr,si,Gr,Sr,Hr,Ha,$r,Ya),to=o.cU([],Do);return o.cV(Oi,Oi,to)}(Tn[0],Tn[1],Gn[0],Gn[1],zn[0],zn[1],Dn[0],Dn[1]);this.elevatedGlobePerspectiveTransform=Aa(Tn[0],Tn[1],Gn[0],Gn[1],zn[0],zn[1],Dn[0],Dn[1]);const kn=(Jr,si)=>{bt.push(Jr.lng);const Gr=Math.round((Jr.lng-ss)/Lt*o.a6),Sr=Math.round((Jr.lat-Jt)/ps*o.a6),Hr=yn(si),Ha=o.cT([],[Hr[0],Hr[1],1],Mr),$r=Math.round(Ha[0]/Ha[2]*o.a6),Ya=Math.round(Ha[1]/Ha[2]*o.a6);Gs.emplaceBack(Gr,Sr,$r,Ya)},pr=B[3].x-B[0].x,ta=B[3].y-B[0].y,ka=B[2].x-B[1].x,qr=B[2].y-B[1].y;for(let Jr=0;Jr{Ls.emplaceBack(Bs,nn,yn);const Tn=bt[Bs],Gn=bt[nn],zn=bt[yn],Dn=Math.min(Math.min(Tn,Gn),zn),Mr=Math.max(Math.max(Tn,Gn),zn)-Dn;Mr>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=Mr),Gs.push(Dn+Mr/2)};for(let Bs=0;BsDn);yn.sort((zn,Dn)=>Bs[zn]-Bs[Dn]);const Tn=[],Gn=new o.ae;for(let zn=0;zn{oe.segments.push({vertexOffset:0,primitiveOffset:Ze,vertexLength:T.segments[0].vertexLength,primitiveLength:Xe,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||he(Ze,o.cR(B,Ze+1,B.length,K+360-we)-Ze),oe}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))):oe&&(this._setTileJSON(oe),Ui.updateCrossSourceElevationGate&&this.map.style&&Ui.updateCrossSourceElevationGate(this.map.style),o.cK(oe.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 oe=Q?Q.find(we=>we!=null):null,he=o.cM(this._options,oe,this.map._requestManager);he instanceof Error?k(he):k(null,he)})().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 oe=await this.map._requestManager.transformRequest(B,o.R.Tile,Q.signal);if(Q.signal.aborted)return k(null);this.dispatchTile(L,B,T,oe,Q,K,k)}catch(oe){if(Q.signal.aborted)return k(null);k(oe)}}dispatchTile(L,k,T,B,K,Q,oe){const he=this.map.style?this.map.style.getLut(this.scope):null,we=he?{image:he.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 dt=this.map.painter,_t=dt?dt.frcCoverageFadeRange:null;if(_t==null)return null;const bt=dt?dt.frcCoverageSnapshot:null,Mt=this.map.transform.zoom<_t[0],ss=bt?bt.getTileOrParent(L.tileID.canonical):null,Jt=L.tileID.overscaledZ>=Math.ceil(_t[1]),Lt=bt&&Jt?bt.getFullCoverageMask(L.tileID.canonical):null;return{frcMask:Jt?Lt??null:null,resolved:Mt||bt!=null,polygons:ss&&ss.frcMask!==0?ss.polygons:null,tileZoom:ss&&ss.frcMask!==0?ss.tileId.z:null,sourceLayers:dt?dt.frcCoverageSourceLayers:["road","structure"]}})(),terrainEnabled:ah(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,{},Xe.bind(this));else{const dt=o.cH.call({deduped:this._deduped},Ze,(_t,bt)=>{L.aborted||(_t||!bt?Xe.call(this,_t):(Ze.data={rawData:bt.rawData.slice(0),headers:bt.headers},L.actor&&(L.request=L.actor.sendCancelable("loadTile",Ze,{},Xe.bind(this)))))},!0);K.signal.addEventListener("abort",dt,{once:!0})}else L.request=L.actor.sendCancelable("reloadTile",Ze,{},Xe.bind(this));function Xe(dt,_t){return delete L.request,L.aborted?oe(null):dt?oe(dt):(_t&&_t.resourceTiming&&(L.resourceTiming=_t.resourceTiming),this.map._refreshExpiredTiles&&_t&&L.setExpiryData(o.cI(_t.headers)),void(function(){if(L.aborted)return oe(null);L.loadVectorData(_t,this.map.painter),o.cJ(this.dispatcher),oe(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:lr,"raster-dem":class extends lr{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 oe=Q?Q.find(we=>we!=null):null,he=o.cM(this._options,oe,this.map._requestManager);he instanceof Error?k(he):k(null,he)})().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,oe){return delete L.request,L.aborted?k(null):Q?(L.state="errored",k(Q)):(oe&&(this.map._refreshExpiredTiles&&L.setExpiryData(o.cI(oe.headers)),oe.borderReady||L.neighboringTiles||(L.neighboringTiles=this._getNeighboringTiles(L.tileID)),L.dem=oe.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,oe=k.x+1===T?L.wrap+1:L.wrap,he={};return he[new o.bQ(L.overscaledZ,K,k.z,B,k.y).key]={backfilled:!1},he[new o.bQ(L.overscaledZ,oe,k.z,Q,k.y).key]={backfilled:!1},k.y>0&&(he[new o.bQ(L.overscaledZ,K,k.z,B,k.y-1).key]={backfilled:!1},he[new o.bQ(L.overscaledZ,L.wrap,k.z,k.x,k.y-1).key]={backfilled:!1},he[new o.bQ(L.overscaledZ,oe,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,oe={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,oe,{},(he,we)=>Q&&!we?(L.state="loaded",k(null)):(delete L.request,L.destroy(!1),L.aborted?k(null):he?k(he):(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 is(`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 is(`sources.${L}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.f(new is(`sources.${L}`,null,'missing required property "coordinates"'))),k.animate&&typeof k.animate!="boolean"&&this.fire(new o.f(new is(`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 is(`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 is(`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 oe=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(oe===void 0)return L.state="errored",k(null);if(oe===null)return this.loadTileData(L,{width:this.tileSize,height:this.tileSize,data:null}),L.state="loaded",k(null);if(!function(he){return he instanceof ImageData||he instanceof HTMLCanvasElement||he instanceof ImageBitmap||he instanceof HTMLImageElement}(oe))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,oe),L.state="loaded",k(null)}catch(oe){if(Q.signal.aborted)return;L.state="errored",k(oe)}}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"}))}}},oo=function(L,k,T,B){const K=Lc(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},Lc=function(L){return Object.hasOwn(bl,L)?bl[L]:void 0};function hf([L,k],T,B,{scaled:K=!0}={}){const{tileSize:Q,buffer:oe}=B,{x:he,y:we,z:Me}=T;if(!isFinite(he)||!isFinite(we)||!isFinite(Me))throw new Error("Invalid MRT header");const Re=2**Me,Ze=Re*o.a7(L),Xe=Re*o.a8(k);return function([dt,_t],bt,{scaled:Mt=!0}={}){if(!bt)throw new Error("bandView is undefined");const{data:ss,tileSize:Jt,buffer:Lt,offset:ps,scale:Gs,dimension:Ls}=bt;if(dt<-Lt||dt>Jt+Lt||_t<-Lt||_t>Jt+Lt)throw new Error(`Point (${dt}, ${_t}) out of bounds for tileSize=${Jt}, buffer=${Lt}`);const sn=(_t+Lt)*(Jt+2*Lt)+(dt+Lt);if(new Uint32Array(ss.buffer)[sn]===4294967295)return null;let Bs=[];Bs=Mt?[]:new bt.data.constructor(Ls);for(let nn=0;nn=Xe||Ze<0||Ze>=Xe)throw new Xl(`Invalid overzoom, ${we}/${oe}/${he} is not a child of ${Q}/${B}/${K}.`);const dt=0|Math.log2(L),_t=Math.min(Me,dt),bt=Me-_t,Mt=L>>_t;return{offset:[(Re>>bt)*Mt,(Ze>>bt)*Mt],tileSize:Mt,deltaZ:Me}}o.c_.setPbf(o.c$);class hm extends Px{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 oe=this.texturePerLayer.get(k)||B.getTileTexture(T.width);oe&&oe instanceof o.T?oe.update(T,{premultiply:!1}):(oe=new o.T(K,T,Q.RGBA8,{premultiply:!1}),oe.bind(Q.LINEAR,Q.CLAMP_TO_EDGE)),this.texturePerLayer.has(k)||this.texturePerLayer.set(k,oe)}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:oe,headers:he})=>{try{const we=B.getHeaderLength(oe);if(we>k)return void(this.request=this.fetchHeader(we,T));B.parseHeader(oe),this._isHeaderLoaded=!0;let Me=0;for(const Re of Object.values(B.layers))Me=Math.max(Me,Re.dataIndex.at(-1).lastByte);oe.byteLength>=Me&&(this.entireBuffer=oe),T(null,this.entireBuffer||oe,he)}catch(we){T(we)}}).catch(oe=>{Q.signal.aborted||T(oe)}),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 oe=this.textureDescriptorPerLayer.get(T);K(null,oe?oe.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 oe=this.actor;if(!oe)return void K(new Error("Can't fetch tile band without an actor"));let he;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)=>{he.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,ss=!1;if(T!==null){const Lt=this._workQueuePerLayer.get(T)||[];Lt.push(()=>{ss=!0,Mt&&Mt.abort(),he.cancel()}),this._workQueuePerLayer.has(T)||this._workQueuePerLayer.set(T,Lt)}const Jt=()=>{ss||(Mt=oe.sendCancelable("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:bt,task:he},{},Re))};this.workerReady!==void 0?this.workerReady.then(Jt).catch(Lt=>K(Lt)):Jt()};let Xe;try{Xe=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(!Xe)return void K(new Error(`Unknown sourceLayer "${k}"`));if(Xe.hasDataForBand(B))return Me.forEach(_t=>_t(null,null)),void this._taskQueue.delete(we);const dt=Xe.getDataRange([B]);if(he=Q.createDecodingTask(dt),!he||he.tasks.length)if(T!==null&&this.flushQueues(T),this.entireBuffer)Ze(null,this.entireBuffer.slice(dt.firstByte,dt.lastByte+1));else{const _t={...this.requestParams,headers:{Range:`bytes=${dt.firstByte}-${dt.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(),he.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:oe,buffer:he,offset:we,scale:Me}=K.getBandView(B);if(this.parentTile&&this.overzoomCoordsPerLayer){const dt=this.overzoomCoordsPerLayer.get(k);dt&&(Q=this.cropBandData(Q,oe,he,dt),oe=dt.tileSize)}const Re=oe+2*he,Ze=new o.b({width:Re,height:Re},Q),Xe=this.texturePerLayer.get(T);Xe&&Xe instanceof o.T&&Xe.update(Ze,{premultiply:!1}),this.textureDescriptorPerLayer.set(T,{layer:k,band:B,img:Ze,buffer:he,offset:we,tileSize:oe,format:K.pixelFormat,mix:[Me,256*Me,65536*Me,16777216*Me]})}cropBandData(k,T,B,K){const{offset:Q,tileSize:oe}=K,he=T+2*B,we=oe+2*B;return function(Me,Re,Ze,Xe){const dt=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[dt];if(!_t)throw new Error(`Invalid data type "${dt}"`);const bt=Re[2]*Re[3],Mt=Re[1]*bt,ss=Ze[2]*Ze[3],Jt=Ze[1]*ss,Lt=new _t(Jt*Ze[0]);for(let ps=0;psnew hm(L,k,T,B,K);const To={RasterArrayTileSource:class extends lr{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 oe=Q.parentTile;oe&&L[oe.tileID.key]&&T.push(oe.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 oe=this._pendingParentWaiters.get(L.uid)||[];this._pendingParentWaiters.delete(L.uid);const he=Q?null:new Error("Parent tile failed to load");for(const we of oe)we(he)};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 oe=he=>{L._isLoadInProgress=!1,k(he)};this._waitForParent(Q,he=>{if(he||!L.setupOverzoom(Q))return L.state="errored",void oe(he||new Error("Parent tile setup failed"));L.state="loaded",oe(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=(oe,he,we)=>{if(delete L.request,L.aborted)return k(null);if(oe)return(oe.status===404||typeof oe.message=="string"&&oe.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(oe));if(this.map._refreshExpiredTiles&&he&&L.setExpiryData(o.cI(we)),this.partial&&L.state!=="expired")L.state="empty";else if(!this.partial){if(!he)return k(null);L.state="loaded",L._isHeaderLoaded=!0,L._mrt=he}k(null)};try{const oe=await this.map._requestManager.transformRequest(B,o.R.Tile,K.signal);if(K.signal.aborted)return k(null);L.requestParams=oe;const he={request:oe,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",he,{},(we,Me)=>we?Q(we):Me?void Q(null,Me.mrt,Me.headers):Q(null,null))}catch(oe){if(K.signal.aborted)return k(null);L.state="errored",k(oe)}}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,oe]=K.split("/"),he=B.getLayer(Q);if(!he||!he.hasBand(oe)||!he.hasDataForBand(oe))continue;const{bytes:we,tileSize:Me,buffer:Re}=he.getBandView(oe),Ze=Me+2*Re,Xe={data:new o.b({width:Ze,height:Ze},we),pixelRatio:2,sdf:!1,usvg:!1,version:0};T.set(K,Xe)}return T}queryRasterArrayValueByBandId(L,k,T){const B=k._mrt;return new Promise(K=>{const Q={},oe=new Set;for(const[he,we]of Object.entries(B.layers)){if(T.layerName&&he!==T.layerName)continue;const Me={};Q[he]=Me;for(const{bands:Re}of we.dataIndex)for(const Ze of Re)T.bands&&!T.bands.includes(Ze)||(oe.add(o.m(he,Ze)),k.fetchBand(he,null,Ze,Xe=>{o.e.frame(()=>{Me[Ze]=Xe?null:hf([L.lng,L.lat],B,we.getBandView(Ze)),oe.delete(o.m(he,Ze)),oe.size===0&&K(Q)})}))}oe.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||oe<0||oe>=B)return null;const he=this.map.style.getSourceCache(this.id),we=new o.bQ(T,K,T,Q,oe);return he.findLoadedParent(we,this.minzoom)}}},Ql=To,$c={model:()=>gr().then(()=>xr.ModelSource),"batched-model":()=>gr().then(()=>xr.Tiled3dModelSource),"raster-array":()=>async function(){return Promise.resolve()}().then(()=>Ql.RasterArrayTileSource)};class If 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 rg(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 Yd(L,k,T,B=""){if(L.uniqueFeatureID){const K=rg(L,k,B);if(T.has(K))return!0;T.add(K)}return!1}function ag(L,k,T,B,K=!1,Q=void 0){const oe=k.sourceCache.transform,he=k.sourceCache.tilesIn(L,k.has3DLayers,K);he.sort(ud);const we=[];for(const Me of he){const Re=Me.tile.queryRenderedFeatures(k,Me,T,B,oe,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 Xe of Me){const dt=Xe.queryResults,_t=Xe.wrappedTileID,bt=Ze[_t]=Ze[_t]||{};for(const Mt in dt){const ss=dt[Mt],Jt=bt[Mt]=bt[Mt]||{},Lt=Re[Mt]=Re[Mt]||[];for(const ps of ss)Jt[ps.featureIndex]||(Jt[ps.featureIndex]=!0,Lt.push(ps))}}return Re}(we)}function Lh(L,k,T,B,K,Q){const oe={},he=B.queryRenderedSymbols(L),we=[];for(const Me of Object.keys(he).map(Number))we.push(K[Me]);we.sort(ud);for(const Me of we){const Re=Me.featureIndex.lookupSymbolFeatures(he[Me.bucketInstanceId],Me.bucketIndex,Me.sourceLayerIndex,k,T,Q);for(const Ze in Re){const Xe=oe[Ze]=oe[Ze]||[],dt=Re[Ze];dt.sort((_t,bt)=>{const Mt=Me.featureSortOrder;if(Mt){const ss=Mt.indexOf(_t.featureIndex);return Mt.indexOf(bt.featureIndex)-ss}return bt.featureIndex-_t.featureIndex});for(const _t of dt)Xe.push(_t)}}return oe}function mf(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,oe=this.style.getLayerSourceCache(Q);let he=1;Q.type==="fill-extrusion"?he=K.visible?Q.paint.get("fill-extrusion-vertical-scale"):0:Q.type==="building"&&(he=K.visible?Q.paint.get("building-vertical-scale"):0);let we=oe?oe.getTile(T):null;if(!we&&oe)for(const Me in oe._tiles){const Re=oe._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:he})}k.hasAnyZOffset=!1;let B=!1;for(let K=0;K{oe in K&&(Q[oe]=K[oe])}),T}function ip(L){L=L.slice();const k=Object.create(null);for(const T of L)k[T.id]=T;for(let T=0;T0?(K-oe)/he:0;return this.points[Q].mult(1-we).add(this.points[T].mult(we))}}const vh=100;class xc{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+vh,this.screenBottomBoundary=k.height+vh,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,oe,he,we,Me,Re,Ze){let Xe=B.projectedAnchorX,dt=B.projectedAnchorY,_t=B.projectedAnchorZ;const bt=B.tileAnchorX,Mt=B.tileAnchorY,ss=B.elevation,Jt=B.tileID,Lt=k.getProjection();if(ss&&Jt){const[zn,Dn,Mr]=Lt.upVector(Jt.canonical,B.tileAnchorX,B.tileAnchorY),kn=Lt.upVectorScale(Jt.canonical,this.transform.center.lat,this.transform.worldSize).metersToTile;Xe+=zn*ss*kn,dt+=Dn*ss*kn,_t+=Mr*ss*kn}const ps=k.projection.name==="globe",Gs=k.projection.name==="globe"?o.S(this.transform.zoom):0;if(Jt&&ps&&Gs<1&&!oe){const zn=1<0,Lt),sn=Me*Ls.perspectiveRatio,Bs=(B.x1*T+he.x-B.padding)*sn+Ls.point.x,nn=(B.y1*T+he.y-B.padding)*sn+Ls.point.y,yn=(B.x2*T+he.x+B.padding)*sn+Ls.point.x,Tn=(B.y2*T+he.y+B.padding)*sn+Ls.point.y,Gn=Ls.perspectiveRatio<=o.d9||Ls.occluded;return!this.isInsideGrid(Bs,nn,yn,Tn)||!we&&this.grid.hitTest(Bs,nn,yn,Tn,Ze)||Gn?{box:[],offscreen:!1,occluded:Ls.occluded}:{box:[Bs,nn,yn,Tn],offscreen:this.isOffscreen(Bs,nn,yn,Tn),occluded:!1}}placeCollisionCircles(k,T,B,K,Q,oe,he,we,Me,Re,Ze,Xe,dt,_t,bt,Mt){const ss=[],Jt=this.transform.elevation,Lt=k.getProjection(),ps=k.elevationType==="road",Gs=!!Jt||ps,Ls=o.c2.getAtTileOffsetFunc(Mt,this.transform.center.lat,this.transform.worldSize,Lt),sn=new o.P(B.tileAnchorX,B.tileAnchorY),Bs=new o.P(B.tileAnchorX,B.tileAnchorY);let{x:nn,y:yn,z:Tn}=Lt.projectTilePoint(Bs.x,Bs.y,Mt.canonical),Gn=null;if(Gs){Gn=ps&&k.hdExt?k.hdExt.makeRoadSymbolElevationParams(k,k.text,K,Mt,Ls,Jt,Lt,this.transform.center.lat,this.transform.worldSize):{getElevation:Ls,elevation:Jt,elevationFeature:null};const[Ha,$r,Ya]=Gn.getElevation(sn,Jt,Gn.elevationFeature);nn+=Ha,yn+=$r,Tn+=Ya}const zn=Lt.name==="globe",Dn=this.projectAndGetPerspectiveRatio(we,nn,yn,Tn,Mt,zn||!!Jt||this.transform.pitch>0,Lt),{perspectiveRatio:Mr}=Dn,kn=(Xe?he/Mr:he*Mr)/o.dg,pr=o.da(nn,yn,Tn,Me),ta=B.lineOffsetX*kn,ka=B.lineOffsetY*kn,qr=o.av(k.layers[0].layout.get("text-max-angle")),Jr=Math.cos(qr),si=Dn.signedDistanceFromCamera>0?o.db(kn,oe,ta,ka,ps&&B.flipState===1,pr,Bs,B,Q,Me,{},Gs&&!Xe?Gn:null,Xe&&Gs,Lt,Mt,Xe,Jr):null;let Gr=!1,Sr=!1,Hr=!0;if(si&&!Dn.occluded){const Ha=.5*_t*Mr+bt,$r=new o.P(-100,-100),Ya=new o.P(this.screenRightBoundary,this.screenBottomBoundary),Oi=new dh,{first:Do,last:to}=si,ql=Do.path.length;let yu=[];for(let so=ql-1;so>=1;so--)yu.push(Do.path[so]);for(let so=1;so(Gs&&!zn&&(Gh=Gn.getElevation(_hso[3]<=0)&&(yu=[]));let Ko=[];if(yu.length>0){let so=1/0,_d=-1/0,Gh=1/0,_h=-1/0;for(const Vl of yu)so=Math.min(so,Vl[0]),Gh=Math.min(Gh,Vl[1]),_d=Math.max(_d,Vl[0]),_h=Math.max(_h,Vl[1]);_d>=$r.x&&so<=Ya.x&&_h>=$r.y&&Gh<=Ya.y&&(Ko=[yu.map(Vl=>new o.P(Vl[0],Vl[1]))],(so<$r.x||_d>Ya.x||Gh<$r.y||_h>Ya.y)&&(Ko=o.dc(Ko,$r.x,$r.y,Ya.x,Ya.y)))}for(const so of Ko){Oi.reset(so,.25*Ha);let _d=0;_d=Oi.length<=.5*Ha?1:Math.ceil(Oi.paddedLength/Uc)+1;for(let Gh=0;Gh<_d;Gh++){const _h=Gh/Math.max(_d-1,1),Vl=Oi.lerp(_h),mm=Vl.x+vh,yc=Vl.y+vh;ss.push(mm,yc,Ha,0);const dc=mm-Ha,Dh=yc-Ha,Wh=mm+Ha,Pd=yc+Ha;if(Hr=Hr&&this.isOffscreen(dc,Dh,Wh,Pd),Sr=Sr||this.isInsideGrid(dc,Dh,Wh,Pd),!T&&this.grid.hitTestCircle(mm,yc,Ha,dt)&&(Gr=!0,!Ze))return{circles:[],offscreen:!1,collisionDetected:Gr,occluded:!1}}}}return{circles:!Ze&&Gr||!Sr?[]:ss,offscreen:Hr,collisionDetected:Gr,occluded:Dn.occluded}}queryRenderedSymbols(k){if(k.length===0||this.grid.keysLength()===0&&this.ignoredGrid.keysLength()===0)return{};const T=[];let B=1/0,K=1/0,Q=-1/0,oe=-1/0;for(const Re of k){const Ze=new o.P(Re.x+vh,Re.y+vh);B=Math.min(B,Ze.x),K=Math.min(K,Ze.y),Q=Math.max(Q,Ze.x),oe=Math.max(oe,Ze.y),T.push(Ze)}const he=this.grid.query(B,K,Q,oe).concat(this.ignoredGrid.query(B,K,Q,oe)),we={},Me={};for(const Re of he){const Ze=Re.key;if(we[Ze.bucketInstanceId]===void 0&&(we[Ze.bucketInstanceId]={}),we[Ze.bucketInstanceId][Ze.featureIndex])continue;const Xe=this.clippedSymbols.get(Ze.bucketInstanceId);if(Xe&&Xe.has(Ze.featureIndex))continue;const dt=[new o.P(Re.x1,Re.y1),new o.P(Re.x2,Re.y1),new o.P(Re.x2,Re.y2),new o.P(Re.x1,Re.y2)];o.aU(T,dt)&&(we[Ze.bucketInstanceId][Ze.featureIndex]=!0,Me[Ze.bucketInstanceId]===void 0&&(Me[Ze.bucketInstanceId]=[]),Me[Ze.bucketInstanceId].push(Ze.featureIndex))}return Me}insertCollisionBox(k,T,B,K,Q){(T?this.ignoredGrid:this.grid).insert({bucketInstanceId:B,featureIndex:K,collisionGroupID:Q},k[0],k[1],k[2],k[3])}insertCollisionCircles(k,T,B,K,Q){const oe=T?this.ignoredGrid:this.grid,he={bucketInstanceId:B,featureIndex:K,collisionGroupID:Q};for(let we=0;we0?(o.c6(we,we,k),this.fogState&&Q&&he.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+vh,(-we[1]/Re+1)/2*this.transform.height+vh),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(he)/Re*.5,1.5),signedDistanceFromCamera:Re,occluded:oe&&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 ex(L,k,T,B,K){const{horizontalAlign:Q,verticalAlign:oe}=o.du(L),he=-(Q-.5)*k,we=-(oe-.5)*T,Me=o.dv(L,B);return new o.P(he+Me[0]*K,we+Me[1]*K)}function Zd(L,k,T,B,K){const Q=new o.P(L,k);return T&&Q._rotate(B?K:-K),Q}function ff(L,k,T,B){const{leftJustifiedTextSymbolIndex:K,centerJustifiedTextSymbolIndex:Q,rightJustifiedTextSymbolIndex:oe,verticalPlacedTextSymbolIndex:he,crossTileID:we}=T,Me=o.dw(k),Re=B===o.dt.vertical?he:Me==="left"?K:Me==="center"?Q:Me==="right"?oe:-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),oe>=0&&(L.text.placedSymbolArray.get(oe).crossTileID=Re>=0&&oe!==Re?0:we),he>=0&&(L.text.placedSymbolArray.get(he).crossTileID=Re>=0&&he!==Re?0:we)}function Td(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:oe,rightJustifiedTextSymbolIndex:he,verticalPlacedTextSymbolIndex:we}=T,Me=L.text.placedSymbolArray;Q>=0&&(Me.get(Q).placedOrientation=B),oe>=0&&(Me.get(oe).placedOrientation=B),he>=0&&(Me.get(he).placedOrientation=B),we>=0&&(Me.get(we).placedOrientation=K)}class Jl{constructor(k,T,B,K,Q,oe,he){this.transform=k.clone(),this.projection=k.projection.name,he instanceof xc?(he.reset(this.transform,Q),this.collisionIndex=he):this.collisionIndex=new xc(this.transform,Q),this.buildingIndex=oe,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=T,this.retainedQueryData={},this.collisionGroups=new Mp(B),this.collisionCircleArrays={},this.prevPlacement=K,K&&(K.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(k,T,B,K,Q=1){const oe=B.getBucket(T),he=B.latestFeatureIndex;if(!oe||!he||T.fqid!==oe.layerIds[0])return;const we=oe.layers[0].layout,Me=oe.layers[0].paint,Re=B.collisionBoxArray,Ze=Math.pow(2,this.transform.zoom-B.tileID.overscaledZ),Xe=B.tileSize/o.a6,dt=B.tileID.toUnwrapped();this.transform.setProjection(oe.projection);const _t=o.di(B.tileID,oe.getProjection(),this.transform,this.projection),bt=we.get("text-pitch-alignment")==="map",Mt=we.get("text-rotation-alignment")==="map";T.compileFilter(T.options);const ss=T.dynamicFilter(),Jt=T.dynamicFilterNeedsFeature(),Lt=T.dynamicFilterNeedsGeometry(),ps=this.transform.calculatePixelsToTileUnitsMatrix(B),Gs=o.dj(_t,B.tileID.canonical,bt,Mt,this.transform,oe.getProjection(),ps);let Ls=null;const sn=oe.getProjection().createInversionMatrix(this.transform,B.tileID.canonical);if(bt){const kn=o.dk(_t,B.tileID.canonical,bt,Mt,this.transform,oe.getProjection(),ps);Ls=o.X([],this.transform.labelPlaneMatrix,kn)}let Bs=null;ss&&B.latestFeatureIndex&&(Bs={unwrappedTileID:dt,dynamicFilter:ss,dynamicFilterNeedsFeature:Jt,needGeometry:Lt}),this.retainedQueryData[oe.bucketInstanceId]=new Jg(oe.bucketInstanceId,he,oe.sourceLayerIndex,oe.index,B.tileID);const[nn,yn]=oe.layers[0].layout.get("text-size-scale-range"),Tn=o.b1(Q,nn,yn),[Gn,zn]=we.get("icon-size-scale-range"),Dn=o.b1(Q,Gn,zn),Mr={bucket:oe,layout:we,paint:Me,posMatrix:_t,invMatrix:sn,mercatorCenter:[o.a7(this.transform.center.lng),o.a8(this.transform.center.lat)],textLabelPlaneMatrix:Gs,labelToScreenMatrix:Ls,clippingData:Bs,scale:Ze,textPixelRatio:Xe,holdingForFade:B.holdingForFade(),collisionBoxArray:Re,partiallyEvaluatedTextSize:o.dl(oe.textSizeData,this.transform.zoom,Tn),partiallyEvaluatedIconSize:o.dl(oe.iconSizeData,this.transform.zoom,Dn),collisionGroup:this.collisionGroups.get(oe.sourceID),latestFeatureIndex:B.latestFeatureIndex};if(K)for(const kn of oe.sortKeyRanges){const{sortKey:pr,symbolInstanceStart:ta,symbolInstanceEnd:ka}=kn;k.push({sortKey:pr,symbolInstanceStart:ta,symbolInstanceEnd:ka,parameters:Mr})}else k.push({symbolInstanceStart:0,symbolInstanceEnd:oe.symbolInstances.length,parameters:Mr})}placeLayerBucketPart(k,T,B,K=1){const{bucket:Q,layout:oe,paint:he,posMatrix:we,textLabelPlaneMatrix:Me,labelToScreenMatrix:Re,clippingData:Ze,textPixelRatio:Xe,mercatorCenter:dt,invMatrix:_t,holdingForFade:bt,collisionBoxArray:Mt,partiallyEvaluatedTextSize:ss,partiallyEvaluatedIconSize:Jt,collisionGroup:Lt,latestFeatureIndex:ps}=k.parameters,Gs=oe.get("text-optional"),Ls=oe.get("icon-optional"),sn=oe.get("text-allow-overlap"),Bs=oe.get("icon-allow-overlap"),nn=oe.get("text-rotation-alignment")==="map",yn=oe.get("icon-rotation-alignment")==="map",Tn=oe.get("text-pitch-alignment")==="map",Gn=he.get("symbol-z-offset"),zn=oe.get("symbol-elevation-reference")==="sea",Dn=oe.get("symbol-placement"),Mr=oe.get("text-variable-anchor"),kn=nn&&Dn!=="point",pr=yn&&Dn!=="point",ta=Mr&&Q.hasTextData(),ka=Q.hasIconTextFit()&&ta&&Q.hasIconData();this.transform.setProjection(Q.projection);const qr=ta||kn,Jr=pr||ka;let si=sn&&(Bs||!Q.hasIconData()||Ls),Gr=Bs&&(sn||!Q.hasTextData()||Gs);const Sr=!Gn.isConstant();!Q.collisionArrays&&Mt&&Q.deserializeCollisionBoxes(Mt);const Hr=($r,Ya,Oi)=>{const{crossTileID:Do,numVerticalGlyphVertices:to}=$r;let ql=null;if(Ze&&Ze.dynamicFilterNeedsFeature||Sr){const vu=this.retainedQueryData[Q.bucketInstanceId],id=ps.loadFeature({featureIndex:$r.featureIndex,bucketIndex:vu.bucketIndex,sourceLayerIndex:vu.sourceLayerIndex,layoutVertexArrayOffset:0}),Rc=id.properties?id.properties.worldview:null;if(Q.localizable&&Q.worldview&&typeof Rc=="string")if(Rc==="all")id.properties.$localized=!0;else{if(!Rc.split(",").includes(Q.worldview))return;id.properties.$localized=!0,id.properties.worldview=Q.worldview}ql=Ze&&Ze.needGeometry?o.bx(id,!0):id}if(Ze&&!(0,Ze.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:Q.worldview},ql,this.retainedQueryData[Q.bucketInstanceId].tileID.canonical,new o.P($r.tileAnchorX,$r.tileAnchorY),this.transform.calculateDistanceTileData(Ze.unwrappedTileID)))return this.placements[Do]=new Rf(!1,!1,!1,!0),void T.add(Do);const yu=Gn.evaluate(ql,{});if(($r.zOffset||0)+(yu||0)>0&&this.frontCutoffStart>0){const vu=2*this.frontCutoffStart-1,id=[$r.tileAnchorX,$r.tileAnchorY,0,1],Rc=o.c6(o.dr(),id,we);if(Rc[1]/Rc[3]{vu.tileID=this.retainedQueryData[Q.bucketInstanceId].tileID;const id=this.transform.elevation;if(Q.elevationType==="road")vu.elevation=zn?yu:yu+o.c2.getAtTileOffset(vu.tileID,new o.P(vu.tileAnchorX,vu.tileAnchorY),id,null);else{const Rc=Q.hdExt?Q.hdExt.elevationFeatures[$r.elevationFeatureIndex]:void 0;vu.elevation=zn?yu:yu+o.c2.getAtTileOffset(vu.tileID,new o.P(vu.tileAnchorX,vu.tileAnchorY),id,Rc)}vu.elevation+=$r.zOffset},cg=Oi.textBox;if(cg){Kh(cg);const vu=Rc=>{let Yh=o.dt.horizontal;if(Q.allowVerticalPlacement&&!Rc&&this.prevPlacement){const sx=this.prevPlacement.placedOrientations[Do];sx&&(this.placedOrientations[Do]=sx,Yh=sx,Td(Q,Yh,$r))}return Yh},id=(Rc,Yh)=>{if(Q.allowVerticalPlacement&&to>0&&Oi.verticalTextBox){for(const sx of Q.writingModes)if(sx===o.dt.vertical?(Vl=Yh(),mm=Vl):Vl=Rc(),Vl&&Vl.box&&Vl.box.length)break}else Vl=Rc()};if(Mr){let Rc=Mr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Do]){const Ku=this.prevPlacement.variableOffsets[Do];Rc.indexOf(Ku.anchor)>0&&(Rc=Rc.filter(Li=>Li!==Ku.anchor),Rc.unshift(Ku.anchor))}const Yh=(Ku,Li,wm)=>{const dg=Q.getSymbolInstanceTextSize(ss,$r,this.transform.zoom,Ya),rj=(Ku.x2-Ku.x1)*dg+2*Ku.padding,aj=(Ku.y2-Ku.y1)*dg+2*Ku.padding,Ob=$r.hasIconTextFit&&!Bs?Li:null;Ob&&Kh(Ob);let zb={box:[],offscreen:!1,occluded:!1};const Y2=sn?2*Rc.length:Rc.length;for(let Bb=0;Bb=Rc.length,$r,Ya,Q,wm,Ob,ss,Jt);if(yy&&(zb=yy.placedGlyphBoxes,zb&&zb.box&&zb.box.length)){Uc=!0,_h=yy.shift;break}}return zb};id(()=>Yh(cg,Oi.iconBox,o.dt.horizontal),()=>{const Ku=Oi.verticalTextBox;return Ku&&Kh(Ku),Q.allowVerticalPlacement&&!(Vl&&Vl.box&&Vl.box.length)&&to>0&&Ku?Yh(Ku,Oi.verticalIconBox,o.dt.vertical):{box:null,offscreen:null,occluded:null}}),Vl&&(Uc=Vl.box,so=Vl.offscreen,_d=Vl.occluded);const sx=vu(!(!Vl||!Vl.box));if(!Uc&&this.prevPlacement){const Ku=this.prevPlacement.variableOffsets[Do];Ku&&(this.variableOffsets[Do]=Ku,ff(Q,Ku.anchor,$r,sx))}}else{const Rc=(Yh,sx)=>{const Ku=Q.getSymbolInstanceTextSize(ss,$r,this.transform.zoom,Ya),Li=this.collisionIndex.placeCollisionBox(Q,Ku,Yh,dt,_t,qr,new o.P(0,0),sn,Xe,we,Lt.predicate);return Li&&Li.box&&Li.box.length&&(Td(Q,sx,$r),this.placedOrientations[Do]=sx),Li};id(()=>Rc(cg,o.dt.horizontal),()=>{const Yh=Oi.verticalTextBox;return Q.allowVerticalPlacement&&to>0&&Yh?(Kh(Yh),Rc(Yh,o.dt.vertical)):{box:null,offscreen:null,occluded:null}}),vu(!!(Vl&&Vl.box&&Vl.box.length))}}if(yc=Vl,Uc=yc&&yc.box&&yc.box.length>0,so=yc&&yc.offscreen,_d=yc&&yc.occluded,$r.useRuntimeCollisionCircles){const vu=$r.centerJustifiedTextSymbolIndex>=0?$r.centerJustifiedTextSymbolIndex:$r.verticalPlacedTextSymbolIndex,id=Q.text.placedSymbolArray.get(vu),Rc=o.ds(Q.textSizeData,ss,id),Yh=oe.get("text-padding");dc=this.collisionIndex.placeCollisionCircles(Q,sn,id,vu,Q.lineVertexArray,Q.glyphOffsetArray,Rc,we,Me,Re,B,Tn,Lt.predicate,$r.collisionCircleDiameter*Rc/o.dg,Yh,this.retainedQueryData[Q.bucketInstanceId].tileID),Uc=sn||dc.circles.length>0&&!dc.collisionDetected,so=so&&dc.offscreen,_d=dc.occluded}if(Oi.iconFeatureIndex&&(vc=Oi.iconFeatureIndex),Oi.iconBox){const vu=id=>{Kh(id);const Rc=$r.hasIconTextFit&&_h?Zd(_h.x,_h.y,nn,Tn,this.transform.angle):new o.P(0,0),Yh=Q.getSymbolInstanceIconSize(Jt,this.transform.zoom,$r.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(Q,Yh,id,dt,_t,Jr,Rc,Bs,Xe,we,Lt.predicate)};mm&&mm.box&&mm.box.length&&Oi.verticalIconBox?(Dh=vu(Oi.verticalIconBox),Ko=Dh.box.length>0):(Dh=vu(Oi.iconBox),Ko=Dh.box.length>0),so=so&&Dh.offscreen,Gh=Dh.occluded}const H_=Gs||$r.numHorizontalGlyphVertices===0&&to===0,Jy=Ls||$r.numIconVertices===0;if(H_||Jy?Jy?H_||(Ko=Ko&&Uc):Uc=Ko&&Uc:Ko=Uc=Ko&&Uc,Uc&&yc&&yc.box&&this.collisionIndex.insertCollisionBox(yc.box,oe.get("text-ignore-placement"),Q.bucketInstanceId,mm&&mm.box&&Pd?Pd:Wh,Lt.ID),Ko&&Dh&&this.collisionIndex.insertCollisionBox(Dh.box,oe.get("icon-ignore-placement"),Q.bucketInstanceId,vc,Lt.ID),dc&&(Uc&&this.collisionIndex.insertCollisionCircles(dc.circles,oe.get("text-ignore-placement"),Q.bucketInstanceId,Wh,Lt.ID),B)){const vu=Q.bucketInstanceId;let id=this.collisionCircleArrays[vu];id===void 0&&(id=this.collisionCircleArrays[vu]=new Tp);for(let Rc=0;Rc=0;--Ya){const Oi=$r[Ya];Hr(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 $r=Q.getSortedIndexesByZOffset();for(let Ya=0;Ya<$r.length;++Ya){const Oi=$r[Ya];Hr(Q.symbolInstances.get(Oi),Oi,Q.collisionArrays[Oi])}}else for(let $r=k.symbolInstanceStart;$r0){let Gn;return this.prevPlacement&&this.prevPlacement.variableOffsets[Bs]&&this.prevPlacement.placements[Bs]&&this.prevPlacement.placements[Bs].text&&(Gn=this.prevPlacement.variableOffsets[Bs].anchor),this.variableOffsets[Bs]={textOffset:nn,width:oe,height:he,anchor:k,textScale:we,prevAnchor:Gn},ff(ss,k,bt,Jt),ss.allowVerticalPlacement&&(Td(ss,Jt,bt),this.placedOrientations[Bs]=Jt),{shift:yn,placedGlyphBoxes:Tn}}}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:{},oe=T?T.variableOffsets:{},he=T?T.placedOrientations:{};for(const we in this.placements){const Me=this.placements[we],Re=Q[we];Re?(this.opacities[we]=new Bm(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 Bm(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 Bm(Me,K,!1,!1);Re.isHidden()||(this.opacities[we]=Re,B=B||Me.text.placed||Me.icon.placed)}}for(const we in oe)this.variableOffsets[we]||!this.opacities[we]||this.opacities[we].isHidden()||(this.variableOffsets[we]=oe[we]);for(const we in he)this.placedOrientations[we]||!this.opacities[we]||this.opacities[we].isHidden()||(this.placedOrientations[we]=he[we]);B?this.lastPlacementChangeTime=k:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=T?T.lastPlacementChangeTime:k)}updateLayerOpacities(k,T,B,K,Q=!1,oe=1){K&&(this.lastReplacementSourceUpdateTime=K.updateTime);const he=new Set;for(const we of T){const Me=we.getBucket(k);if(Me&&we.latestFeatureIndex&&k.fqid===Me.layerIds[0]&&(this.updateBucketOpacities(Me,he,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,Xe]=Re.get("text-size-scale-range"),[dt,_t]=Re.get("icon-size-scale-range"),bt=o.b1(oe,Ze,Xe),Mt=o.b1(oe,dt,_t);Me.updateCollisionDebugBuffers(this.transform.zoom,we.collisionBoxArray,bt,Mt)}}}updateBucketOpacities(k,T,B,K,Q,oe,he,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(),Xe=new Bm(null,0,!1,!1,!0),dt=Me.get("text-allow-overlap"),_t=Me.get("icon-allow-overlap"),bt=Me.get("text-variable-anchor"),Mt=Me.get("text-rotation-alignment")==="map",ss=Me.get("text-pitch-alignment")==="map",Jt=Re.get("symbol-z-offset"),Lt=Me.get("symbol-elevation-reference")==="sea",ps=!Jt.isConstant(),Gs=new Bm(null,0,dt&&(_t||!k.hasIconData()||Me.get("icon-optional")),_t&&(dt||!k.hasTextData()||Me.get("text-optional")),!0);!k.collisionArrays&&K&&(k.hasIconCollisionBoxData()||k.hasTextCollisionBoxData())&&k.deserializeCollisionBoxes(K);const Ls=(Bs,nn,yn)=>{for(let Tn=0;Tn0||Tn>0,si=zn>0,Gr=this.placedOrientations[Gn],Sr=Gr===o.dt.vertical,Hr=Gr===o.dt.horizontal||Gr===o.dt.horizontalOnly;!Jr&&!si||qr.isHidden()||sn++;let Ha=!1;if((Jr||si)&&oe)for(const $r of k.activeReplacements){if(o.dm($r,Q,o.dn.Symbol,we)||$r.min.x>Dn||Dn>$r.max.x||$r.min.y>Mr||Mr>$r.max.y)continue;const Ya=o.dp(Dn,Mr,he.canonical,$r.footprintTileId.canonical);if(Ha=o.dq(Ya,$r.footprint),Ha)break}if(Ha&&this.collisionIndex.markSymbolAsClipped(k.bucketInstanceId,nn.featureIndex),Jr){const $r=Ha?ig:B1(qr.text);Ls(k.text,yn,Sr?ig:$r),Ls(k.text,Tn,Hr?ig:$r);const Ya=qr.text.isHidden(),{leftJustifiedTextSymbolIndex:Oi,centerJustifiedTextSymbolIndex:Do,rightJustifiedTextSymbolIndex:to,verticalPlacedTextSymbolIndex:ql}=nn,yu=k.text.placedSymbolArray,Uc=Ya||Sr?1:0;Oi>=0&&(yu.get(Oi).hidden=Uc),Do>=0&&(yu.get(Do).hidden=Uc),to>=0&&(yu.get(to).hidden=Uc),ql>=0&&(yu.get(ql).hidden=Ya||Hr?1:0);const Ko=this.variableOffsets[Gn];Ko&&ff(k,Ko.anchor,nn,Gr);const so=this.placedOrientations[Gn];so&&(ff(k,"left",nn,so),Td(k,so,nn))}if(si){const $r=Ha?ig:B1(qr.icon),{placedIconSymbolIndex:Ya,verticalPlacedIconSymbolIndex:Oi}=nn,Do=k.icon.placedSymbolArray,to=qr.icon.isHidden()?1:0;Ya>=0&&(Ls(k.icon,zn,Sr?ig:$r),Do.get(Ya).hidden=to),Oi>=0&&(Ls(k.icon,nn.numVerticalIconVertices,Hr?ig:$r),Do.get(Oi).hidden=to)}if(k.hasIconCollisionBoxData()||k.hasTextCollisionBoxData()){const $r=k.collisionArrays[Bs];if($r){let Ya=new o.P(0,0),Oi=!0;if($r.textBox||$r.verticalTextBox){if(bt){const to=this.variableOffsets[Gn];to?(Ya=ex(to.anchor,to.width,to.height,to.textOffset,to.textScale),Mt&&Ya._rotate(ss?this.transform.angle:-this.transform.angle)):Oi=!1}Ze&&(Oi=!qr.clipped),$r.textBox&&Ud(k.textCollisionBox.collisionVertexArray,qr.text.placed,!Oi||Sr,ta,Lt,Ya.x,Ya.y),$r.verticalTextBox&&Ud(k.textCollisionBox.collisionVertexArray,qr.text.placed,!Oi||Hr,ta,Lt,Ya.x,Ya.y)}const Do=Oi&&!!(!Hr&&$r.verticalIconBox);$r.iconBox&&Ud(k.iconCollisionBox.collisionVertexArray,qr.icon.placed,Do,ta,Lt,nn.hasIconTextFit?Ya.x:0,nn.hasIconTextFit?Ya.y:0),$r.verticalIconBox&&Ud(k.iconCollisionBox.collisionVertexArray,qr.icon.placed,!Do,ta,Lt,nn.hasIconTextFit?Ya.x:0,nn.hasIconTextFit?Ya.y:0)}}}if(k.fullyClipped=sn===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 Bs=this.collisionCircleArrays[k.bucketInstanceId];k.placementInvProjMatrix=Bs.invProjMatrix,k.placementViewportMatrix=Bs.viewportMatrix,k.collisionCircleArray=Bs.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 Ud(L,k,T,B,K,Q,oe){L.emplaceBack(k?1:0,T?1:0,Q||0,oe||0,B,K?1:0),L.emplaceBack(k?1:0,T?1:0,Q||0,oe||0,B,K?1:0),L.emplaceBack(k?1:0,T?1:0,Q||0,oe||0,B,K?1:0),L.emplaceBack(k?1:0,T?1:0,Q||0,oe||0,B,K?1:0)}const bd=Math.pow(2,25),Df=Math.pow(2,24),Fx=Math.pow(2,17),O1=Math.pow(2,16),bm=Math.pow(2,9),Fk=Math.pow(2,8),z1=Math.pow(2,1);function B1(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*bd+k*Df+T*Fx+k*O1+T*bm+k*Fk+T*z1+k}const ig=0;class Rb{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,oe){const he=this._bucketParts;for(;this._currentTileIndexwe.sortKey-Me.sortKey));this._currentPartIndex!this.isFullPlacementRequested()&&this._fadeDuration!==0&&o.e.now()-oe>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"),Xe=Re.layout.get("symbol-sort-key").constantOr(1)!==void 0,dt=Re.layout.get("symbol-z-order"),_t=dt==="viewport-y"||dt==="auto"&&!(dt!=="viewport-y"&&Xe),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,ss=this._inProgressLayer=this._inProgressLayer||new Rb(Re),Jt=o.m(we.source,we.scope);if(ss.continuePlacement(Ze||Mt?K[Jt]:B[Jt],this.placement,this._showCollisionBoxes,we,he,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 H2=512/o.a6/2;class Ok{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 oe=0;oeMt-ss);for(const Mt of bt){const ss=this.crossTileIDs[Mt];if(this.keys[Mt]===Re&&!B.has(ss)){B.add(ss),Me.crossTileID=ss;break}}}}}class py{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class gy{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 oe in K){const he=K[oe];he.tileID=he.tileID.unwrapTo(he.tileID.wrap+T),Q[he.tileID.key]=he}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 he in oe){const we=oe[he];we.tileID.isChildOf(k)&&we.findMatches(T.symbolInstances,k,K)}else{const he=oe[k.scaledTo(Number(Q)).key];he&&he.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 Db(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(!Ox(this._geometries[he],Q))return!1;const we=this._geometryData[he];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,oe):this._grid.hitTestCircle(Q.x+K,Q.y+K,Q.radius,oe))?"intersects":"does-not-intersect"}insert(k,T){const B=this._padding;let K=!1;for(const Q of k){if(!Ox(Q,this._workingArea))continue;const oe=this._geometries.length;this._geometries.push(Q),this._geometryData.push(T),Q.kind==="box"?this._grid.insert(oe,Q.left+B,Q.top+B,Q.right+B,Q.bottom+B):this._grid.insertCircle(oe,Q.x+B,Q.y+B,Q.radius),K=!0}return K}}function op(L){return 2*L.styleLayerId+L.symbolIdOrigin}function B_(L,k){const T=L.get(op(k.symbolId));if(!T)return!1;const B=T.get(k.symbolId.symbolId);return B!==void 0&&B.has(k.variantIdx)}function Yy(L,k){const T=op(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 zk{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 $1(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(op(k));return T!==void 0&&T.has(k.symbolId)}_addPlacedSymbol(k){const T=op(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&&Yy(this._ignoredSymbolVariantIds,Q.symbolVariantToIgnoreCollisionWith),Q.onlyIfPlaced&&Yy(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,oe){return Q.placementSubgroupOrder-oe.placementSubgroupOrder||Q.symbolPlacementPriority-oe.symbolPlacementPriority||Q.symbolVariantVisibility-oe.symbolVariantVisibility||Q.symbolPlacementType-oe.symbolPlacementType||Q.styleLayerOrder-oe.styleLayerOrder||Q.symbolDisplayOrder-oe.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 oe=B.placementRules.collisionRules.onlyIfPlaced;if(oe&&!B_(this._placedVariantIds,oe))Q=!1;else{const he=B.placementRules.collisionRules.symbolVariantToIgnoreCollisionWith;k.intersects(B.geometry,K?0:1,we=>{return he!==void 0&&(Me=we).variantIdx===(Re=he).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 oe=B_(this._ignoredSymbolVariantIds,B.variantId)?B.variantId:void 0;k.insert(B.geometry,oe)||(Q=!1)}Q&&(this._addPlacedSymbol(B.variantId.symbolId),B_(this._onlyIfPlacedReferencedIds,B.variantId)&&Yy(this._placedVariantIds,B.variantId)),K!==Q&&(Q?B.source.showSymbolVariant(B.variantId,T):B.source.hideSymbolVariant(B.variantId,T))}}}class ej{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 Zy 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 gr(),xr.loadModel?await xr.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=[],oe=[];for(const he of K){const we=k[he];this.hasURLBeenRequested(we)&&!B.forceReload||(this.modelByURL[we]={modelId:he,scope:T},Q.push(this.loadModel(he,we)),oe.push(he)),this.models[T][he]||(this.models[T][he]={model:null,numReferences:1})}this.numModelsLoading[T]=(this.numModelsLoading[T]||0)+oe.length,Promise.allSettled(Q).then(he=>{for(let we=0;we{this.fire(new o.f(new Error(`Could not load models: ${he.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:oe}=this.modelByURL[K];this.models[Q][oe].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 oe=this.models[T][k].model;if(!oe)return;delete this.models[T][k],oe.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 lp=["RENDER_SHADOWS","NORMAL_OFFSET"],U1=new Set(["symbol","circle"]),zx=class QHe{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(),oe=!(!B.projection||B.projection.name!=="globe"),he=Q||oe,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"),Xe=(dt,_t=[],bt={})=>{this._queue.push({programId:dt,params:{...bt.params,defines:_t,overrideFog:!!bt.fog,overrideTerrain:!!bt.terrain,overrideGlobe:!!bt.globe,overrideRtt:!!bt.rtt,precompiled:!0}})};for(const dt of k){if(dt.visibility==="none")continue;const _t=dt.getProgramIds();if(_t)for(const bt of _t){if(U1.has(bt))continue;const Mt=dt.getDefaultProgramParams(bt,T.zoom,B._styleColorTheme.lut);if(!Mt)continue;const ss=Me?Me.getShaderSource(bt):null,Jt=he&&(!ss||ss.usedDefines.has("RENDER_TO_TEXTURE"));let Lt=Mt.defines;if(Ze&&Jt&&(Lt=(Lt||[]).concat("USE_MRT1"),Me.emissiveMode==="mrt-full-rgba"&&(Lt=(Lt||[]).concat("USE_MRT1_RGBA"))),Re){Xe(bt,Mt.defines,{params:Mt}),Jt&&Xe(bt,Lt,{params:Mt,rtt:!0});continue}const ps=K&&(!ss||ss.usedDefines.has("FOG")),Gs=Q&&!dt.isDraped()&&(!ss||ss.usedDefines.has("TERRAIN")),Ls=oe&&(!ss||ss.usedDefines.has("GLOBE")),sn=we&&dt.hasElevation()&&(!ss||ss.usedDefines.has("RENDER_SHADOWS"));for(const Bs of sn?[!1,!0]:[!1]){const nn=Bs?(Mt.defines||[]).concat(lp):Mt.defines||[];for(const yn of Gs?[!1,!0]:[!1])for(const Tn of Ls?[!1,!0]:[!1])for(const Gn of ps?[!1,!0]:[!1])Xe(bt,nn,{params:Mt,fog:Gn,terrain:yn,globe:Tn})}Jt&&Xe(bt,Lt,{params:Mt,rtt:!0})}}if(Xe("clippingMask"),Q)for(const dt of[!1,!0])Xe("terrainRaster",dt?["TERRAIN_VERTEX_MORPHING"]:[],{terrain:!0,fog:K});if(!Re){if(k.some(dt=>dt.type==="hillshade")&&Xe("hillshadePrepare"),we)for(const dt of[!1,!0])for(const _t of[!1,!0]){const bt=[];dt&&bt.push("RENDER_CUTOFF"),bt.push("RENDER_SHADOWS"),_t&&bt.push("NORMAL_OFFSET"),Xe("groundShadow",bt),K&&Xe("groundShadow",bt,{fog:!0})}if(oe){for(const dt of[[],["TERRAIN_VERTEX_MORPHING"],["GLOBE_POLES"]])for(const _t of[!1,!0]){const bt=[...dt,"PROJECTION_GLOBE_VIEW"];_t&&bt.push("CUSTOM_ANTIALIASING"),Xe("globeRaster",bt,{terrain:Q,globe:!0,fog:K})}for(const dt of[!1,!0]){const _t=dt?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Xe("globeAtmosphere",_t,{fog:!0,terrain:Q,globe:dt}),Xe("globeAtmosphere",[..._t,"ALPHA_PASS"],{fog:!0,terrain:Q,globe:dt})}Xe("stars",[],{fog:K,terrain:Q,globe:!0})}}}_executeBatch(k,T,B){if(B.map&&B.map.isMoving())return void(this._idleHandle=o.e.requestIdleCallback(he=>this._executeBatch(he,T,B)));T.context.sweepPendingPrograms();const K=T.context.extParallelShaderCompile?QHe.DEADLINE_MARGIN_KHR_MS:QHe.DEADLINE_MARGIN_SYNC_MS;let Q=0;for(;this._queue.length>0;){const he=this._queue.shift();if(!he||he.programId in jr&&(T.style=B,T._fogVisible=!!he.params.overrideFog,T.getOrCreateProgram(he.programId,he.params),Q++,k.timeRemaining()<=K))break}const oe=this._queue.length===0||k.timeRemaining()>K;Q>0&&oe&&T.context.gl.flush(),this._idleHandle=this._queue.length>0||T.context._pendingPrograms.size>0?o.e.requestIdleCallback(he=>this._executeBatch(he,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}};zx.DEADLINE_MARGIN_KHR_MS=5,zx.DEADLINE_MARGIN_SYNC_MS=25;let cp=zx;const q1=o.s.colorTheme,C3=new o.ag({data:new o.ah(q1.data)});function Bk(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,oe=T*k,he=B*k;return[oe,he,oe+K*k,he+Q*k]}function VT(L){if(L)return L.map(([k,T])=>[k*o.e.devicePixelRatio,T*o.e.devicePixelRatio])}class Bv{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(oe=>this.sourceCache.getTile(oe)),Q=B.getImages(K,Array.from(this.pendingRequests));for(const[oe,he]of Q)k.set(o.I.from({name:oe,iconsetId:this.id}),he),this.pendingRequests.delete(oe);for(const oe of this.pendingRequests)this.missingRequests.add(oe);return this.pendingRequests.clear(),k}}const $v=(L,k)=>lm(L,k&&k.filter(T=>T.identifier!=="source.canvas")),V0=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"]),$_=new Set(["setCenter","setZoom","setBearing","setPitch"]),og=new Set(["background","sky","slot","custom","placement-group"]),H0={version:8,layers:[],sources:{}},Xy={duration:300,delay:0};class dp 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={...Xy},this._buildingIndex=new lu(this),this.crossTileSymbolIndex=new Jw,this.globalPlacement=null,this.symbolIdRangeAllocator=new ej,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(cu(),this);const B={referrer:o.dA(),config:o.dT()};if(this.map.painter&&this.map.painter.context){const Q=this.map.painter.context.maxUniformBufferBindings,oe=Math.floor(this.map.painter.context.maxUniformBlockSize/4);B.contextOptions={maxBindingPoints:Q,maxUniformBlockSizeDwords:oe}}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 Zy(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 cp: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=dp.registerForPluginStateChange(Q=>{K.dispatcher.send("syncRTLPluginState",{pluginStatus:Q.pluginStatus,pluginURL:Q.pluginURL}).then(oe=>{if(o.dD(null),oe.every(he=>he))for(const he in K._sourceCaches){const we=K._sourceCaches[he],Me=we.getSource().type;Me!=="vector"&&Me!=="geojson"||we.reload()}}).catch(oe=>{o.dD(oe)})}),this.on("data",Q=>{if(Q.dataType!=="source"||Q.sourceDataType!=="metadata")return;const oe=this.getOwnSource(Q.sourceId);if(oe&&oe.vectorLayerIds)for(const he in this._layers){const we=this._layers[he];we.source===oe.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),Mh();const K=(Q,oe)=>{try{oe(null,this.setState(Q,B))}catch(he){oe(he,!1)}};if(typeof k=="string"){const Q=this.map._requestManager.normalizeStyleURL(k),oe=new AbortController;this._request={cancel:()=>oe.abort()},(async()=>{const he=await this.map._requestManager.transformRequest(Q,o.R.Style,oe.signal),{data:we}=await o.g(he,oe.signal);this._request=null,K(we,T)})().catch(he=>{this._request=null,oe.signal.aborted||this.fire(new o.f(he))})}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&&Mh(),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 oe=await this.map._requestManager.transformRequest(k,o.R.Style,Q.signal),{data:he}=await o.g(oe,Q.signal);this._request=null,this.importsCache.set(k,he),this._load(he,B)})().catch(oe=>{this._request=null,Q.signal.aborted||this.fire(new o.f(oe))})}loadJSON(k,T={}){this.fire(new o.h("dataloading",{dataType:"style"}));const B=T.validate!==!1;B&&Mh(),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(H0,!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 oe=this._createFragmentStyle(Q),he=new Promise(Re=>{oe.once("style.import.load",Re),oe.once("error",Re)}).then(()=>{this.mergeAll(),this.fire(new o.h("data",{dataType:"style"}))});if(K.push(he),this.resolvedImports.has(Q.url)){oe.loadEmpty();continue}const we=Q.data||this.importsCache.get(Q.url);we?(Q.data?(oe.fire(new o.h("dataloading",{dataType:"style"})),oe.globalId=oe._getGlobalId(we),T&&Mh(),queueMicrotask(()=>{oe._load(we,T)})):oe.loadJSON(we,{validate:T}),this._isInternalStyle(we)&&(oe.globalId=null)):Q.url?oe.loadURL(Q.url,{validate:T}):oe.loadEmpty();const Me={style:oe,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 dp(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:""},oe={...H0,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(oe,T)}if(this.updateConfig(this._config,k.schema),T&&(await Mh(),!this.dispatcher.actors.length||$v(this,ws(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=ip(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 Vh(Me.properties,Me.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Vh(this.stylesheet.light)),this._layers=Object.create(null);let oe=!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)&&(oe=!0);const Ze=this.getOwnLayerSourceCache(Re),Xe=!!this.directionalLight&&this.directionalLight.shadowsEnabled();Ze&&Re.canCastShadows()&&Xe&&(Ze.castsShadows=!0)}if(oe&&um().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 Xe=Ze.layout.get("text-font");Xe&&Xe.value&&Xe.value.kind==="constant"&&Me.add(Xe.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 he=this.stylesheet.terrain;he&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||(this._startLiteLoad(),this._createTerrain(he,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(oe=>{o.w(`Couldn't load color theme from the stylesheet: ${oe}`),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,oe,he,we,Me,Re;const Ze={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(Xe=>{if(Xe.stylesheet){if(Xe.disableElevatedTerrain&&(this.disableElevatedTerrain=!0),Xe.light!=null&&(k=Xe.light),Xe.stylesheet.lights)for(const dt of Xe.stylesheet.lights)dt.type==="ambient"&&Xe.ambientLight!=null&&(T=Xe.ambientLight),dt.type==="directional"&&Xe.directionalLight!=null&&(B=Xe.directionalLight);K=this._prioritizeTerrain(K,Xe.terrain,Xe.stylesheet.terrain),Xe.stylesheet.fog&&Xe.fog!=null&&(Q=Xe.fog),Xe.stylesheet.snow&&Xe.snow!=null&&(oe=Xe.snow),Xe.stylesheet.rain&&Xe.rain!=null&&(he=Xe.rain),Xe.stylesheet.camera!=null&&(Re=Xe.stylesheet.camera),Xe.stylesheet.projection!=null&&(we=Xe.stylesheet.projection),Xe.stylesheet.transition!=null&&(Me=Xe.stylesheet.transition),Ze[Xe.scope]=Xe._styleColorTheme}}),this.light=k,this.ambientLight=T,this.directionalLight=B,this.fog=Q,this.snow=oe,this.rain=he,this._styleColorThemeForScope=Ze,K===null?delete this.terrain:this.terrain=K,this.camera=Re||{"camera-projection":"perspective"},this.projection=we||{name:"mercator"},this.transition={...Xy,...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(oe=>{for(const he in oe._sourceCaches){const we=o.m(he,oe.scope);k[we]=oe._sourceCaches[he]}for(const he in oe._otherSourceCaches){const we=o.m(he,oe.scope);T[we]=oe._otherSourceCaches[he]}for(const he in oe._symbolSourceCaches){const we=o.m(he,oe.scope);B[we]=oe._symbolSourceCaches[he]}for(const he in oe._fillExtrusionSourceCaches){const we=o.m(he,oe.scope);K[we]=oe._fillExtrusionSourceCaches[he]}if(oe._hdCoverage){const he=oe._hdCoverage.coverageSourceCaches;for(const we in he)Q[o.m(we,oe.scope)]=he[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||um().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(oe=>{for(const he of oe._order){const we=oe._layers[he];if(we.type==="slot"){const Me=o.dH(he);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=(oe=[])=>{for(const he of oe)if(he.type==="slot"){const we=o.dH(he.id);k[we]&&Q(k[we]),this._mergedSlots.push(we)}else{const we=o.m(he.id,he.scope);this._mergedOrder.push(we),B[we]=he,he.is3D(!!this.terrain)&&(this._has3DLayers=!0,K=this._mergedOrder.length-1),he.type==="circle"&&(this._hasCircleLayers=!0),he.type==="symbol"&&(this._hasSymbolLayers=!0),he.type==="clip"&&(this._clipLayerPresent=!0)}};if(Q(T),this._has3DLayers){const oe={};for(let he=0;heoe[he]-oe[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 he of Object.keys(q1))Q[he]===void 0&&(Q[he]=q1[he].default);const oe=new o.af(C3,T,new Map(K));return oe.setTransitionOrValue(Q,K),oe.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 oe=k;oe.startsWith(Q)||(oe=Q+oe);const he=o.I.from("mapbox-reserved-lut"),we=new Image;we.src=oe,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(he)&&this.removeImage(he),this.addImage(he,{data:new o.b({width:Me,height:Re},Ze),pixelRatio:1,sdf:!1,usvg:!1,version:0});const Xe=this.imageManager.getImage(he,this.scope);Xe?(this._styleColorTheme.lut={image:Xe.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,oe){let he,we,Me;const Re=o.e.devicePixelRatio>1?"@2x":"";function Ze(Xe){Me||Xe&&Q.aborted||(Xe&&(Me=Xe),function(){if(Me)oe(Me);else if(he&&we){const dt=o.e.getImageData(we),_t={};for(const bt in he){const{width:Mt,height:ss,x:Jt,y:Lt,sdf:ps,pixelRatio:Gs,stretchX:Ls,stretchY:sn,content:Bs}=he[bt],nn=new o.b({width:Mt,height:ss});o.b.copy(dt,nn,{x:Jt,y:Lt},{x:0,y:0},{width:Mt,height:ss},null),_t[bt]={data:nn,pixelRatio:Gs!==void 0?Gs:1,sdf:ps!==void 0&&ps,stretchX:Ls,stretchY:sn,content:Bs,usvg:!1,version:0}}oe(null,_t)}}())}(async function(){const Xe=await K.transformRequest(K.normalizeSpriteURL(B,Re,".json"),o.R.SpriteJSON,Q),{data:dt}=await o.g(Xe,Q);Me||(he=dt)})().then(()=>Ze(void 0),Xe=>Ze(Xe)),async function(){const Xe=await K.transformRequest(K.normalizeSpriteURL(B,Re,".png"),o.R.SpriteImage,Q),{data:dt}=await o.a(Xe,Q);Me||(we=dt)}().then(()=>Ze(void 0),Xe=>Ze(Xe))}(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 oe in K)Q.set(o.I.from(oe),K[oe]);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 Bv(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,oe,he){try{const we=await Q.transformRequest(Q.normalizeIconsetURL(K),o.R.Iconset,oe),{data:Me}=await o.d0(we,oe),Re={},Ze=function(Xe){const dt={icons:[]};let _t;for(;_t=Xe.nextField(void 0);)_t===1&&dt.icons.push(Z(Xe,Xe.readVarint()+Xe.pos));return dt}(new o.c$(Me));for(const Xe of Ze.icons){const dt={version:1,pixelRatio:o.e.devicePixelRatio,content:Bk(Xe),stretchX:Xe.metadata?VT(Xe.metadata.stretch_x_areas):void 0,stretchY:Xe.metadata?VT(Xe.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:Xe};Re[Xe.name]=dt}he(null,Re)}catch(we){oe.aborted||he(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 oe=new Map;for(const he in Q)oe.set(o.I.from(he),Q[he]);this.addImages(oe,!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:Xe}=Me[Re];(Ze||Xe)&&(this._updateWorkerLayers(Re,Ze,Xe),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 oe={};for(const Me in this._mergedSourceCaches){const Re=this._mergedSourceCaches[Me];oe[Me]=Re.used,Re.used=!1,Re.tileCoverLift=0}const he={};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(),um()),Re.mayUse("Standard")&&(Re.prepare(),gr()),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),Xe=this._mergedHdRoadCoverageSourceCaches[Ze];Xe&&!Xe.used&&(Xe.used=!0)}if(Re.type==="fill-extrusion"){const Ze=o.m(Re.source,Re.scope);if(Ze in this._mergedFillExtrusionSourceCaches){const Xe=Re.layout&&Re.layout.get("source-max-zoom");if(Xe!=null){const dt=he[Ze];he[Ze]=dt==null?Xe:Math.min(dt,Xe)}}}}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(he[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 oe){const Re=this._mergedSourceCaches[Me];oe[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(),$v(this,ws(k)))return!1;if((k=o.dG(k)).layers=ip(k.layers),!Mc.diffStyles)throw new Error("Debug module not loaded; cannot diff style.");const B=Mc.diffStyles(this.serialize(),k).filter(oe=>!$_.has(oe.command));if(B.length===0)return!1;const K=B.filter(oe=>!V0.has(oe.command));if(K.length>0)throw new Error(`Unimplemented: ${K.map(oe=>oe.command).join(", ")}.`);const Q=[];return B.forEach(oe=>{Q.push(this[oe.command](...oe.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(Ol,`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($c,T.type)&&!Lc(T.type),Q=K?new If(k,T,this.dispatcher,this):oo(k,T,this.dispatcher,this);Q.scope=this.scope;const oe=we=>{we.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(we.id),source:we.serialize(),sourceId:we.id}))};oe(Q);const he=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)};he(o.bS.Other),T.type!=="vector"&&T.type!=="geojson"||(he(o.bS.Symbol),T.type==="vector"&&he(o.bS.FillExtrusion)),Q.onAdd&&Q.onAdd(this.map),K&&async function(we){if(Lc(we))return;const Me=$c[we];if(!Me)throw new Error(`Unknown source type "${we}"`);const Re=await Me();Re&&!Lc(we)&&function(Ze,Xe){bl[Ze]=Xe}(we,Re)}(T.type).then(()=>{const we=Lc(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=oo(k,T,this.dispatcher,this);Re.scope=this.scope,oe(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,oe])=>oe.type==="source"&&oe.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 oe=this.ambientLight;oe.set(Q),oe.updateTransitions(T)}else this.ambientLight=new Ms(Q,fn(),this.scope,this.options);break;case"directional":if(this.directionalLight){const oe=this.directionalLight;oe.set(Q),oe.updateTransitions(T)}else this.directionalLight=new Ms(Q,Mn(),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=Xe=>.2126*(Xe[0]<=.03928?Xe[0]/12.92:Math.pow((Xe[0]+.055)/1.055,2.4))+.7152*(Xe[1]<=.03928?Xe[1]/12.92:Math.pow((Xe[1]+.055)/1.055,2.4))+.0722*(Xe[2]<=.03928?Xe[2]/12.92:Math.pow((Xe[2]+.055)/1.055,2.4)),K=k.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Q=k.properties.get("intensity"),oe=k.properties.get("direction"),he=1-o.b_(oe.x,oe.y,oe.z)[2]/90,we=B(K)*Q*he,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 oe of k[B].selectors){if(oe.featureNamespace){const we=this.getOwnLayer(oe.layer);if(!we){o.w(`Layer is undefined for selector: ${oe.layer}`);continue}const Me=T(we.source,we.sourceLayer);if(Me in K&&K[Me]!==oe.featureNamespace){o.w(`"featureNamespace ${oe.featureNamespace} of featureset ${B}'s selector is not associated to the same source, skip this selector`);continue}K[Me]=oe.featureNamespace}let he;if(oe.properties)for(const we in oe.properties){const Me=o.c(oe.properties[we]);Me.result==="success"&&(he=he||{},he[we]=Me.value)}Q.push({layerId:oe.layer,namespace:oe.featureNamespace,properties:he,uniqueFeatureID:oe._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 oe of K[k].selectors){const he=B.getOwnLayer(oe.layer);he&&Q.push(he)}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),oe=Q?Q.value||Q.default:null;return oe?oe.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 oe=o.dK(B,Q[T]);if(oe.result!=="success")return void $v(this,oe.value);const he=oe.value.expression,we=o.m(T,K.scope),Me=K.options.get(we);if(!Me)return;let Re;const{minValue:Ze,maxValue:Xe,stepValue:dt,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:he,default:Re,minValue:Ze,maxValue:Xe,stepValue:dt,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 oe=o.m(Q,T.scope),he=T.options.get(oe),we=he?he.value||he.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 oe=o.dK(T[B].default,T[B]);if(oe.result==="success"&&(K=oe.value.expression),k&&k[B]!==void 0){const Xe=o.dK(k[B],T[B]);Xe.result==="success"&&(Q=Xe.value.expression)}const{minValue:he,maxValue:we,stepValue:Me,type:Re,values:Ze}=T[B];if(K){const Xe=o.m(B,this.scope);this.options.set(Xe,{default:K,value:Q,minValue:he,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($v(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 oe=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.`):oe=Re}this._order.splice(oe,0,K),this._handleLayerOrderChange(),this._layers[K]=Q;const he=this.getOwnLayerSourceCache(Q),we=!!this.directionalLight&&this.directionalLight.shadowsEnabled();he&&Q.canCastShadows()&&we&&(he.castsShadows=!0);const Me=this._changes.getRemovedLayer(Q);if(Me&&Q.source&&he&&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"),he.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 oe=this._order.indexOf(T);if(oe===-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=oe}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 oe in this._layers)if(this._layers[oe].source===T.source&&this._layers[oe].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)&&$v(Q,Fl.call(ws,{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||!$v(Q,Gg.call(ws,{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:Xe,sourceLayer:dt}of Ze)Re.setFeatureState({id:k.id,source:Xe,sourceLayer:dt},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 oe=Q.type;if(oe==="geojson"&&K)return void this.fire(new o.f(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(oe==="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 he=this.getOwnSourceCaches(B);for(const we of he)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:Xe,sourceLayer:dt}of Ze)Re.removeFeatureState({id:k.id,source:Xe,sourceLayer:dt},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,oe=Q==="vector"?k.sourceLayer:void 0;if(Q==="vector"&&!oe)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 he=this.getOwnSourceCaches(B);for(const we of he)we.removeFeatureState(oe,k.id,T)}getFeatureState(k){if(this._checkLoaded(),"target"in k){let Q;if("featuresetId"in k.target){const{featuresetId:oe,importId:he}=k.target,we=this.getFragmentStyle(he),Me=we.getFeaturesetLayers(oe);for(const{source:Re,sourceLayer:Ze}of Me){const Xe=we.getFeatureState({id:k.id,source:Re,sourceLayer:Ze});if(Xe&&!Q)Q=Xe;else if(!o.O(Q,Xe))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 oe=this._resolveLayerFragment(k.target.layerId);Q=oe==null?void 0:oe.fragment.getFeatureState({id:k.id,source:oe.layer.source,sourceLayer:oe.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:oe,sourceLayer:he}of Q)K.removeFeatureState({source:oe,sourceLayer:he})}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=he=>this._mergedLayers[he].is3D(!!this.terrain),B=this.order,K={},Q=[];for(let he=B.length-1;he>=0;he--){const we=B[he];if(T(we)){K[we]=he;for(const Me of k){const Re=Me[we];if(Re)for(const Ze of Re)Q.push(Ze)}}}Q.sort((he,we)=>we.intersectionZ-he.intersectionZ);const oe=[];for(let he=B.length-1;he>=0;he--){const we=B[he];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(og.has(Re.type))return;const Ze=this.getOwnLayerSourceCache(Re),Xe=Q[Ze.id]=Q[Ze.id]||{sourceCache:Ze,layers:{},has3DLayers:!1};Re.is3D(!!this.terrain)&&(Xe.has3DLayers=!0),Xe.layers[Re.fqid]=Xe.layers[Re.fqid]||{styleLayer:Re,targets:[]},Xe.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.`))),[];oe(Ze)}}else for(const Re in this._layers)oe(this._layers[Re]);const he=this._queryRenderedFeatures(k,Q,B),we=this._flattenAndSortRenderedFeatures(he),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",oe=[];if(T&&T.target)oe.push({...T,targetId:Q,filter:K});else{const Re=this.getFeaturesetDescriptors();for(const Ze of Re)oe.push({targetId:Q,filter:K,target:Ze});for(const{style:Ze}of this.fragments){const Xe=Ze.getFeaturesetDescriptors();for(const dt of Xe)oe.push({targetId:Q,filter:K,target:dt})}}const he=this.queryRenderedTargets(k,oe,B),we=[],Me=new Set;for(const Re of he)for(const Ze of Re.variants[Q])Yd(Ze,Re,Me)||we.push(new o.dP(Re,Ze));return we}queryRenderedTargets(k,T,B){const K={},Q=(he,we,Me,Re)=>{const Ze=K[we.id]=K[we.id]||{sourceCache:we,layers:{},has3DLayers:!1};if(Ze.layers[he.fqid]=Ze.layers[he.fqid]||{styleLayer:he,targets:[]},he.is3D(!!this.terrain)&&(Ze.has3DLayers=!0),!Re)return Me.uniqueFeatureID=!1,void Ze.layers[he.fqid].targets.push(Me);Ze.layers[he.fqid].targets.push({...Me,namespace:Re.namespace,properties:Re.properties,uniqueFeatureID:Re.uniqueFeatureID})};for(const he of T)if("featuresetId"in he.target){const{featuresetId:we,importId:Me}=he.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 Xe of Ze){const dt=Re.getOwnLayer(Xe.layerId);dt&&!og.has(dt.type)&&Q(dt,Re.getOwnLayerSourceCache(dt),he,Xe)}}else if("layerId"in he.target){const{layerId:we}=he.target,Me=this.getLayer(we);if(!Me||og.has(Me.type))continue;Q(Me,this.getLayerSourceCache(Me),he)}const oe=this._queryRenderedFeatures(k,K,B);return this._flattenAndSortRenderedFeatures(oe)}_queryRenderedFeatures(k,T,B){const K=[],Q=!!this.map._showQueryGeometry,oe=yr.createFromScreenPoints(k,B);for(const he in T){const we=ag(oe,T[he],this._availableImages,B,Q,this.getActualScope());Object.keys(we).length&&K.push(we)}if(this.placement)for(const he in T){if(T[he].sourceCache._renderSourceType!==o.bS.Symbol)continue;const we=Lh(oe.screenGeometry,T[he],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 oe of Q)K=K.concat(mf(oe,T));return K}getFlatLight(){return this.light.getLight()}setFlatLight(k,T,B={}){this._checkLoaded();const K=this.light.getLight();let Q=!1;for(const he in k)if(!o.O(k[he],K[he])){Q=!0;break}if(!Q)return;const oe=this._getTransitionParameters();this.light.setLight(k,T,B),this.light.updateTransitions(oe)}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 he="terrain-dem-src";this.addSource(he,B.source),B=o.dG(B),B=Object.assign(B,{source:he})}const Q={...B},oe={};if(this.terrain&&K){Q.source=this.terrain.get().source;const he=this.terrain?this.getFragmentStyle(this.terrain.scope):null;he&&(oe.style=he.serialize())}if(this._validate(ao,"terrain",Q,oe))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,oe=Q.get();for(const he of Object.keys(o.s.terrain))!Object.hasOwn(B,he)&&o.s.terrain[he].default&&(B[he]=o.s.terrain[he].default);for(const he in k)if(!o.O(k[he],oe[he])){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 xt(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 Nt(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 Wy(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 oe={...this.serialize()};return $v(this,k.call(ws,{key:T,style:oe,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 oe in this._mergedLayers){const he=this._mergedLayers[oe];he.type==="building"?B.add(he.source):he.type==="raster"&&he.paint&&he.paint.get("raster-elevation-reference")==="ground"&&Q.add(he.source),he.hasElevation()&&!K.has(he.source)&&K.add(he.source)}this.updateFrcCoverageFadeRange();for(const oe in this._mergedSourceCaches){const he=this._mergedSourceCaches[oe],we=K.has(he._source.id);he._isRasterElevatedOverTerrain=Q.has(he._source.id),B.has(he._source.id)&&(he._source.reparseOverscaled=!1),he.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 tx),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(k,T,B,K,Q,oe){this.pauseablePlacement||(this.pauseablePlacement=new tx);let he=!1,we=!1;const Me={},Re={},Ze=oe==="global",Xe=Ze?[]:this._mergedOrder;Ze&&this._driveGlobalPlacement(k,Q);for(const Jt of Xe){const Lt=this._mergedLayers[Jt];if(Lt.type!=="symbol")continue;const ps=o.m(Lt.source,Lt.scope);let Gs=Me[ps];if(!Gs){const sn=this.getLayerSourceCache(Lt);if(!sn)continue;const Bs=sn.getRenderableIds(!0).map(nn=>sn.getTileByID(nn));Re[ps]=Bs.slice(),Gs=Me[ps]=Bs.sort((nn,yn)=>yn.tileID.overscaledZ-nn.tileID.overscaledZ||(nn.tileID.isLessThan(yn.tileID)?-1:1))}const Ls=this.crossTileSymbolIndex.addLayer(Lt,Gs,k.center.lng,k.projection);he=he||Ls}this.crossTileSymbolIndex.pruneUnusedLayers(Xe);const dt=!!(this.placement&&!k.equals(this.placement.transform)),_t=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!Q||this.placement.lastReplacementSourceUpdateTime!==Q.updateTime)),bt=dt||_t||he,Mt=(bt||this.pauseablePlacement.isStale())&&B===0,ss=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.e.now(),k.zoom)&&B!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||Mt||ss)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(k,Xe,T,B,K,this.placement,this.fog&&k.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const Jt=this.map.painter.maxFrontCutoffRawStart;if(Jt>0){const Lt=180*k.pitch/Math.PI;if(Lt>=15){const ps=Math.min(1,Math.max(0,(Lt-15)/5)),Gs=ps*ps*(3-2*ps);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-Gs)+Jt*Gs}}}if(this.pauseablePlacement.isDone()?bt&&B!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(Xe,this._mergedLayers,Me,Re,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.e.now()),we=!0),he&&this.pauseablePlacement.setStale()),we||he){this._buildingIndex.onNewFrame(k.zoom);for(let Jt=0;Jtwe.getTileByID(Ze)),Re=this.isLayerClipped(he);he.placeSymbols(Q,Me,oe,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 oe=B[K],he=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(oe).concat(B.slice(Q)),this.fragments=this.fragments.slice(0,Q).concat(he).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 oe=this.fragments[K];B&&oe.style.stylesheet&&(oe.style.stylesheet.schema=B);const he=oe.style.stylesheet&&oe.style.stylesheet.schema;return oe.config=T,oe.style.updateConfig(T,he),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)),oe=we=>{we&&(we.setDependencies(T.tileID.key,"icons",K),we.setDependencies(T.tileID.key,"patterns",Q))},he=o.m(T.source,T.scope);return oe(this._mergedOtherSourceCaches[he]),oe(this._mergedSymbolSourceCaches[he]),(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,oe)=>{Q?K(Q):B(oe)})})}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,oe)=>{Q?K(Q):B(oe)})})}}dp.registerForPluginStateChange=o.dz;class Uv{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,oe,he,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(` `),Xe=[Me,o.d_];for(const Mt of B.vertexIncludes)Xe.push(o.bb[Mt]);this.forceManualRenderingForInstanceIDShaders=k.forceManualRenderingForInstanceIDShaders&&B.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Xe.push("uniform int u_instanceID;"),Xe.push(B.vertexSource);let dt=Xe.join(` `);this.forceManualRenderingForInstanceIDShaders&&(dt=dt.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,dt),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,oe=k._compileStats;if(oe.totalStallMs+=Q,Q>oe.maxStallMs&&(oe.maxStallMs=Q),Q>1){oe.framesMissed+=Math.floor(60*Q/1e3);const Me=this.fixedDefines.join(",");oe.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 he=this.fixedDefines,we=this.name;(he.includes("TERRAIN")||he.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)),he.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)),he.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)),he.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=o.d$(k)),he.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)),he.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 oe=K[Q];oe&&oe.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,oe,he,we,Me,Re){const Ze=k.options.wireframe;if(Ze.terrain===!1&&Ze.layers2D===!1&&Ze.layers3D===!1)return;const Xe=k.context;if(!(!(!Ze.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Ze.layers2D||k._terrain&&k._terrain.renderingToTexture||!oa.includes(this.name))||!(!Ze.layers3D||!A3.includes(this.name))))return;const dt=Xe.gl,_t=k.wireframeDebugCache.getLinesFromTrianglesBuffer(k.frameCounter,Q,Xe);if(!_t)return;const bt=[...this.fixedDefines,"DEBUG_WIREFRAME"],Mt=k.getOrCreateProgram(this.name,{config:this.configuration,defines:bt});Mt._ensureReady(),Xe.program.set(Mt.program);const ss=(ps,Gs,Ls)=>{if(Gs[ps]&&Ls[ps])for(const sn in Gs[ps])Ls[ps][sn]&&Ls[ps][sn].set(Ls.program,sn,Gs[ps][sn].current)};Me&&Me.setUniforms(Mt.program,Xe,Mt.binderUniforms,he,{zoom:we}),ss("fixedUniforms",this,Mt),ss("terrainUniforms",this,Mt),ss("globeUniforms",this,Mt),ss("fogUniforms",this,Mt),ss("lightsUniforms",this,Mt),ss("shadowUniforms",this,Mt),_t.bind(),Xe.setColorMode(new o.a1([dt.ONE,dt.ONE_MINUS_SRC_ALPHA,dt.ZERO,dt.ONE],o.C.transparent,[!0,!0,!0,!1])),Xe.setDepthMode(new o.Z(T.func===dt.LESS?dt.LEQUAL:T.func,o.Z.ReadOnly,T.range)),Xe.setStencilMode(o._.disabled);const Jt=3*oe.primitiveLength*2,Lt=3*oe.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const ps=Re||1;for(let Gs=0;Gs1?dt.drawElementsInstanced(dt.LINES,Jt,dt.UNSIGNED_SHORT,Lt,Re):dt.drawElements(dt.LINES,Jt,dt.UNSIGNED_SHORT,Lt);Q.bind(),Xe.program.set(this.program),Xe.setDepthMode(T),Xe.setStencilMode(B),Xe.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,oe,he,we,Me,Re,Ze,Xe,dt,_t,bt,Mt){const ss=k.context,Jt=ss.gl;if(this._ensureReady(),this.failedToCreate)return;ss.program.set(this.program),ss.setDepthMode(B),ss.setStencilMode(K),ss.setColorMode(Q),ss.setCullFace(oe);for(const[Bs,nn]of this.fixedUniformsEntries)nn.set(this.program,Bs,he[Bs]);_t&&_t.setUniforms(this.program,ss,this.binderUniforms,Xe,{zoom:dt});const Lt={[Jt.POINTS]:1,[Jt.LINES]:2,[Jt.TRIANGLES]:3,[Jt.LINE_STRIP]:1}[T];this.checkUniforms(we,"RENDER_SHADOWS",this.shadowUniforms);const ps=bt||[],Gs=_t?_t.getPaintVertexBuffers():[],Ls=T===Jt.TRIANGLES&&Re,sn=Mt&&Mt>0?1:void 0;for(const Bs of Ze.get()){const nn=Bs.vaos||(Bs.vaos={});if((nn[we]||(nn[we]=new Uv)).bind(ss,this,Me,Gs,Re,Bs.vertexOffset,ps,sn),this.forceManualRenderingForInstanceIDShaders){const yn=Mt||1;for(let Tn=0;Tn1?Jt.drawElementsInstanced(T,Bs.primitiveLength*Lt,Jt.UNSIGNED_SHORT,Bs.primitiveOffset*Lt*2,Mt):Re?Jt.drawElements(T,Bs.primitiveLength*Lt,Jt.UNSIGNED_SHORT,Bs.primitiveOffset*Lt*2):Jt.drawArrays(T,Bs.vertexOffset,Bs.vertexLength);Ls&&this._drawDebugWireframe(k,B,K,Q,Re,Bs,Xe,dt,_t,Mt)}}}class lg{constructor(k,T,B,K){this.id=lg.uniqueIdxCounter,lg.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=lg.uniqueIdxCounter,lg.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)}}lg.uniqueIdxCounter=0;const qv={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class Bx{constructor(k,T,B,K,Q,oe){this.length=T.length,this.attributes=B,this.itemSize=T.bytesPerElement,this.dynamicDraw=K,this.instanceCount=oe,this.context=k;const he=k.gl;this.buffer=he.createBuffer(),k.bindVertexBuffer.set(this.buffer),he.bufferData(he.ARRAY_BUFFER,T.arrayBuffer,this.dynamicDraw?he.DYNAMIC_DRAW:he.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 oe=K.offset+this.itemSize*(B||0);K.type==="Float32"||K.normalized?k.vertexAttribPointer(Q,K.components,k[qv[K.type]],!!K.normalized,this.itemSize,oe):k.vertexAttribIPointer(Q,K.components,k[qv[K.type]],this.itemSize,oe)}}}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 K2{constructor(k,T,B,K,Q){this.context=k,this.width=T,this.height=B;const oe=this.framebuffer=k.gl.createFramebuffer();K>0&&(this.colorAttachment0=new Pr(k,oe,0)),K>1&&(this.colorAttachment1=new Pr(k,oe,1)),Q&&(this.depthAttachmentType=Q,this.depthAttachment=Q==="renderbuffer"?new Ik(k,oe):new LC(k,oe))}static createWithTexture(k,T,B,K,Q){const oe=k.gl;if(k.activeTexture.set(oe.TEXTURE1),k.viewport.set([0,0,B,K]),T&&T.width===B&&T.height===K)return oe.bindTexture(oe.TEXTURE_2D,T.colorAttachment0.get()),k.bindFramebuffer.set(T.framebuffer),T;T&&T.destroy();const he=k.extRenderToTextureHalfFloat||k.extColorBufferFloat?k.gl.RGBA16F:k.gl.RGBA8,we=new o.T(k,{width:B,height:K,data:null},he);we.bind(oe.LINEAR,oe.CLAMP_TO_EDGE);const Me=k.createFramebuffer(B,K,1,null);if(Me.format=he,Me.colorAttachment0.set(we.texture),Q){const Re=k.createRenderbuffer(oe.DEPTH24_STENCIL8,B,K);k.bindFramebuffer.set(Me.framebuffer),oe.framebufferRenderbuffer(oe.FRAMEBUFFER,oe.DEPTH_STENCIL_ATTACHMENT,oe.RENDERBUFFER,Re),Me._stencilRbo=Re}return Me}createColorAttachment(k,T){T===0?this.colorAttachment0=new Pr(k,this.framebuffer,0):T===1&&(this.colorAttachment1=new Pr(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 _m{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 Yg(this),this.clearDepth=new P1(this),this.clearStencil=new I1(this),this.colorMask=new L1(this),this.depthMask=new Kw(this),this.stencilMask=new Yw(this),this.stencilFunc=new D_(this),this.stencilOp=new Mk(this),this.stencilTest=new Pb(this),this.depthRange=new Ov(this),this.depthTest=new N3(this),this.depthFunc=new U2(this),this.blend=new np(this),this.blendFunc=new Pk(this),this.blendColor=new R1(this),this.blendEquation=new Zg(this),this.cullFace=new rp(this),this.cullFaceSide=new Rx(this),this.frontFace=new $d(this),this.program=new zv(this),this.activeTexture=new PC(this),this.viewport=new UT(this),this.bindFramebuffer=new qT(this),this.bindRenderbuffer=new k3(this),this.bindTexture=new Ib(this),this.bindVertexBuffer=new Ep(this),this.bindElementBuffer=new $0(this),this.bindVertexArrayOES=new IC(this),this.pixelStoreUnpack=new S3(this),this.pixelStoreUnpackPremultiplyAlpha=new Lb(this),this.pixelStoreUnpackFlipY=new ap(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 lg(this,k,T,B)}createVertexBuffer(k,T,B,K,Q){return new Bx(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 K2(this,k,T,B,K)}clear({color:k,depth:T,stencil:B,colorMask:K}){const Q=this.gl;let oe=0;k&&(oe|=Q.COLOR_BUFFER_BIT,this.clearColor.set(k.toNonPremultipliedRenderColor(null)),this.colorMask.set(K||[!0,!0,!0,!0])),T!==void 0&&(oe|=Q.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(T),this.depthMask.set(!0)),B!==void 0&&(oe|=Q.STENCIL_BUFFER_BIT,this.clearStencil.set(B),this.stencilMask.set(255)),Q.clear(oe)}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 E3=o.Y();function HT(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 _9({width:L,height:k,anchor:T,textOffset:B,textScale:K},Q){const{horizontalAlign:oe,verticalAlign:he}=o.du(T),we=-(oe-.5)*L,Me=-(he-.5)*k,Re=o.dv(T,B);return new o.P((we/K+Re[0])*Q,(Me/K+Re[1])*Q)}function w9(L,k,T,B,K,Q,oe,he,we,Me){const Re=L.text.placedSymbolArray,Ze=L.text.dynamicLayoutVertexArray,Xe=L.icon.dynamicLayoutVertexArray,dt={},_t=L.getProjection(),bt=o.e1(oe,_t,K),Mt=K.elevation,ss=_t.upVectorScale(oe.canonical,K.center.lat,K.worldSize).metersToTile;Ze.clear();for(let Jt=0;Jt=0&&(dt[Lt.associatedIconIndex]={x:Gn,y:zn,z:Dn,angle:ka})}else o.e3(Ls,Ze)}if(Me){Xe.clear();const Jt=L.icon.placedSymbolArray;for(let Lt=0;Lt{let vc=[0,0,0];if(Pd){const Kh=L.style.directionalLight,cg=L.style.ambientLight;Kh&&cg&&(vc=o.aG(L.style,Kh,cg))}return vc},Ko=Pd=>{const vc=Math.floor(L.context.maxUniformBlockSize/4),Kh=Math.floor(vc/4);Pd.push(`MAX_UBO_SIZE_VEC4 ${Kh}u`)},so=Pd=>{nn.depthOcclusionForSymbolsAndCircles&&(T.hasOcclusionOpacityProperties||L.terrain)&&(Pd.push("DEPTH_D24"),Pd.push("DEPTH_OCCLUSION"))},_d=Pd=>{T.lut&&!Ls&&(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],sn.gl.RGBA8)),sn.activeTexture.set(sn.gl.TEXTURE0+o.ci.LUT),T.lut.texture&&T.lut.texture.bind(sn.gl.LINEAR,sn.gl.CLAMP_TO_EDGE),Pd.push("APPLY_LUT_ON_GPU"))},Gh=()=>{const Pd=yn&&T.layout.get("symbol-placement")!=="point",vc=[];so(vc),_d(vc);const Kh=Pd||to,cg=Hr.elevationType==="road",H_=L.shadowRenderer,Jy=cg&&Gn&&!!H_&&H_.enabled,nj=Uc(Jy),vu=cg&&Gn&&!L.terrain?pr:kn,id=T.paint.get("icon-image-cross-fade");L.terrainRenderModeElevated()&&Gn&&vc.push("PITCH_WITH_MAP_TERRAIN"),Ha&&(vc.push("PROJECTION_GLOBE_VIEW"),Kh&&vc.push("PROJECTED_POS_ON_VIEWPORT")),id>0&&Hr.hasAnySecondaryIcon&&vc.push("ICON_TRANSITION"),!Hr.icon.zOffsetVertexBuffer||cg&&L.terrain||vc.push("Z_OFFSET"),ss===0&&Jt===0&&Lt===0&&ps===1||vc.push("COLOR_ADJUSTMENT"),Jy&&vc.push("RENDER_SHADOWS","NORMAL_OFFSET"),cg&&Gn&&!L.terrain&&Hr.icon.orientationVertexBuffer&&vc.push("ELEVATED_ROADS"),Ko(vc);const Rc=L.getOrCreateProgram("symbol",{defines:vc}),Yh=Sr.imageAtlasTexture?Sr.imageAtlasTexture.size:[0,0],sx=Hr.iconSizeData,Ku=o.dl(sx,nn.zoom),Li=Gn||!nn.isOrthographic,wm=o.e2(Ya,Sr.tileID.canonical,Gn,yn,nn,Hr.getProjection(),Oi),dg=o.dk(Ya,Sr.tileID.canonical,Gn,yn,nn,Hr.getProjection(),Oi),rj=Hr.icon.uboBinder&&Hr.icon.uboBinder.hasPerFeatureTranslate()?[0,0]:he,aj=L.translatePosMatrix(dg,Sr,rj,Me,!0),Ob=L.translatePosMatrix(Ya,Sr,rj,Me),zb=Kh?E3:wm,Y2=yn&&!Gn&&!Pd;let Bb=si;!qr&&!nn.mercatorFromTransition||yn||(Bb=HT(nn));const yy=Ha?Bb:si,$m=T.getColorAdjustmentMatrix(ss,Jt,Lt,ps),lo=qs(sx.kind,Ku,Y2,Gn,L,Ob,zb,aj,Gs,!1,Hr.sdfIcons,Yh,[0,0],0,Gr,$r,ta,ql,yy,Hr.getProjection(),nj,yu,$m,id,null),up=Sr.imageAtlasTexture?Sr.imageAtlasTexture:null,Um=T.layout.get("icon-size").constantOr(0)!==1||Hr.iconsNeedLinear,bY=Hr.sdfIcons||L.options.rotating||L.options.zooming||Um||Li?Bs.LINEAR:Bs.NEAREST,G_=Hr.sdfIcons&&T.paint.get("icon-halo-width").constantOr(1)!==0,G6=L.terrain&&Gn&&Pd?o.aP(o.Y(),wm):E3;if(Pd&&Hr.icon){const Of=o.c2.getAtTileOffsetFunc(Gr,nn.center.lat,nn.worldSize,Hr.getProjection()),W6=o.dj(Ya,Sr.tileID.canonical,Gn,yn,nn,Hr.getProjection(),Oi),I9=T.layout.get("icon-size-scale-range"),L9=o.b1(L.scaleFactor,I9[0],I9[1]);o.e6(Hr,Ya,L,!1,W6,dg,Gn,bt,Of,Gr,L9)}return{program:Rc,buffers:Hr.icon,uniformValues:lo,atlasTexture:up,atlasTextureIcon:null,atlasInterpolation:bY,atlasInterpolationIcon:null,isSDF:Hr.sdfIcons,hasHalo:G_,depthMode:vu,tile:Sr,renderWithShadows:Jy,labelPlaneMatrixInv:G6}},_h=()=>{const Pd=Tn&&T.layout.get("symbol-placement")!=="point",vc=[],Kh=Pd||ka||to,cg=Hr.elevationType==="road",H_=L.shadowRenderer,Jy=cg&&zn&&!!H_&&H_.enabled,nj=Uc(Jy),vu=cg&&zn&&!L.terrain?pr:kn;L.terrainRenderModeElevated()&&zn&&vc.push("PITCH_WITH_MAP_TERRAIN"),Ha&&(vc.push("PROJECTION_GLOBE_VIEW"),Kh&&vc.push("PROJECTED_POS_ON_VIEWPORT")),!Hr.text.zOffsetVertexBuffer||cg&&L.terrain||vc.push("Z_OFFSET"),Hr.iconsInText&&vc.push("RENDER_TEXT_AND_SYMBOL"),Jy&&vc.push("RENDER_SHADOWS","NORMAL_OFFSET"),cg&&zn&&!L.terrain&&Hr.text.orientationVertexBuffer&&vc.push("ELEVATED_ROADS"),so(vc),Ko(vc);const id=L.getOrCreateProgram("symbol",{defines:vc});let Rc,Yh=[0,0],sx=null;const Ku=Hr.textSizeData;Hr.iconsInText&&(Yh=Sr.imageAtlasTexture?Sr.imageAtlasTexture.size:[0,0],sx=Sr.imageAtlasTexture?Sr.imageAtlasTexture:null,Rc=zn||!nn.isOrthographic||L.options.rotating||L.options.zooming||Ku.kind==="composite"||Ku.kind==="camera"?Bs.LINEAR:Bs.NEAREST);const Li=Sr.glyphAtlasTexture?Sr.glyphAtlasTexture.size:[0,0],wm=T.layout.get("text-size-scale-range"),dg=o.b1(L.scaleFactor,wm[0],wm[1]),rj=o.dl(Ku,nn.zoom,dg),aj=o.e2(Ya,Sr.tileID.canonical,zn,Tn,nn,Hr.getProjection(),Oi),Ob=o.dk(Ya,Sr.tileID.canonical,zn,Tn,nn,Hr.getProjection(),Oi),zb=Hr.text.uboBinder&&Hr.text.uboBinder.hasPerFeatureTranslate()?[0,0]:we,Y2=L.translatePosMatrix(Ob,Sr,zb,Re,!0),Bb=L.translatePosMatrix(Ya,Sr,zb,Re),yy=Kh?E3:aj,$m=Tn&&!zn&&!Pd;let lo=si;!qr&&!nn.mercatorFromTransition||Tn||(lo=HT(nn));const up=qs(Ku.kind,rj,$m,zn,L,Bb,yy,Y2,Gs,!0,!0,Li,Yh,0,Gr,$r,ta,ql,Ha?lo:si,Hr.getProjection(),nj,yu,null,null,dg),Um=Sr.glyphAtlasTexture?Sr.glyphAtlasTexture:null,bY=Bs.LINEAR,G_=T.paint.get("text-halo-width").constantOr(1)!==0,G6=L.terrain&&zn&&Pd?o.aP(o.Y(),aj):E3;if(Pd&&Hr.text){const Of=o.c2.getAtTileOffsetFunc(Gr,nn.center.lat,nn.worldSize,Hr.getProjection()),W6=o.dj(Ya,Sr.tileID.canonical,zn,Tn,nn,Hr.getProjection(),Oi);o.e6(Hr,Ya,L,!0,W6,Ob,zn,Mt,Of,Gr,dg)}return{program:id,buffers:Hr.text,uniformValues:up,atlasTexture:Um,atlasTextureIcon:sx,atlasInterpolation:bY,atlasInterpolationIcon:Rc,isSDF:!0,hasHalo:G_,depthMode:vu,tile:Sr,renderWithShadows:Jy,labelPlaneMatrixInv:G6}},Vl=Hr.icon.segments.get().length,mm=Hr.text.segments.get().length,yc=Vl&&!oe.onlyText?Gh():null,dc=mm&&!oe.onlyIcons?_h():null,Dh=T.paint.get("icon-opacity").constantOr(1),Wh=T.paint.get("text-opacity").constantOr(1);if(Dn&&Hr.canOverlap){Mr=!0;const Pd=Dh&&!oe.onlyText?Hr.icon.segments.get():[],vc=Wh&&!oe.onlyIcons?Hr.text.segments.get():[];for(const Kh of Pd)Jr.push({segments:new o.ad([Kh]),sortKey:Kh.sortKey,state:yc});for(const Kh of vc)Jr.push({segments:new o.ad([Kh]),sortKey:Kh.sortKey,state:dc})}else oe.onlyText||Jr.push({segments:Dh?Hr.icon.segments:new o.ad([]),sortKey:0,state:yc}),oe.onlyIcons||Jr.push({segments:Wh?Hr.text.segments:new o.ad([]),sortKey:0,state:dc})}Mr&&Jr.sort((Gr,Sr)=>Gr.sortKey-Sr.sortKey);for(const Gr of Jr){const Sr=Gr.state;if(Sr)if(L.terrain?L.terrain.setupElevationDraw(Sr.tile,Sr.program,{useDepthForOcclusion:nn.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:Sr.labelPlaneMatrixInv}):L.setupDepthForOcclusion(nn.depthOcclusionForSymbolsAndCircles,Sr.program),sn.activeTexture.set(Bs.TEXTURE0),Sr.atlasTexture&&Sr.atlasTexture.bind(Sr.atlasInterpolation,Bs.CLAMP_TO_EDGE,!0),Sr.atlasTextureIcon&&(sn.activeTexture.set(Bs.TEXTURE1),Sr.atlasTextureIcon&&Sr.atlasTextureIcon.bind(Sr.atlasInterpolationIcon,Bs.CLAMP_TO_EDGE,!0)),Sr.renderWithShadows&&L.shadowRenderer.setupShadows(Sr.tile.tileID.toUnwrapped(),Sr.program,"vector-tile"),L.uploadCommonLightUniforms(L.context,Sr.program),Sr.hasHalo){const Hr=Sr.uniformValues;Hr.u_is_halo=1,FC(Sr.buffers,Gr.segments,T,L,Sr.program,Sr.depthMode,K,Q,Hr,2),Hr.u_is_halo=0}else{if(Sr.isSDF){const Hr=Sr.uniformValues;Sr.hasHalo&&(Hr.u_is_halo=1,FC(Sr.buffers,Gr.segments,T,L,Sr.program,Sr.depthMode,K,Q,Hr,1)),Hr.u_is_halo=0}FC(Sr.buffers,Gr.segments,T,L,Sr.program,Sr.depthMode,K,Q,Sr.uniformValues,1)}}}function FC(L,k,T,B,K,Q,oe,he,we,Me){const Re=B.context,Ze=Re.gl,Xe=[L.dynamicLayoutVertexBuffer,L.opacityVertexBuffer,L.iconTransitioningVertexBuffer,L.globeExtVertexBuffer,L.zOffsetVertexBuffer,L.orientationVertexBuffer];L.featureIdBuffer&&Xe.push(L.featureIdBuffer);const dt=L.uboBinder?null:L.programConfigurations.get(T.id);if(L.uboBinder){L.uboBinder.layer=T;const Mt=B.transform.zoom,ss=B.style.getBrightness?B.style.getBrightness():null,Jt=L.uboBinder.getConstantUniformValues(Mt,ss);we.u_spp_fill_np_color=Jt.fill_np_color,we.u_spp_halo_np_color=Jt.halo_np_color,we.u_spp_opacity=Jt.opacity,we.u_spp_halo_width=Jt.halo_width,we.u_spp_halo_blur=Jt.halo_blur,we.u_spp_emissive_strength=Jt.emissive_strength,we.u_spp_occlusion_opacity=Jt.occlusion_opacity,we.u_spp_z_offset=Jt.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 ss=bt.get(Mt);L.uboBinder&&L.uboBinder.bind(Re,K.program,Mt),K.draw(B,Ze.TRIANGLES,Q,oe,he,o.$.disabled,we,T.id,L.layoutVertexBuffer,L.indexBuffer,ss,T.paint,B.transform.zoom,dt,Xe,Me)}}function OC(L,k,T,B,K,Q){const oe=T.paint.get("line-width"),he=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",Xe=Re==="sea",dt=!(!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"),ss=Mt!==void 0,Jt=Mt<1,Lt=K||L.colorModeForDrapableLayerRenderPass(he?we:null),ps=L.terrain&&L.terrain.renderingToTexture||Q,Gs=ps?1:o.e.devicePixelRatio,Ls=T.paint.get("line-dasharray"),sn=Ls.constantOr(1),Bs=T.layout.get("line-cap"),nn=Ls.constantOr(null),yn=Bs.constantOr(null),Tn=T.paint.get("line-pattern"),Gn=Tn.constantOr(1),zn=T.paint.get("line-pattern-cross-fade"),Dn=Tn.constantOr(null),Mr=T.paint.get("line-opacity").constantOr(1);let kn=!Gn&&Mr!==1||L.depthOcclusion&&Me>0&&Me<1;const pr=T.paint.get("line-gradient"),ta=T.paint.get("line-border-width").constantOr(1)!==0?T.paint.get("line-border-gradient"):null,ka=Gn?"linePattern":"line",qr=o.ea(T);let Jr;if(ps&&L.terrain&&L.terrain.clipOrMaskOverlapStencilType()&&(kn=!1),Me!==0&&L.depthOcclusion){const Ya=T.paint._values["line-opacity"];Ya&&Ya.value&&Ya.value.kind==="constant"?Jr=Ya.value:o.w(`Occlusion opacity for layer ${T.id} is supported only when line-opacity isn't data-driven.`)}oe.value.kind!=="constant"&&oe.value.isLineProgressConstant===!1&&qr.push("VARIABLE_LINE_WIDTH");const si=T.paint.get("line-emissive-strength");Gn||si.value.kind==="constant"||si.value.isLineProgressConstant!==!1||qr.push("VARIABLE_LINE_EMISSIVE_STRENGTH"),L._debugParams.showElevationIdDebug&&qr.push("DEBUG_ELEVATION_ID"),ps&&(L.emissiveMode!=="dual-source-blending"||he?L.isEmissiveMrtActive()&&(qr.push("USE_MRT1"),L.emissiveMode==="mrt-full-rgba"&&qr.push("USE_MRT1_RGBA")):qr.push("DUAL_SOURCE_BLENDING"));const Gr={},Sr=[],Hr=(Ya,Oi,Do,to,ql,yu)=>{for(const Uc of Ya){const Ko=k.getTile(Uc);if(Gn&&!Ko.patternsLoaded())continue;const so=Ko.getBucket(T);if(!so||so.elevationType!=="none"&&!ql||so.elevationType==="none"&&ql)continue;L.prepareDrawTile();const _d=[...Oi],Gh=so.elevationType==="road",_h=L.shadowRenderer,Vl=Gh&&!!_h&&_h.enabled;let mm=[0,0,0];if(Vl){const Li=L.style.directionalLight,wm=L.style.ambientLight;Li&&wm&&(mm=o.aG(L.style,Li,wm)),_d.push("RENDER_SHADOWS","NORMAL_OFFSET")}const yc=so.programConfigurations.get(T.id);let dc=!1;if(Dn&&Ko.imageAtlas){const Li=o.aH.from(Dn),wm=Li.getPrimary().scaleSelf(Gs).toString(),dg=Ko.imageAtlas.patternPositions.get(wm),rj=Li.getSecondary(),aj=rj?Ko.imageAtlas.patternPositions.get(rj.scaleSelf(Gs).toString()):null;dc=!!dg&&!!aj,dg&&yc.setConstantPatternPositions(dg,aj)}zn>0&&(dc||yc.getPatternTransitionVertexBuffer("line-pattern"))&&_d.push("LINE_PATTERN_TRANSITION"),so.elevationGroundScaleVertexBuffer&&_d.push("ELEVATION_GROUND_SCALE");const Dh=L.isTileAffectedByFog(Uc),Wh=L.getOrCreateProgram(ka,{config:yc,defines:_d,overrideFog:Dh});if(!Gn&&nn&&yn&&Ko.lineAtlas){const Li=Ko.lineAtlas.getDash(nn,yn);Li&&yc.setConstantPatternPositions(Li)}Vl&&_h.setupShadows(Ko.tileID.toUnwrapped(),Wh,"vector-tile");let[Pd,vc]=T.paint.get("line-trim-offset");(yn==="round"||yn==="square")&&Pd!==vc&&(Pd===0&&(Pd-=1),vc===1&&(vc+=1));const Kh=ps?Uc.projMatrix:null,cg=Ze?1/so.tileToMeter/o.cd(Ko,1,L.transform.zoom):1,H_=Ze?1/so.tileToMeter/o.cd(Ko,1,Math.floor(L.transform.zoom)):1,Jy=sn?T.paint._values["line-floorwidth"]:null;let nj;const vu=Ko.dashIdealZ;if(Jy&&Jy.value.kind==="constant"&&vu!==Ko.tileID.overscaledZ){const Li=so.zoom;Li in Gr||(Gr[Li]=Math.max(.01,T.widthExpression().evaluate({zoom:Li}))),nj=Jy.value.value,Jy.value.value=Gr[Li]*Math.pow(2,vu-Li)}const id=Gn?o.eb(L,Ko,T,Kh,Gs,cg,H_,[Pd,vc],mm,zn):o.ec(L,Ko,T,Kh,so.lineClipsArray.length,Gs,cg,H_,[Pd,vc],mm),Rc=(Li,wm,dg,rj,aj,Ob)=>{let zb=Li.texture;if(wm!==Li.version){let Y2=256;if(dg){const Bb=k.getSource().maxzoom,yy=Uc.canonical.z===Bb?Math.ceil(1<{wm&&wm.get().length!==0&&(Jr!=null&&(Jr.value=Mr*Me),dg!==void 0&&(id.u_opacity_multiplier=dg),Wh.draw(L,bt.TRIANGLES,Do,Li,Lt,o.$.disabled,id,T.id,so.layoutVertexBuffer,so.indexBuffer,wm,T.paint,L.transform.zoom,yc,[so.layoutVertexBuffer2,so.patternVertexBuffer,so.zOffsetVertexBuffer,so.elevationIdColVertexBuffer,so.elevationGroundScaleVertexBuffer]),dg!==void 0&&(id.u_opacity_multiplier=1),Jr!=null&&(Jr.value=Mr))},Ku=Li=>{Yh&&Yh.active&&Ui.drawLineFrcRenderLine?Ui.drawLineFrcRenderLine(so,Yh,Li,sx):sx(Li,so.segments)};if(kn&&!ql){const Li=L.stencilModeForClipping(Uc).ref;Li===0&&ps&&_t.clear({stencil:0});const wm={func:bt.EQUAL,mask:255};id.u_alpha_discard_threshold=.8,Ku(new o._(wm,Li,255,bt.KEEP,bt.KEEP,bt.INVERT)),id.u_alpha_discard_threshold=0,Ku(new o._(wm,Li,255,bt.KEEP,bt.KEEP,bt.KEEP))}else id.u_alpha_discard_threshold=kn&&ql&&yu?.8:0,Ku(ql?to:L.stencilModeForClipping(Uc));Yh&&Ui.drawLineFrcFadePass&&Ui.drawLineFrcFadePass(L,so,Uc,Yh,ql,to,sx),nj!==void 0&&(Jy.value.value=nj)}};let Ha=L.depthModeForSublayer(0,o.Z.ReadOnly);const $r=new o.Z(L.depthOcclusion?bt.GREATER:bt.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D);if(T.hasNonElevatedBuckets){const Ya=!ps&&L.terrain;Me!==0&&Ya?o.w(`Occlusion opacity for layer ${T.id} is supported on terrain only if the layer has line-z-offset enabled.`):Ya?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${T.id}.`):Hr(B,qr,Ha,o._.disabled,!1,!0)}if(T.hasElevatedBuckets){Re==="hd-road-markup"?dt||(Ha=$r,qr.push("ELEVATED_ROADS")):(qr.push("ELEVATED"),Ha=$r,ss&&qr.push(Jt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),Xe&&qr.push("ELEVATION_REFERENCE_SEA"));const Ya=kn?L.stencilModeFor3D():o._.disabled;Re!=="hd-road-markup"&&(L.forceTerrainMode=!0),Hr(B,qr,Ha,Ya,!0,!0),kn&&Hr(B,qr,Ha,Ya,!0,!1),Re!=="hd-road-markup"&&(L.forceTerrainMode=!1)}Ui.drawLineFrcCoverageSecondPass&&Ui.drawLineFrcCoverageSecondPass(L,T,Sr),kn&&(L.resetStencilClippingMasks(),ps&&_t.clear({stencil:0})),Me===0||L.depthOcclusion||ps||L.layersWithOcclusionOpacity.push(L.currentLayer)}class G0{destroy(){this.fbo&&(this.fbo.destroy(),this.fbo=null),this.drapeFbo&&(this.drapeFbo.destroy(),this.drapeFbo=null)}}class GT{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 T3={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 Fb(L){return!(!L.extRenderToTextureHalfFloat&&!L.extColorBufferFloat)}function Uk(L,k){return L==="additive"&&Fb(k)?o.a1.additiveAlphaWeightedUnboundedAlpha:T3[L].colorMode}function tj(L,k,T){const B=L.context,K=B.gl;let Q=T.width,oe=T.height,he=T.colorAttachment0.get();k.lineBlendDensityReadback||(k.lineBlendDensityReadback=new GT(K));const we=k.lineBlendDensityReadback;let Me=0,Re=!0;for(;Q>1||oe>1;){const dt=Math.max(1,Math.floor(Q/2)),_t=Math.max(1,Math.floor(oe/2)),bt=Me===0?"fboA":"fboB";we[bt]=K2.createWithTexture(B,we[bt],dt,_t,!1);const Mt=we[bt];B.bindFramebuffer.set(Mt.framebuffer),B.viewport.set([0,0,dt,_t]),B.activeTexture.set(K.TEXTURE0),K.bindTexture(K.TEXTURE_2D,he),L.getOrCreateProgram("lineBlendReduce").draw(L,K.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.unblended,o.$.disabled,He(0,[1/Q,1/oe],Re),k.id,L.viewportBuffer,L.quadTriangleIndexBuffer,L.viewportSegments,k.paint,L.transform.zoom),Q=dt,oe=_t,he=Mt.colorAttachment0.get(),Me=1-Me,Re=!1}const Ze=Fb(B),Xe=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,Xe,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 qk(L,k,T){if(!Fb(L.context))return;const B=k.lineBlendDensityReadback;B&&B.sync?(function(K,Q,oe){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),Fb(oe)){const he=new Float32Array(4);Q.getBufferSubData(Q.PIXEL_PACK_BUFFER,0,he);const we=he[1];K.maxDensity=Math.max(2*(we>0?he[0]/we:0),1)}else K.maxDensity=1;Q.bindBuffer(Q.PIXEL_PACK_BUFFER,null)}}(B,L.context.gl,L.context),B.sync||(tj(L,k,T),L.style.map.triggerRepaint())):(tj(L,k,T),L.style.map.triggerRepaint())}function zC(L,k,T,B,K,Q){const oe=L.context,he=oe.gl,we=T==="additive"?1:k.paint.get("line-opacity").constantOr(1),Me=T==="additive"?function(Ze,Xe){const dt=Xe.paint.get("line-blend-additive-clamp");if(dt>0)return dt;const _t=Xe.lineBlendDensityReadback;return _t&&_t.maxDensity!==0?_t.maxDensity:null}(0,k):1;if(Me===null)return;oe.bindFramebuffer.set(K),Q&&oe.viewport.set([0,0,Q[0],Q[1]]),oe.activeTexture.set(he.TEXTURE0),he.bindTexture(he.TEXTURE_2D,B.colorAttachment0.get());const Re=Uk(T,L.context);L.getOrCreateProgram("lineBlendComposite").draw(L,he.TRIANGLES,o.Z.disabled,o._.disabled,Re,o.$.disabled,((Ze,Xe,dt,_t)=>({u_image:0,u_opacity:Xe,u_blend_mode:dt,u_max_density:_t}))(0,we,T3[T].compositeUniformValue,Me),k.id,L.viewportBuffer,L.quadTriangleIndexBuffer,L.viewportSegments,k.paint,L.transform.zoom)}function BC(L,k,T,B){const{painter:K,sourceCache:Q,layer:oe,coords:he,colorMode:we,elevationType:Me,terrainEnabled:Re,pass:Ze}=L,Xe=K.context.gl,dt=oe.paint.get("fill-pattern"),_t=oe.paint.get("fill-pattern-cross-fade"),bt=dt.constantOr(null);let Mt=Me;Me!=="road"||k&&!Re||(Mt="none");const ss=Mt==="road",Jt=L.painter.shadowRenderer,Lt=ss&&!!Jt&&Jt.enabled,ps=new o.Z(K.context.gl.LEQUAL,o.Z.ReadOnly,K.depthRangeFor3D);let Gs=[0,0,0];if(Lt){const nn=K.style.directionalLight,yn=K.style.ambientLight;nn&&yn&&(Gs=o.aG(K.style,nn,yn))}const Ls=dt&&dt.constantOr(1),sn=K.terrain&&K.terrain.renderingToTexture,Bs=(nn,yn)=>{let Tn,Gn,zn,Dn,Mr;yn?(Tn=Ls&&!oe.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",zn=Xe.LINES):(Tn=Ls?"fillPattern":"fill",zn=Xe.TRIANGLES);const kn=[];for(const pr of he){const ta=Q.getTile(pr);if(Ls&&!ta.patternsLoaded())continue;const ka=ta.getBucket(oe);if(!ka)continue;const qr=k?ka.hdExt&&ka.hdExt.elevationBufferData:ka.bufferData;if(!qr||qr.isEmpty())continue;K.prepareDrawTile();const Jr=qr.programConfigurations.get(oe.id),si=K.isTileAffectedByFog(pr),Gr=[],Sr=[];ss&&(Gr.push("ELEVATED_ROADS"),Sr.push(qr.elevatedLayoutVertexBuffer)),Lt&&Gr.push("RENDER_SHADOWS","NORMAL_OFFSET"),sn&&T&&(Gr.push("USE_MRT1"),K.emissiveMode==="mrt-full-rgba"&&Gr.push("USE_MRT1_RGBA")),Ls&&(K.context.activeTexture.set(Xe.TEXTURE0),ta.imageAtlasTexture&&ta.imageAtlasTexture.bind(Xe.LINEAR,Xe.CLAMP_TO_EDGE),Jr.updatePaintBuffers());let Hr=!1;if(bt&&ta.imageAtlas){const ql=ta.imageAtlas,yu=o.aH.from(bt),Uc=yu.getPrimary().scaleSelf(o.e.devicePixelRatio).toString(),Ko=yu.getSecondary(),so=ql.patternPositions.get(Uc),_d=Ko?ql.patternPositions.get(Ko.scaleSelf(o.e.devicePixelRatio).toString()):null;Hr=!!so&&!!_d,so&&Jr.setConstantPatternPositions(so,_d)}_t>0&&(Hr||Jr.getPatternTransitionVertexBuffer("fill-pattern"))&&Gr.push("FILL_PATTERN_TRANSITION");const Ha=K.getOrCreateProgram(Tn,{config:Jr,overrideFog:si,defines:Gr}),$r=K.translatePosMatrix(pr.projMatrix,ta,oe.paint.get("fill-translate"),oe.paint.get("fill-translate-anchor"));Lt&&Jt.setupShadows(ta.tileID.toUnwrapped(),Ha,"vector-tile");const Ya=oe.paint.get("fill-emissive-strength");if(yn){Dn=qr.lineIndexBuffer,Mr=qr.lineSegments;const ql=K.terrain&&K.terrain.renderingToTexture?K.terrain.drapeBufferSize:[Xe.drawingBufferWidth,Xe.drawingBufferHeight];Gn=Tn==="fillOutlinePattern"&&Ls?Pe($r,Ya,K,ta,ql,Gs,_t):Qw($r,Ya,ql,Gs)}else Dn=qr.indexBuffer,Mr=qr.triangleSegments,Gn=Ls?F1($r,Ya,K,ta,Gs,_t):DC($r,Ya,Gs);K.uploadCommonUniforms(K.context,Ha,pr.toUnwrapped());let Oi=nn;if((Me==="road"&&!Re||Me==="offset")&&(Oi=ps),!Mr||Mr.get&&Mr.get().length===0)continue;const Do=B||K.stencilModeForClipping(pr);let to="fallthrough";!yn&&Ui.drawFillFrcCoverageFirstPass&&(to=Ui.drawFillFrcCoverageFirstPass({painter:K,layer:oe,bucket:ka,coord:pr,elevatedGeometry:k,program:Ha,programConfiguration:Jr,uniformValues:Gn,drawMode:zn,depthMode:Oi,stencilMode:Do,colorMode:we,bufferData:qr,indexBuffer:Dn,segments:Mr,dynamicBuffers:Sr,polygonCoverageTiles:kn})),to==="fallthrough"&&Ha.draw(K,zn,Oi,Do,we,o.$.disabled,Gn,oe.id,qr.layoutVertexBuffer,Dn,Mr,oe.paint,K.transform.zoom,Jr,Sr)}!yn&&Ui.drawFillFrcCoverageSecondPass&&Ui.drawFillFrcCoverageSecondPass(K,oe,kn,zn,we)};K.renderPass===Ze&&Bs(K.depthModeForSublayer(1,K.renderPass==="opaque"?o.Z.ReadWrite:o.Z.ReadOnly),!1),Mt==="none"&&K.renderPass==="translucent"&&oe.paint.get("fill-antialias")&&Bs(K.depthModeForSublayer(oe.getPaintProperty("fill-outline-color")?2:0,o.Z.ReadOnly),!0)}function I6(L){return[L[0]*o.eg,L[1]*o.eg,L[2]*o.eg,0]}function M3(L,k,T,B,K,Q,oe,he,we,Me){const Re=K.getSource(),Ze=B.globeSharedBuffers;if(!Ze)return;let Xe,dt,_t;if(T&&(Xe=K.getTile(T)),Re instanceof Fi?(dt=Re.texture,_t=o.c1(0,0,B.transform)):Xe&&T&&(dt=Xe.texture,_t=o.c1(T.canonical.z,T.canonical.x,B.transform)),!dt||!_t)return;k||(_t=o.aO(o.Y(),_t,[1,-1,1]));const bt=B.context,Mt=bt.gl,ss=Q.paint.get("raster-resampling")==="nearest"?Mt.NEAREST:Mt.LINEAR,Jt=B.colorModeForDrapableLayerRenderPass(oe),Lt=he.defines;Lt.push("GLOBE_POLES");const ps=new o.Z(Mt.LEQUAL,o.Z.ReadWrite,B.depthRangeFor3D),Gs=B.transform.expandedFarZProjMatrix,Ls=Float32Array.from(o.b5(o.b6(new o.bW(0,0,0))));B.terrain&&B.terrain.prepareDrawTile(),bt.activeTexture.set(Mt.TEXTURE0),dt.bind(ss,Mt.CLAMP_TO_EDGE),bt.activeTexture.set(Mt.TEXTURE1),dt.bind(ss,Mt.CLAMP_TO_EDGE),"useMipmap"in dt&&bt.extTextureFilterAnisotropic&&B.transform.pitch>20&&Mt.texParameterf(Mt.TEXTURE_2D,bt.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,bt.extTextureFilterAnisotropicMax);const[sn,Bs,nn,yn]=T?Ze.getPoleBuffers(T.canonical.z,!1):Ze.getPoleBuffers(0,!0),Tn=L;let Gn;k?(Gn=sn,B.renderDefaultNorthPole=Tn!==0):(Gn=Bs,B.renderDefaultSouthPole=Tn!==0);const zn=I6(he.mix),Dn=((kn,pr,ta,ka,qr,Jr,si,Gr,Sr,Hr,Ha,$r,Ya,Oi)=>ks(kn,pr,ta,ka,new Float32Array(16),new Float32Array(9),[0,0],qr,[0,0],[0,0,0,0],1,{opacity:1,mix:0},si,[0,0],Sr,2,Ha,$r,Ya,1,0,Oi))(B,Gs,Ls,_t,o.S(B.transform.zoom),0,Q,0,Tn,0,zn,he.offset,he.range,oe),Mr=B.getOrCreateProgram("raster",{defines:Lt});B.uploadCommonUniforms(bt,Mr,null),Mr.draw(B,Mt.TRIANGLES,ps,Me,Jt,we,Dn,Q.id,Gn,nn,yn)}function L6(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 WT(L,k,T,B){if(L)return k.type==="raster-array"?k.getTextureDescriptor(L,T,!0):{texture:L.texture,mix:I6(B.mix),offset:B.offset,buffer:0,tileSize:1}}const R6=o.df(new Float32Array(16)),$C={"dual-source-blending":"dual-source-blending","mrt-fallback":"mrt","mrt-full-rgba":"mrt-rgba"},j9=o.a$([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:D6}=j9;function ie(L,k,T,B){L.emplaceBack(k,T,B)}class de{constructor(k){this.vertexArray=new o.eh,this.indices=new o.ae,ie(this.vertexArray,-1,-1,1),ie(this.vertexArray,1,-1,1),ie(this.vertexArray,-1,1,1),ie(this.vertexArray,1,1,1),ie(this.vertexArray,-1,-1,-1),ie(this.vertexArray,1,-1,-1),ie(this.vertexArray,-1,1,-1),ie(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,D6),this.indexBuffer=k.createIndexBuffer(this.indices),this.segment=o.ad.simpleSegment(0,0,36,12)}}function Oe(L,k,T,B,K,Q){const oe=L.context.gl,he=k.paint.get("sky-atmosphere-color"),we=k.paint.get("sky-atmosphere-halo-color"),Me=k.paint.get("sky-atmosphere-sun-intensity"),Re=((Ze,Xe,dt,_t,bt)=>({u_matrix_3f:Ze,u_sun_direction:Xe,u_sun_intensity:dt,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,he.toPremultipliedRenderColor(null),we.toPremultipliedRenderColor(null));oe.framebufferTexture2D(oe.FRAMEBUFFER,oe.COLOR_ATTACHMENT0,oe.TEXTURE_CUBE_MAP_POSITIVE_X+Q,k.skyboxTexture,0),T.draw(L,oe.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.unblended,o.$.frontCW,Re,"skyboxCapture",k.skyboxGeometry.vertexBuffer,k.skyboxGeometry.indexBuffer,k.skyboxGeometry.segment)}const tt=o.a$([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class lt{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,tt.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 Ys{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 lt(T);let B=this.params;const K=B.sizeRange,Q=B.intensityRange,oe=function(Ze){const Xe=o.bj(30),dt=[];for(let _t=0;_t{const Bs=Q.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];sn&&Bs.push("ALPHA_PASS");const nn=k.getOrCreateProgram("globeAtmosphere",{defines:Bs}),yn=((Gn,zn,Dn,Mr,kn,pr,ta,ka,qr,Jr,si,Gr)=>({u_frustum_tl:Gn,u_frustum_tr:zn,u_frustum_br:Dn,u_frustum_bl:Mr,u_horizon:kn,u_transition:pr,u_fadeout_range:ta,u_atmosphere_fog_color:ka.toArray01(),u_high_color:qr.toArray01(),u_space_color:Jr.toArray01(),u_temporal_offset:si,u_horizon_angle:Gr}))(Q.frustumCorners.TL,Q.frustumCorners.TR,Q.frustumCorners.BR,Q.frustumCorners.BL,Q.frustumCorners.horizon,he,Mt,Re,Xe,_t,Jt,Gs);k.uploadCommonUniforms(B,nn);const Tn=this.atmosphereBuffer;Tn&&nn.draw(k,K.TRIANGLES,oe,o._.disabled,sn?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,o.$.backCW,yn,sn?"atmosphere_glow_alpha":"atmosphere_glow",Tn.vertexBuffer,Tn.indexBuffer,Tn.segments)};Ls(!1),Ls(!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,oe=k.transform,he=k.getOrCreateProgram("stars"),we=o.be([]);o.bf(we,we,-oe._pitch),o.bg(we,we,-oe.angle),o.bf(we,we,o.av(oe._center.lat)),o.et(we,we,-o.av(oe._center.lng));const Me=o.bh(new Float32Array(16),we),Re=o.X([],oe.starsProjMatrix,Me),Ze=o.ek([],Me),Xe=o.eu([],Ze);let dt=this.params.sizeMultiplier;const _t=[0,1,0];o.cT(_t,_t,Xe),o.dV(_t,_t,dt);const bt=[1,0,0];o.cT(bt,bt,Xe),o.dV(bt,bt,dt);const Mt=(ss=_t,Jt=bt,Lt=B,{u_matrix:Float32Array.from(Re),u_up:ss,u_right:Jt,u_intensity_multiplier:Lt});var ss,Jt,Lt;k.uploadCommonUniforms(K,he),this.starsVx&&this.starsIdx&&he.draw(k,Q.TRIANGLES,o.Z.disabled,o._.disabled,this.colorModeAlphaBlendedWriteRGB,o.$.disabled,Mt,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class ur{}class Or{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),oe=new ArrayBuffer(Q),he=new Int16Array(oe);K.getBufferSubData(K.ELEMENT_ARRAY_BUFFER,0,new Int16Array(oe));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 ci{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const Mi={symbol:function(L,k,T,B,K){if(L.renderPass!=="translucent")return;const Q=o._.disabled,oe=L.colorModeForRenderPass(),he=T.layout.get("text-variable-anchor"),we=T.layout.get("text-size-scale-range"),Me=o.b1(L.scaleFactor,we[0],we[1]);he&&function(Xe,dt,_t,bt,Mt,ss,Jt,Lt){const ps=dt.transform,Gs=Mt==="map",Ls=ss==="map";for(const sn of Xe){const Bs=bt.getTile(sn),nn=Bs.getBucket(_t);if(!nn||!nn.text||!nn.text.segments.get().length)continue;const yn=o.dl(nn.textSizeData,ps.zoom,Lt),Tn=o.e1(sn,nn.getProjection(),ps),Gn=ps.calculatePixelsToTileUnitsMatrix(Bs),zn=o.e2(Tn,Bs.tileID.canonical,Ls,Gs,ps,nn.getProjection(),Gn),Dn=nn.hasIconTextFit()&&nn.hasIconData();yn&&w9(nn,Gs,Ls,Jt,ps,zn,sn,Math.pow(2,ps.zoom-Bs.tileID.overscaledZ),yn,Dn)}}(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)?$k(L,k,T,B,Q,oe):(Re&&$k(L,k,T,B,Q,oe,{onlyIcons:!0}),Ze&&$k(L,k,T,B,Q,oe,{onlyText:!0})),k.map.showCollisionBoxes&&Mc.drawCollisionDebug&&(Mc.drawCollisionDebug(L,k,T,B,T.paint.get("text-translate"),T.paint.get("text-translate-anchor"),!0),Mc.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"),oe=T.paint.get("circle-stroke-opacity"),he=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||oe.constantOr(1)===0))return;const Me=L.context,Re=Me.gl,Ze=L.transform,Xe=!(!L.terrain||!L.terrain.enabled),dt=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=dt==="none"||Xe?_t:bt,ss=o._.disabled,Jt=L.colorModeForDrapableLayerRenderPass(we),Lt=Ze.projection.name==="globe",ps=[o.a7(Ze.center.lng),o.a8(Ze.center.lat)],Gs=[];for(let sn=0;snsn.sortKey-Bs.sortKey);const Ls={useDepthForOcclusion:Ze.depthOcclusionForSymbolsAndCircles};for(const sn of Gs){const{programConfiguration:Bs,program:nn,layoutVertexBuffer:yn,dynamicBuffers:Tn,indexBuffer:Gn,uniformValues:zn,tile:Dn}=sn.state,Mr=sn.segments;L.terrain&&L.terrain.setupElevationDraw(Dn,nn,Ls),L.uploadCommonUniforms(Me,nn,Dn.tileID.toUnwrapped()),nn.draw(L,Re.TRIANGLES,Mt,ss,Jt,o.$.disabled,zn,T.id,yn,Gn,Mr,T.paint,Ze.zoom,Bs,Tn)}},heatmap:function(L,k,T,B){if(T.paint.get("heatmap-opacity")!==0)if(L.renderPass==="offscreen"){const K=L.context,Q=K.gl,oe=o._.disabled,he=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=K2.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"]:[],Xe=Re?o.$.frontCCW:o.$.disabled,dt=[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 oe=T.paint.get("line-blend-mode"),he=L.terrain&&L.terrain.renderingToTexture;if(oe==="default"||L.transform.projection.name==="globe")L.renderPass==="translucent"&&OC(L,k,T,B);else{if(he)return void function(we,Me,Re,Ze,Xe){if(we.renderPass!=="translucent")return;const dt=we.context,_t=dt.gl,bt=we.terrain;if(!bt)return;const Mt=dt.bindFramebuffer.current,ss=we.isEmissiveMrtActive(),Jt=bt.drapeBufferSize[0],Lt=bt.drapeBufferSize[1];Re.lineBlendFbos||(Re.lineBlendFbos=new G0),Re.lineBlendFbos.drapeFbo=K2.createWithTexture(dt,Re.lineBlendFbos.drapeFbo,Jt,Lt,!0),ss&&_t.drawBuffers([_t.COLOR_ATTACHMENT0]),dt.clear({color:T3[Xe].clearColor,depth:1,stencil:0});const ps=we.currentStencilSource,Gs=we._tileClippingMaskIDs,Ls=we.nextStencilID;we.currentStencilSource=void 0,we._tileClippingMaskIDs={},we.nextStencilID=1;const sn=we._terrain;we._terrain=null,we._renderTileClippingMasks(Re,Me,Ze),OC(we,Me,Re,Ze,Uk(Xe,we.context),!0),we._terrain=sn,we.currentStencilSource=ps,we._tileClippingMaskIDs=Gs,we.nextStencilID=Ls,ss&&_t.drawBuffers([_t.COLOR_ATTACHMENT0,_t.COLOR_ATTACHMENT1]);const Bs=bt.drapeBufferSize,nn=Re.lineBlendFbos&&Re.lineBlendFbos.drapeFbo;nn&&(Xe==="additive"&&qk(we,Re,nn),zC(we,Re,Xe,nn,Mt,Bs))}(L,k,T,B,oe);if(L.renderPass==="offscreen")return void function(we,Me,Re,Ze,Xe){const dt=we.context,_t=Math.ceil(we.width),bt=Math.ceil(we.height);Re.lineBlendFbos||(Re.lineBlendFbos=new G0),Re.lineBlendFbos.fbo=K2.createWithTexture(dt,Re.lineBlendFbos.fbo,_t,bt,!0),dt.clear({color:T3[Xe].clearColor,depth:1,stencil:0});const Mt=we.currentStencilSource,ss=we._tileClippingMaskIDs,Jt=we.nextStencilID;we.currentStencilSource=void 0,we._tileClippingMaskIDs={},we.nextStencilID=1,we._renderTileClippingMasks(Re,Me,Ze);const Lt=we.renderPass;we.renderPass="translucent",OC(we,Me,Re,Ze,Uk(Xe,we.context)),we.renderPass=Lt,we.currentStencilSource=Mt,we._tileClippingMaskIDs=ss,we.nextStencilID=Jt,dt.viewport.set([0,0,we.width,we.height]),Xe==="additive"&&qk(we,Re,Re.lineBlendFbos.fbo)}(L,k,T,B,oe);if(L.renderPass==="translucent"){const we=T.lineBlendFbos&&T.lineBlendFbos.fbo;return void(we&&zC(L,T,oe,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 oe=T.paint.get("fill-emissive-strength"),he=L.colorModeForDrapableLayerRenderPass(oe),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),Xe={painter:L,sourceCache:k,layer:T,coords:B,colorMode:he,elevationType:Re,terrainEnabled:Ze,pass:Me};if(L.renderPass==="shadow")return void(L.shadowRenderer&&Re==="road"&&!Ze&&Ui.drawElevatedFillShadows&&Ui.drawElevatedFillShadows(Xe));const dt=L.isEmissiveMrtActive();if(Re!=="offset"){if(BC(Xe,!1,dt),Re==="road"){const _t=!Ze&&L.renderPass==="translucent";_t&&Ui.drawDepthPrepass&&Ui.drawDepthPrepass(L,k,T,B,"geometry"),BC(Xe,!0,dt,o._.disabled),_t&&Ui.drawElevatedStructures&&Ui.drawElevatedStructures(Xe)}}else BC(Xe,!1,dt,L.stencilModeFor3D())},"fill-extrusion":function(L,k,T,B){const K=T.paint.get("fill-extrusion-opacity"),Q=L.context,oe=Q.gl,he=L.terrain,we=he&&he.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(Xe,dt,_t,bt,Mt){for(const ss of bt){const Jt=dt.getTile(ss).getBucket(_t);Jt&&(Jt.updateReplacement(ss,Xe.replacementSource,Mt),Jt.uploadCentroid(Xe.context))}}(L,k,T,B,Ze),he||Re)for(const Xe of B){const dt=k.getTile(Xe).getBucket(T);dt&&Es(L.context,k,Xe,dt,T,he,Re)}if(L.renderPass==="shadow"&&L.shadowRenderer){if(he&&K<.65&&T._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.ak)return;const Xe=L.shadowRenderer.getShadowPassDepthMode();qa(L,k,T,B,Xe,o._.disabled,o.a1.disabled,Re)}else if(L.renderPass==="translucent"){const Xe=!T.paint.get("fill-extrusion-pattern").constantOr(1),dt=T.paint.get("fill-extrusion-color").constantOr(o.C.white);if(!we&&dt.a!==0){const bt=new o.Z(L.context.gl.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D);K===1&&Xe?qa(L,k,T,B,bt,o._.disabled,o.a1.unblended,Re):(qa(L,k,T,B,bt,o._.disabled,o.a1.disabled,Re),qa(L,k,T,B,bt,L.stencilModeFor3D(),L.colorModeForRenderPass(),Re),L.resetStencilClippingMasks())}const _t=L.style.enable3dLights()&&Xe&&(!he&&L.transform.projection.name!=="globe"||we);if(_t&&!xr.drawGroundEffect&&gr(),_t&&xr.drawGroundEffect){const bt=T.paint.get("fill-extrusion-opacity"),Mt=T.paint.get("fill-extrusion-ambient-occlusion-intensity"),ss=T.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),Jt=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),Gs=Mt>0&&ss>0,Ls=Jt>0,sn=new et;sn.translate=T.paint.get("fill-extrusion-translate"),sn.translateAnchor=T.paint.get("fill-extrusion-translate-anchor"),sn.edgeRadius=T.layout.get("fill-extrusion-edge-radius"),sn.cutoffFadeRange=T.paint.get("fill-extrusion-cutoff-fade-range");const Bs=nn=>{const yn=L.depthModeForSublayer(1,o.Z.ReadOnly,oe.LEQUAL,!0),Tn=T.paint.get(nn?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Gn=o.am(.1,3,Tn),zn=L._showOverdrawInspector;if(!zn){const Dn=new o._({func:oe.ALWAYS,mask:255},255,255,oe.KEEP,oe.KEEP,oe.REPLACE),Mr=new o.a1([oe.ONE,oe.ONE,oe.ONE,oe.ONE],o.C.transparent,[!1,!1,!1,!0],oe.MIN);xr.drawGroundEffect(sn,L,k,T,B,yn,Dn,Mr,o.$.disabled,nn,"sdf",bt,Mt,ss,Jt,ps,Gn,Re,!1)}{const Dn=zn?o._.disabled:new o._({func:oe.EQUAL,mask:255},255,255,oe.KEEP,oe.DECR,oe.DECR),Mr=zn?L.colorModeForRenderPass():new o.a1([oe.ONE_MINUS_DST_ALPHA,oe.DST_ALPHA,oe.ONE,oe.ONE],o.C.transparent,[!0,!0,!0,!0]);xr.drawGroundEffect(sn,L,k,T,B,yn,Dn,Mr,o.$.disabled,nn,"color",bt,Mt,ss,Jt,ps,Gn,Re,!1)}};if(we){const nn=()=>{const Tn=he.drapeBufferSize[0],Gn=he.drapeBufferSize[1];let zn=he.framebufferCopyTexture;return zn&&(!zn||zn.size[0]===Tn&&zn.size[1]===Gn)||(zn&&zn.destroy(),zn=he.framebufferCopyTexture=new o.T(Q,new o.b({width:Tn,height:Gn}),oe.RGBA8)),zn.bind(oe.LINEAR,oe.CLAMP_TO_EDGE),oe.copyTexSubImage2D(oe.TEXTURE_2D,0,0,0,0,0,Tn,Gn),zn},yn=(Tn,Gn,zn)=>{const Dn=L.depthModeForSublayer(1,o.Z.ReadOnly,oe.LEQUAL,!1),Mr=T.paint.get(Tn?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),kn=o.am(.1,3,Mr);{const pr=new o.a1([oe.ONE,oe.ONE,oe.ONE,oe.ONE],o.C.transparent,[!1,!1,!1,!0]);xr.drawGroundEffect(sn,L,k,T,B,Dn,o._.disabled,pr,o.$.disabled,Tn,"clear",bt,Mt,ss,Jt,ps,kn,Re,Gn)}{const pr=new o._({func:oe.ALWAYS,mask:255},255,255,oe.KEEP,oe.KEEP,oe.REPLACE),ta=new o.a1([oe.ONE,oe.ONE,oe.ONE,oe.ONE],o.C.transparent,[!1,!1,!1,!0],oe.MIN);xr.drawGroundEffect(sn,L,k,T,B,Dn,pr,ta,o.$.disabled,Tn,"sdf",bt,Mt,ss,Jt,ps,kn,Re,Gn)}Me&&!Tn&&(zn=nn());{const pr=Tn?oe.ZERO:oe.ONE_MINUS_DST_ALPHA,ta=new o._({func:oe.EQUAL,mask:255},255,255,oe.KEEP,oe.DECR,oe.DECR),ka=new o.a1([pr,oe.DST_ALPHA,oe.ONE_MINUS_DST_ALPHA,oe.ZERO],o.C.transparent,[!0,!0,!0,!0]);xr.drawGroundEffect(sn,L,k,T,B,Dn,ta,ka,o.$.disabled,Tn,"color",bt,Mt,ss,Jt,ps,kn,Re,Gn)}if(!Me||Tn){const pr=new o.a1([oe.ONE,oe.ONE,oe.ONE,Tn?oe.ZERO:oe.ONE],o.C.transparent,[!1,!1,!1,!0],Tn?oe.FUNC_ADD:oe.MAX);xr.drawGroundEffect(sn,L,k,T,B,Dn,o._.disabled,pr,o.$.disabled,Tn,"clear",bt,Mt,ss,Jt,ps,kn,Re,Gn,zn)}else{oe.drawBuffers([oe.NONE,oe.COLOR_ATTACHMENT1]);const pr=new o._({func:oe.EQUAL,mask:255},254,255,oe.KEEP,oe.DECR,oe.DECR),ta=new o.a1([oe.ONE,oe.ONE,oe.ONE,oe.ONE],o.C.transparent,[!0,!1,!1,!1],oe.MAX);xr.drawGroundEffect(sn,L,k,T,B,Dn,pr,ta,o.$.disabled,Tn,"emissive",bt,Mt,ss,Jt,ps,kn,Re,Gn,zn),oe.drawBuffers([oe.COLOR_ATTACHMENT0])}};if(Gs||Ls){let Tn;L.prepareDrawTile(),Me&&!Gs||(Tn=nn()),Gs&&yn(!0,!1,Tn),Ls&&yn(!1,!0,Tn)}}else Gs&&Bs(!0),Ls&&Bs(!1),(Gs||Ls)&&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,[oe,he]=L.renderPass!=="translucent"||Q?[{},B]:L.stencilConfigForOverlap(B);for(const we of he){const Me=k.getTile(we);if(Me.needsHillshadePrepare&&L.renderPass==="offscreen")lh(L,Me,T);else if(L.renderPass==="translucent"){const Re=L.depthModeForSublayer(0,o.Z.ReadOnly),Ze=T.paint.get("hillshade-emissive-strength"),Xe=L.colorModeForDrapableLayerRenderPass(Ze),dt=Q&&L.terrain?L.terrain.stencilModeForRTTOverlap(we):oe[we.overscaledZ];sp(L,we,Me,T,Re,dt,Xe)}}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 oe=T.paint.get("raster-opacity");if(oe===0)return;const he=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,Xe=Re&&he,dt=!he&&Ze;if(L.renderElevatedRasterBackface&&!Xe)return;const _t=L.context,bt=_t.gl,Mt=k.getSource(),ss=function(Tn,Gn,zn,Dn,Mr){const kn=zn.paint.get("raster-color"),pr=Gn.type==="raster-array",ta=[],ka=zn.paint.get("raster-resampling"),qr=zn.paint.get("raster-color-mix");let Jr=zn.paint.get("raster-color-range");const si=[qr[0],qr[1],qr[2],0],Gr=qr[3];let Sr=ka==="nearest"?Mr.NEAREST:Mr.LINEAR;if(pr&&(ta.push("RASTER_ARRAY"),kn||ta.push("RASTER_COLOR"),ka==="linear"&&ta.push("RASTER_ARRAY_LINEAR"),Sr=Mr.NEAREST,kn&&zn.paint.get("raster-color-scale")==="log"&&ta.push("RASTER_COLOR_SCALE_LOG"),!Jr&&Gn.rasterLayers)){const Hr=Gn.rasterLayers.find(({id:Ha})=>Ha===zn.sourceLayer);Hr&&Hr.fields&&Hr.fields.range&&(Jr=Hr.fields.range)}if(Jr=Jr||[0,1],kn){ta.push("RASTER_COLOR"),Dn.activeTexture.set(Mr.TEXTURE2),zn.updateColorRamp(Jr);let Hr=zn.colorRampTexture;Hr||(Hr=zn.colorRampTexture=new o.T(Dn,zn.colorRamp,Mr.RGBA8)),Hr.bind(Sr,Mr.CLAMP_TO_EDGE)}return Tn.terrain&&Tn.terrain.renderingToTexture&&Tn.isEmissiveMrtActive()&&(ta.push("USE_MRT1"),Tn.emissiveMode==="mrt-full-rgba"&&ta.push("USE_MRT1_RGBA")),{mix:si,range:Jr,offset:Gr,defines:ta,resampling:Sr}}(L,Mt,T,_t,bt);if(Mt instanceof Fi&&!B.length&&!he)return;const Jt=T.paint.get("raster-emissive-strength"),Lt=L.colorModeForDrapableLayerRenderPass(Jt),ps=L.terrain&&L.terrain.renderingToTexture,Gs=!L.options.moving,Ls=T.paint.get("raster-resampling")==="nearest"?bt.NEAREST:bt.LINEAR;if(Mt instanceof Fi&&!B.length&&(Mt.onNorthPole||Mt.onSouthPole)){const Tn=Re?L.stencilModeFor3D():o._.disabled;return void M3(we,!!Mt.onNorthPole,null,L,k,T,Jt,ss,o.$.disabled,Tn)}if(!B.length)return;const[sn,Bs]=Mt instanceof Fi||ps?[{},B]:L.stencilConfigForOverlap(B),nn=Bs.at(-1).overscaledZ;Xe&&ss.defines.push("PROJECTION_GLOBE_VIEW"),Re&&ss.defines.push("RENDER_CUTOFF","ELEVATED"),Ze&&ss.defines.push("ELEVATION_REFERENCE_GROUND");const yn=(Tn,Gn,zn)=>{for(const Dn of Tn){const Mr=Dn.toUnwrapped(),kn=k.getTile(Dn);if(ps&&(!kn||!kn.hasData()))continue;_t.activeTexture.set(bt.TEXTURE0);const pr=WT(kn,Mt,T,ss);if(!pr||!pr.texture)continue;const{texture:ta,mix:ka,offset:qr,tileSize:Jr,buffer:si}=pr;let Gr,Sr;ps?(Gr=o.Z.disabled,Sr=Dn.projMatrix):Re?(Gr=new o.Z(bt.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D),Sr=he?L.transform.expandedFarZProjMatrix:L.transform.calculateProjMatrix(Mr,Gs)):(Gr=L.depthModeForSublayer(Dn.overscaledZ-nn,oe===1?o.Z.ReadWrite:o.Z.ReadOnly,bt.LESS),Sr=L.transform.calculateProjMatrix(Mr,Gs));const Hr=L.terrain&&ps?L.terrain.stencilModeForRTTOverlap(Dn):sn[Dn.overscaledZ],Ha=Q?0:T.paint.get("raster-fade-duration");kn.registerFadeDuration(Ha);const $r=k.findLoadedParent(Dn,0),Ya=Cd(kn,$r,k,L.transform,Ha);let Oi,Do;!Ya.isFading&&kn.refreshedUponExpiration&&(kn.refreshedUponExpiration=!1),L.terrain&&L.terrain.prepareDrawTile(),_t.activeTexture.set(bt.TEXTURE0),ta.bind(Ls,bt.CLAMP_TO_EDGE),_t.activeTexture.set(bt.TEXTURE1),$r?($r.texture&&$r.texture.bind(Ls,bt.CLAMP_TO_EDGE),Oi=Math.pow(2,$r.tileID.overscaledZ-kn.tileID.overscaledZ),Do=[kn.tileID.canonical.x*Oi%1,kn.tileID.canonical.y*Oi%1]):ta.bind(Ls,bt.CLAMP_TO_EDGE),"useMipmap"in ta&&_t.extTextureFilterAnisotropic&&L.transform.pitch>20&&bt.texParameterf(bt.TEXTURE_2D,_t.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,_t.extTextureFilterAnisotropicMax);const to=L.transform;let ql;const yu=Re?L6(to):[0,0,0,0];let Uc,Ko,so,_d,Gh,_h=0;if(Xe&&Mt instanceof Fi&&Mt.coordinates.length>3)Uc=Float32Array.from(o.b5(o.b6(new o.bW(0,0,0)))),Ko=Float32Array.from(to.globeMatrix),so=Float32Array.from(o.b7(to)),_d=[o.a7(to.center.lng),o.a8(to.center.lat)],ql=Mt.elevatedGlobePerspectiveTransform,Gh=Mt.elevatedGlobeGridMatrix||new Float32Array(9);else if(Xe){const dc=o.b3(Dn.canonical);_h=o.b4(dc.getCenter().lat),Uc=Float32Array.from(o.b5(o.b6(Dn.canonical))),Ko=Float32Array.from(to.globeMatrix),so=Float32Array.from(o.b7(to)),_d=[o.a7(to.center.lng),o.a8(to.center.lat)],ql=[0,0],Gh=Float32Array.from(o.b8(Dn.canonical,dc,_h,to.worldSize/to._pixelsPerMercatorPixel))}else ql=Mt instanceof Fi?Mt.perspectiveTransform:[0,0],Uc=new Float32Array(16),Ko=new Float32Array(9),so=new Float32Array(16),_d=[0,0],Gh=new Float32Array(9);const Vl=ks(L,Sr,Uc,Ko,so,Gh,Do||[0,0],o.S(L.transform.zoom),_d,yu,Oi||1,Ya,T,ql,we,2,ka,qr,ss.range,Jr,si,Jt),mm=L.isTileAffectedByFog(Dn),yc=L.getOrCreateProgram("raster",{defines:ss.defines,overrideFog:mm});if(L.uploadCommonUniforms(_t,yc,Mr),Mt instanceof Fi){const dc=Mt.elevatedGlobeVertexBuffer,Dh=Mt.elevatedGlobeIndexBuffer;if(ps||!he)Mt.boundsBuffer&&Mt.boundsSegments&&yc.draw(L,bt.TRIANGLES,Gr,o._.disabled,Lt,o.$.disabled,Vl,T.id,Mt.boundsBuffer,L.quadTriangleIndexBuffer,Mt.boundsSegments);else if(dc&&Dh){const Wh=to.zoom<=o.ef?Mt.elevatedGlobeSegments:Mt.getSegmentsForLongitude(to.center.lng);Wh&&yc.draw(L,bt.TRIANGLES,Gr,o._.disabled,Lt,Gn,Vl,T.id,dc,Dh,Wh)}}else if(Xe){Gr=new o.Z(bt.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D);const dc=L.globeSharedBuffers;if(dc){Ze&&(L.terrain.setupElevationDraw(kn,yc),L.uploadCommonUniforms(_t,yc,kn.tileID.toUnwrapped()));const[Dh,Wh,Pd]=dc.getGridBuffers(_h,!1),vc=yc.getAttributeLocation(bt,"a_texture_pos");vc!==-1&&bt.vertexAttribI4ui(vc,0,0,0,0),yc.draw(L,bt.TRIANGLES,Gr,zn||Hr,L.colorModeForRenderPass(),Gn,Vl,T.id,Dh,Wh,Pd)}}else if(dt)Gr=new o.Z(bt.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D),L.terrain.setupElevationDraw(kn,yc),L.uploadCommonUniforms(_t,yc,kn.tileID.toUnwrapped()),to.pitch>20&&yc.draw(L,bt.TRIANGLES,Gr,o._.disabled,o.a1.disabled,o.$.frontCCW,Vl,T.id,L.terrain.gridBuffer,L.terrain.gridIndexBuffer,L.terrain.gridSegments),yc.draw(L,bt.TRIANGLES,Gr,Hr,Lt,o.$.backCCW,Vl,T.id,L.terrain.gridBuffer,L.terrain.gridIndexBuffer,L.terrain.gridSegments);else{const{tileBoundsBuffer:dc,tileBoundsIndexBuffer:Dh,tileBoundsSegments:Wh}=L.getTileBoundsBuffers(kn);yc.draw(L,bt.TRIANGLES,Gr,Hr,Lt,o.$.disabled,Vl,T.id,dc,Dh,Wh)}}if(!(Mt instanceof Fi)&&Xe)for(const Dn of Tn){const Mr=Dn.canonical.y===(1<sn.tileID)),dt&&(Me.activeTexture.set(Re.TEXTURE0),L.imageManager.bind(L.context,T.scope));const Ls=[];if(L.terrain&&L.terrain.renderingToTexture&&L.isEmissiveMrtActive()&&(Ls.push("USE_MRT1"),L.emissiveMode==="mrt-full-rgba"&&Ls.push("USE_MRT1_RGBA")),we){const sn=L.getOrCreateProgram(Lt,{overrideFog:!1,overrideRtt:!0,defines:Ls}),Bs=R6,nn=new o.bQ(0,0,0,0,0),yn=dt?Kn(Bs,he,oe,L,dt,T.scope,_t,we,{tileID:nn,tileSize:Xe}):an(Bs,he,oe,K.toPremultipliedRenderColor(Q?null:T.lut));return void sn.draw(L,Re.TRIANGLES,ss,Mt,Jt,o.$.disabled,yn,T.id,L.viewportBuffer,L.quadTriangleIndexBuffer,L.viewportSegments)}for(const sn of Gs){const Bs=L.isTileAffectedByFog(sn),nn=L.getOrCreateProgram(Lt,{overrideFog:Bs,defines:Ls}),yn=sn.toUnwrapped(),Tn=B?sn.projMatrix:L.transform.calculateProjMatrix(yn);L.prepareDrawTile();const Gn=k?k.getTile(sn):ps?ps[sn.key]:new Px(sn,Xe,Ze.zoom,L),zn=dt?Kn(Tn,he,oe,L,dt,T.scope,_t,we,{tileID:sn,tileSize:Xe}):an(Tn,he,oe,K.toPremultipliedRenderColor(Q?null:T.lut));L.uploadCommonUniforms(Me,nn,yn);const{tileBoundsBuffer:Dn,tileBoundsIndexBuffer:Mr,tileBoundsSegments:kn}=L.getTileBoundsBuffers(Gn);nn.draw(L,Re.TRIANGLES,ss,Mt,Jt,o.$.disabled,zn,T.id,Dn,Mr,kn)}},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,oe=T.paint.get("sky-type"),he=new o.Z(Q.gl.LEQUAL,o.Z.ReadOnly,[0,1]),we=L.frameCounter/1e3%1;oe==="atmosphere"?L.renderPass==="offscreen"?T.needsSkyboxCapture(L)&&(function(Me,Re){const Ze=Me.context,Xe=Ze.gl;let dt=Re.skyboxFbo;if(!dt){dt=Re.skyboxFbo=Ze.createFramebuffer(32,32,1,null),Re.skyboxGeometry=new de(Ze),Re.skyboxTexture=Ze.gl.createTexture(),Xe.bindTexture(Xe.TEXTURE_CUBE_MAP,Re.skyboxTexture),Xe.texParameteri(Xe.TEXTURE_CUBE_MAP,Xe.TEXTURE_WRAP_S,Xe.CLAMP_TO_EDGE),Xe.texParameteri(Xe.TEXTURE_CUBE_MAP,Xe.TEXTURE_WRAP_T,Xe.CLAMP_TO_EDGE),Xe.texParameteri(Xe.TEXTURE_CUBE_MAP,Xe.TEXTURE_MIN_FILTER,Xe.LINEAR),Xe.texParameteri(Xe.TEXTURE_CUBE_MAP,Xe.TEXTURE_MAG_FILTER,Xe.LINEAR);for(let ss=0;ss<6;++ss)Xe.texImage2D(Xe.TEXTURE_CUBE_MAP_POSITIVE_X+ss,0,Xe.RGBA,32,32,0,Xe.RGBA,Xe.UNSIGNED_BYTE,null)}Ze.bindFramebuffer.set(dt.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,Xe,dt){const _t=Me.context,bt=_t.gl,Mt=Me.transform,ss=Me.getOrCreateProgram("skybox");_t.activeTexture.set(bt.TEXTURE0),bt.bindTexture(bt.TEXTURE_CUBE_MAP,Re.skyboxTexture);const Jt=((Lt,ps,Gs,Ls,sn)=>({u_matrix:Lt,u_sun_direction:ps,u_cubemap:0,u_opacity:Ls,u_temporal_offset:sn}))(Mt.skyboxMatrix,Re.getCenter(Me,!1),0,Xe,dt);Me.uploadCommonUniforms(_t,ss),ss.draw(Me,bt.TRIANGLES,Ze,o._.disabled,Me.colorModeForRenderPass(),o.$.backCW,Jt,"skybox",Re.skyboxGeometry.vertexBuffer,Re.skyboxGeometry.indexBuffer,Re.skyboxGeometry.segment)}(L,T,he,K,we):oe==="gradient"&&L.renderPass==="sky"&&function(Me,Re,Ze,Xe,dt){const _t=Me.context,bt=_t.gl,Mt=Me.transform,ss=Me.getOrCreateProgram("skyboxGradient");Re.skyboxGeometry||(Re.skyboxGeometry=new de(_t)),_t.activeTexture.set(bt.TEXTURE0);let Jt=Re.colorRampTexture;Jt||(Jt=Re.colorRampTexture=new o.T(_t,Re.colorRamp,bt.RGBA8)),Jt.bind(bt.LINEAR,bt.CLAMP_TO_EDGE);const Lt=((ps,Gs,Ls,sn,Bs)=>({u_matrix:ps,u_color_ramp:0,u_center_direction:Gs,u_radius:o.av(Ls),u_opacity:sn,u_temporal_offset:Bs}))(Mt.skyboxMatrix,Re.getCenter(Me,!1),Re.paint.get("sky-gradient-radius"),Xe,dt);Me.uploadCommonUniforms(_t,ss),ss.draw(Me,bt.TRIANGLES,Ze,o._.disabled,Me.colorModeForRenderPass(),o.$.backCW,Lt,"skyboxGradient",Re.skyboxGeometry.vertexBuffer,Re.skyboxGeometry.indexBuffer,Re.skyboxGeometry.segment)}(L,T,he,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 oe=Q.prerender;if(oe){if(L.setCustomLayerDefaults(),K.setColorMode(L.colorModeForRenderPass()),L.transform.projection.name==="globe"){const he=L.transform.pointMerc;oe.call(Q,K.gl,L.transform.customLayerMatrix(),L.transform.getProjection(),L.transform.globeToMercatorMatrix(),o.S(L.transform.zoom),[he.x,he.y],L.transform.pixelsPerMeterRatio)}else oe.call(Q,K.gl,L.transform.customLayerMatrix());K.setDirty(),L.setBaseState()}}else if(L.renderPass==="translucent"){if(L.terrain&&L.terrain.renderingToTexture){const he=Q.renderToTile;if(he){const we=B[0].canonical,Me={x:we.x+B[0].wrap*(Q.wrapTileId?0:1<k.getTileByID(he));for(const he of oe)he.updateNeeded(L.id,Q)&&B.prepareTile(he,K,L.id,Q)}};async function Zi(L){if(await gr(),Object.assign(Mi,{model:xr.drawModels}),Object.assign(pl,{model:xr.prepare}),L&&!L._destroyed&&!L._shadowRenderer){const k=xr.ShadowRenderer;k&&(L._shadowRenderer=new k(L))}}class Hh{constructor(k,T,B,K,Q,oe){this._forceFullRgbaEmissive=!1,this.context=new _m(k,T),this._forceFullRgbaEmissive=oe==="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 ci,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 Or,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const he=new o.b({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,he,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=Qg(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)},V2?K():z_.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=Qg(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,Xc.members),this.mercatorBoundsSegments=o.ad.simpleSegment(0,0,4,2);const oe=new o.ae;oe.emplaceBack(0,1,2),oe.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=k.createIndexBuffer(oe);const he=new o.bE;for(const Me of[0,1,3,2,0])he.emplaceBack(Me);this.debugIndexBuffer=k.createIndexBuffer(he),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,gu(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 he=!1;for(const we of B)if(this._tileClippingMaskIDs[we.key]===void 0){he=!0;break}if(!he)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 oe=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const he of B){const we=T.getTile(he),Me=this._tileClippingMaskIDs[he.key]=this.nextStencilID++,{tileBoundsBuffer:Re,tileBoundsIndexBuffer:Ze,tileBoundsSegments:Xe}=this.getTileBoundsBuffers(we);oe.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,gu(he.projMatrix),"$clipping",Re,Ze,Xe)}}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((oe,he)=>he.overscaledZ-oe.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 oe={};for(let he=0;hethis.style._getOrder(K);let oe=Q(),he=!1,we=!1,Me=null,Re=0,Ze=!1;for(const kn of oe){const pr=B[kn];pr.visibility!=="none"&&(pr.type==="circle"?he=!0:pr.type==="building"?(Me=pr,++Re):pr.type==="symbol"&&(pr.hasOcclusionOpacityProperties?we=!0:he=!0))}this.updateEmissiveMode();let Xe=oe.map(kn=>B[kn]);const dt=this.style._mergedSourceCaches;this.imageManager=k.imageManager,this.modelManager=k.modelManager,this.symbolFadeChange=k.placement.symbolFadeChange(o.e.now()),this.imageManager.beginFrame();for(const kn in dt){const pr=dt[kn];pr.used&&(pr.prepare(this.context),pr.getSource().usedInConflation&&++Re)}let _t=!1;for(const kn of Xe)kn.isHidden(this.transform.zoom)||(kn.type==="clip"&&(_t=!0),this.prepareLayer(kn));const bt={},Mt={},ss={},Jt={},Lt={};for(const kn in dt){const pr=dt[kn];bt[kn]=pr.getVisibleCoordinates(),Mt[kn]=bt[kn].slice().reverse(),ss[kn]=pr.getVisibleCoordinates(!0).reverse(),Jt[kn]=pr.getShadowCasterCoordinates(),Lt[kn]=pr.sortCoordinatesByDistance(bt[kn])}const ps=kn=>{const pr=this.style.getLayerSourceCache(kn);return pr&&pr.used?pr.getSource():null};if(Re||_t||this._clippingActiveLastFrame){const kn=[],pr=[];let ta=0;for(const ka of Xe)this.isSourceForClippingOrConflation(ka,ps(ka))&&(kn.push(ka),pr.push(ta)),ta++;if(kn&&(_t||kn.length>1)||this._clippingActiveLastFrame){_t=!1;const ka=[];for(let qr=0;qr0){const ka=ps(pr);ka&&(this.minCutoffZoom=Math.max(ka.minzoom,this.minCutoffZoom)),pr.minzoom&&(this.minCutoffZoom=Math.max(pr.minzoom,this.minCutoffZoom))}pr.is3D(K)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=kn),this._lastOcclusionLayer=kn)}const Gs=this.style&&this.style.fog;Gs?(this._fogVisible=Gs.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Gs.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(ss),this.opaquePassCutoff=0,oe=Q(),Xe=oe.map(kn=>B[kn])),this.style.enable3dLights()&&!this._shadowRenderer&&Zi(this);const Ls=this._shadowRenderer;if(Ls){Ls.updateShadowParameters(this.transform,this.style.directionalLight,Jt);for(const kn in dt)for(const pr of bt[kn]){let ta={min:0,max:0};this.terrain&&(ta=this.terrain.getMinMaxForTile(pr)||ta),Ls.addShadowReceiver(pr.toUnwrapped(),ta.min,ta.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 Ys),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);let sn=!(!this.style||!this.style.snow),Bs=!(!this.style||!this.style.rain);if(sn&&!this._snow&&Ui.Snow&&(this._snow=new Ui.Snow),!sn&&this._snow&&(this._snow.destroy(),delete this._snow),Bs&&!this._rain&&Ui.Rain&&(this._rain=new Ui.Rain),!Bs&&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 kn=this.style.getLayerSourceCache(Me);this.buildingTileBorderManager.updateBorders(kn,Me)}if(!o.ez(this.context.gl))return;this.renderPass="offscreen";for(const kn of Xe){const pr=k.getLayerSourceCache(kn);if(!kn.hasOffscreenPass()||kn.isHidden(this.transform.zoom))continue;const ta=pr?Mt[pr.id]:void 0;(kn.type==="custom"||kn.type==="raster"||kn.type==="raster-particle"||kn.isSky()||ta&&ta.length)&&this.renderLayer(this,pr,kn,ta)}this.depthRangeFor3D=[0,1-(Xe.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Jt)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const nn=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),yn=(()=>{if(T.showOverdrawInspector)return o.C.black;const kn=this.style.fog;if(kn&&this.transform.projection.supportsFog){const pr=this.style.getLut(kn.scope);if(!nn){const ta=kn.properties.get("color-use-theme")==="none",ka=kn.properties.get("color").toNonPremultipliedRenderColor(ta?null:pr).toArray01();return new o.C(...ka)}if(nn){const ta=kn.properties.get("space-color-use-theme")==="none",ka=kn.properties.get("space-color").toNonPremultipliedRenderColor(ta?null:pr).toArray01();return new o.C(...ka)}}return o.C.transparent})();if(this.context.clear({color:yn,depth:1}),this.clearStencil(),this._showOverdrawInspector=T.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&nn&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=oe.length-1;this.currentLayer>=0;this.currentLayer--){const kn=Xe[this.currentLayer],pr=k.getLayerSourceCache(kn);if(kn.isSky())continue;const ta=pr?(kn.is3D(K)?Lt:Mt)[pr.id]:void 0;this._renderTileClippingMasks(kn,pr,ta),this.renderLayer(this,pr,kn,ta)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&nn&&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 ta=this.currentLayer;this.depthOcclusion=!0;for(const ka of this.layersWithOcclusionOpacity){this.currentLayer=ka;const qr=Xe[this.currentLayer],Jr=k.getLayerSourceCache(qr),si=Jr?Mt[Jr.id]:void 0;this.terrain||this._renderTileClippingMasks(qr,Jr,Jr?bt[Jr.id]:void 0),this.renderLayer(this,Jr,qr,si)}this.depthOcclusion=!1,this.currentLayer=ta,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 kn=null;Xe.forEach(pr=>{const ta=k.getLayerSourceCache(pr);ta&&!pr.isHidden(this.transform.zoom)&&ta.getVisibleCoordinates().length&&(!kn||kn.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 oe=B===void 0?!!this._terrain&&this._terrain.renderingToTexture:B,he=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")):oe||Me.push("LIGHTING_3D_MODE")),he&&(Me.push("TERRAIN"),this.linearFloatFilteringSupported()&&Me.push("TERRAIN_DEM_FLOAT_FORMAT")),we&&Me.push("GLOBE"),!this._fogVisible||oe||T!==void 0&&!T||Me.push("FOG"),oe&&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:oe,overrideTerrain:he,overrideGlobe:we,precompiled:Me}=T||{},Re=this.currentGlobalDefines(k,Q,oe,he,we).concat(B||[]),Ze=this.getShaderSource(k),Xe=Ui.programUniforms,dt=xr.programUniforms,_t=jr[k]||Xe&&Xe[k]||dt&&dt[k],bt=W2.cacheKey(Ze,k,Re,K);return this.cache[bt]||(this.cache[bt]=new W2(this.context,k,Ze,K,_t,Re,Me)),this.cache[bt]}getShaderSource(k){const T=Ui.shaders,B=xr.shaders,K=ir.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 oe=((he,we,Me,Re)=>{const Ze=he.properties.get("direction"),Xe=he.properties.get("color-use-theme")==="none",dt=he.properties.get("color").toNonPremultipliedRenderColor(Xe?null:Me.getLut(he.scope)).toArray01();let _t=he.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 ss=we.properties.get("intensity");const Jt=[Ze.x,Ze.y,Ze.z];Re&&(Re.ambientIntensity!==void 0&&(ss=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&&(dt[0]=Re.directionalColor[0],dt[1]=Re.directionalColor[1],dt[2]=Re.directionalColor[2]));const Lt=o.dU(Mt,ss),ps=o.dU(dt,_t);return{u_lighting_ambient_color:Lt,u_lighting_directional_dir:Jt,u_lighting_directional_color:ps,u_ground_radiance:G2(Jt,ps,Lt)}})(K,Q,this.style,B);T.setLightsUniformValues(k,oe)}}}uploadCommonUniforms(k,T,B,K,Q,oe){if(this.uploadCommonLightUniforms(k,T,oe),this.terrain&&this.terrain.renderingToTexture)return;const he=this.style.fog;if(he){const we=he.getOpacity(this.transform.pitch),Me=((Re,Ze,Xe,dt,_t,bt,Mt,ss,Jt,Lt,ps,Gs)=>{const Ls=Re.transform,sn=Ze.properties.get("color-use-theme")==="none",Bs=Ze.properties.get("color").toNonPremultipliedRenderColor(sn?null:Re.style.getLut(Ze.scope)).toArray01();Bs[3]=dt;const nn=Re.frameCounter/1e3%1,[yn,Tn]=Ze.properties.get("vertical-range");return{u_fog_matrix:Xe?Ls.calculateFogTileMatrix(Xe):Gs||Re.identityMat,u_fog_range:Ze.getRangeForProjection(),u_fog_color:Bs,u_fog_horizon_blend:Ze.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(yn,Tn),Tn],u_fog_temporal_offset:nn,u_frustum_tl:_t,u_frustum_tr:bt,u_frustum_br:Mt,u_frustum_bl:ss,u_globe_pos:Jt,u_globe_radius:Lt,u_viewport:ps,u_globe_transition:o.S(Ls.zoom),u_is_globe:+(Ls.projection.name==="globe")}})(this,he,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 Px(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,oe=!!B;var he;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/((he=this.depthRangeFor3D)[1]-he[0]),-1-2*he[0]/(he[1]-he[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),oe||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 uh(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 xy=/(#.+)?$/;class U_{constructor(k){this._hashName=k&&encodeURIComponent(k),o.aW(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=uh(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=zr(k);if(this._hashName){const B=this._hashName;let K=!1;const Q=location.hash.slice(1).split("&").map(oe=>{const he=oe.split("=")[0];return he===B?(K=!0,`${he}=${T}`):oe}).filter(oe=>oe);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(xy,this.getHashString()))}}function zr(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),oe=Math.round(T.lng*Q)/Q,he=Math.round(T.lat*Q)/Q,we=L.getBearing(),Me=L.getPitch();let Re=k?`/${oe}/${he}/${B}`:`${B}/${he}/${oe}`;return(we||Me)&&(Re+="/"+Math.round(10*we)/10),Me&&(Re+=`/${Math.round(Me)}`),Re}const Hn={linearity:.3,easing:o.eC(0,0,.3,1)},aa={deceleration:2500,maxSpeed:1400,...Hn},Qi={deceleration:20,maxSpeed:1400,...Hn},gl={deceleration:1e3,maxSpeed:360,...Hn},Jc={deceleration:1e3,maxSpeed:90,...Hn};class Sc{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=bh(T.pan.mag(),B,{...aa,...k||{}});K.offset=T.pan.mult(Q.amount/T.pan.mag()),K.center=this._map.transform.center,Md(K,Q)}if(T.zoom){const Q=bh(T.zoom,B,Qi);K.zoom=this._map.transform.zoom+Q.amount,Md(K,Q)}if(T.bearing){const Q=bh(T.bearing,B,gl);K.bearing=this._map.transform.bearing+o.b1(Q.amount,-179,179),Md(K,Q)}if(T.pitch){const Q=bh(T.pitch,B,Jc);K.pitch=this._map.transform.pitch+Q.amount,Md(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 Md(L,k){(!L.duration||L.durationT.unproject(we)),he=Q.reduce((we,Me,Re,Ze)=>we.add(Me.div(Ze.length)),new o.P(0,0));super(k,{points:Q,point:he,lngLats:oe,lngLat:T.unproject(he),originalEvent:B}),this._defaultPrevented=!1}}class kr extends o.h{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(k,T){super("wheel",{originalEvent:T}),this._defaultPrevented=!1}}class P3{constructor(k,T){this._map=k,this._clickTolerance=T.clickTolerance}reset(){this._mousedownPos=void 0}wheel(k){return this._firePreventable(new kr(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 fr(k.type,this._map,k))}touchmove(k){this._map.fire(new fr(k.type,this._map,k))}touchend(k){this._map.fire(new fr(k.type,this._map,k))}touchcancel(k){this._map.fire(new fr(k.type,this._map,k))}_firePreventable(k){if(this._map.fire(k),k.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Wu{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(${oe}px,${we}px)`,this._box.style.width=he-oe+"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 N9(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 oe of K)Q._add(oe);return Q.div(K.length)}(T),this.touches=N9(B,T)))}touchmove(k,T,B){if(this.aborted||!this.centroid)return;const K=N9(B,T);for(const Q in this.touches){const oe=K[Q];(!oe||oe.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 F6{constructor(k){this.singleTap=new k9(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,oe=!this.lastTap||this.lastTap.dist(K)<30;if(Q&&oe||this.reset(),this.count++,this.lastTime=k.timeStamp,this.lastTap=K,this.count===this.numTaps)return this.reset(),K}}}class dY{constructor(){this._zoomIn=new F6({numTouches:1,numTaps:2}),this._zoomOut=new F6({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:oe=>oe.easeTo({duration:300,zoom:oe.getZoom()+1,around:oe.unproject(K)},{originalEvent:k})}):Q?(this._active=!0,k.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:oe=>oe.easeTo({duration:300,zoom:oe.getZoom()-1,around:oe.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 loe=0,coe=2,KT={[loe]:1,[coe]:2},doe={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class uY{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 oe=KT[Q];return K.buttons===void 0||(K.buttons&oe)!==oe}(k,this._eventButton))this.reset();else if(this._moved||!(T.dist(B)0&&(this._active=!0);const K=N9(B,T),Q=new o.P(0,0),oe=new o.P(0,0);let he=0;for(const Me in K){const Re=K[Me],Ze=this._touches[Me];Ze&&(Q._add(Re),oe._add(Re.sub(Ze)),he++,K[Me]=Re)}if(this._touches=K,he{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class C9{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,oe]=K,he=I3(B,T,Q),we=I3(B,T,oe);if(!he||!we)return;const Me=this._aroundCenter?null:he.add(we).div(2);return this._move([he,we],Me,k)}touchend(k,T,B){if(!this._firstTwoTouches)return;const[K,Q]=this._firstTwoTouches,oe=I3(B,T,K),he=I3(B,T,Q);oe&&he||(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 I3(L,k,T){for(let B=0;BMath.abs(L.x)}class foe extends C9{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,mY(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]),oe=k[1].sub(K[1]);return this._map._cooperativeGestures&&!o.eD()&&B.touches.length<3||(this._valid=this.gestureBeginsVertically(Q,oe,B.timeStamp),!this._valid)?void 0:(this._lastPoints=k,this._active=!0,{pitchDelta:(Q.y+oe.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 oe=k.y>0==T.y>0;return mY(k)&&mY(T)&&oe}}const poe={panStep:100,bearingStep:15,pitchStep:10};class goe{constructor(){const k=poe;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,oe=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(),oe=-1);break;case 40:k.shiftKey?K=-1:(k.preventDefault(),oe=1);break;default:return}return this._bearingDisabled&&(B=0),this._pitchDisabled&&(K=0),this._panDisabled&&(Q=0,oe=0),this._zoomDisabled&&(T=0),{cameraAnimation:he=>{const we=he.getZoom();he.easeTo({duration:300,easeId:"keyboardHandler",easing:TFe,zoom:T?Math.round(we)+T*(k.shiftKey?2:1):we,bearing:he.getBearing()+B*this._bearingStep,pitch:he.getPitch()+K*this._pitchStep,offset:[-Q*this._panStep,-oe*this._panStep],center:he.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 TFe(L){return L*(2-L)}const fY=4.000244140625,MFe=1/450,Qy=/(Mac|iPad)/i;class A9{constructor(k,T){this._map=k,this._el=k.getCanvasContainer(),this._handler=T,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=MFe,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%fY===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)>fY?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(),Xe=Math.pow(2,Ze),dt=typeof this._targetZoom=="number"?k.zoomScale(this._targetZoom):Xe;this._targetZoom=Math.min(k.maxZoom,Math.max(k.minZoom,k.scaleZoom(dt*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 oe,he=!1;if(this._type==="wheel"&&K&&Q){const Me=Math.min((o.e.now()-this._lastWheelEventTime)/200,1),Re=Q(Me);oe=o.am(K,B,Re),Me<1?this._frameId||(this._frameId=!0):he=!0}else oe=B,he=!0;this._active=!0,he&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let we=oe-T();return we*this._lastDelta<0&&(we=0),{noInertia:!0,needsRenderFrame:!he,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),oe=.27/Math.sqrt(Q*Q+1e-4)*.01,he=Math.sqrt(.0729-oe*oe);T=o.eC(oe,he,.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=Qy.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 ZT{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 xoe{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 L3{constructor(){this._tap=new F6({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 B6{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 PFe{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 IFe{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 E9=L=>L.zoom||L.drag||L.pitch||L.rotate;class LFe extends o.h{}class RFe{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 T9(L){return L.panDelta&&L.panDelta.mag()||L.zoomDelta||L.bearingDelta||L.pitchDelta}class DFe{constructor(k,T){this._map=k,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Sc(k),this._bearingSnap=T.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new RFe,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,oe]of this._listeners){const he=K===document?this.handleWindowEvent:this.handleEvent;K.addEventListener(Q,he,oe)}}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 P3(T,k));const K=T.boxZoom=new Zs(T,k);this._add("boxZoom",K);const Q=new dY,oe=new xoe;T.doubleClickZoom=new ZT(oe,Q),this._add("tapZoom",Q),this._add("clickZoom",oe);const he=new L3;this._add("tapDragZoom",he);const we=T.touchPitch=new foe(T);this._add("touchPitch",we);const Me=new O6(k),Re=new S9(k);T.dragRotate=new PFe(k,Me,Re),this._add("mouseRotate",Me,["mousePitch"]),this._add("mousePitch",Re,["mouseRotate"]);const Ze=new uoe(k),Xe=new hoe(T,k);T.dragPan=new B6(B,Ze,Xe),this._add("mousePan",Ze),this._add("touchPan",Xe,["touchZoom","touchRotate"]);const dt=new moe,_t=new z6;T.touchZoomRotate=new IFe(B,_t,dt,he),this._add("touchRotate",dt,["touchPan","touchZoom"]),this._add("touchZoom",_t,["touchPan","touchRotate"]),this._add("blockableMapEvent",new Wu(T));const bt=T.scrollZoom=new A9(T,this);this._add("scrollZoom",bt,["mousePan"]);const Mt=T.keyboard=new goe;this._add("keyboard",Mt);for(const ss of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])k.interactive&&k[ss]&&T[ss].enable(k[ss])}_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!!E9(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},oe={},he={},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:Xe,handler:dt,allowed:_t}of this._handlers){if(!dt.isEnabled())continue;let bt;this._blockedByActive(he,_t,Xe)?dt.reset():dt[T||k.type]&&(bt=dt[T||k.type](k,Me,we),this.mergeHandlerResult(Q,oe,bt,Xe,K),bt&&bt.needsRenderFrame&&this._triggerRenderFrame()),(bt||dt.isActive())&&(he[Xe]=dt)}const Re={};for(const Xe in this._previousActiveHandlers)he[Xe]||(Re[Xe]=K);this._previousActiveHandlers=he,(Object.keys(Re).length||T9(Q))&&(this._changes.push([Q,oe,Re]),this._triggerRenderFrame()),(Object.keys(he).length||T9(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 oe={handlerName:K,originalEvent:B.originalEvent||Q};B.zoomDelta!==void 0&&(T.zoom=oe),B.panDelta!==void 0&&(T.drag=oe),B.pitchDelta!==void 0&&(T.pitch=oe),B.bearingDelta!==void 0&&(T.rotate=oe)}_applyChanges(){const k={},T={},B={};for(const[K,Q,oe]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,oe);this._updateMapTransform(k,T,B),this._changes=[]}_updateMapTransform(k,T,B){const K=this._map,Q=K.transform,oe=Jt=>[Jt.x,Jt.y,Jt.z];if((()=>{const Jt=this._eventsInProgress.drag;return Jt&&!this._handlersById[Jt.handlerName].isActive()})()&&!T9(k)){const Jt=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"),Jt!==Q.zoom&&this._map._update(!0)}if(Q._isCameraConstrained&&K._stop({keepGesture:"always"}),!T9(k))return void this._fireEvents(T,B,!0);let{panDelta:he,zoomDelta:we,bearingDelta:Me,pitchDelta:Re,around:Ze,aroundCoord:Xe,pinchAround:dt}=k;Q._isCameraConstrained&&(we>0&&(we=0),Q._isCameraConstrained=!1),dt!==void 0&&(Ze=dt),(we||(Jt=>T[Jt]&&!this._eventsInProgress[Jt])("drag"))&&Ze&&(this._dragOrigin=oe(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(he)if(Q.projection.name==="mercator"){const Jt=this._trackingEllipsoid.projectRay(Q.screenPointToMercatorRay(Ze).dir),Lt=this._trackingEllipsoid.projectRay(Q.screenPointToMercatorRay(Ze.sub(he)).dir);_t[0]=Lt[0]-Jt[0],_t[1]=Lt[1]-Jt[1]}else{const Jt=Q.pointCoordinate(Ze);if(Q.projection.name==="globe"){he=he.rotate(-Q.angle);const Lt=Q._pixelsPerMercatorPixel/Q.worldSize;_t[0]=-he.x*o.eF(o.bs(Jt.y))*Lt,_t[1]=-he.y*o.eF(Q.center.lat)*Lt}else{const Lt=Q.pointCoordinate(Ze.sub(he));Jt&&Lt&&(_t[0]=Lt.x-Jt.x,_t[1]=Lt.y-Jt.y)}}const bt=Q.zoom,Mt=[0,0,0];if(we){const Jt=oe(Xe||Q.pointCoordinate3D(Ze)),Lt={dir:o.c9([],o.cv([],Jt,Q._camera.position))};if(Lt.dir[2]<0){const ps=Q.zoomDeltaToMovement(Jt,we);o.dV(Mt,Lt.dir,ps)}}const ss=o.dW(_t,_t,Mt);Q._translateCameraConstrained(ss),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=E9(this._eventsInProgress),Q=E9(k),oe={};for(const Re in k){const{originalEvent:Ze}=k[Re];this._eventsInProgress[Re]||(oe[`${Re}start`]=Ze),this._eventsInProgress[Re]=k[Re]}!K&&Q&&this._fireEvent("movestart",Q.originalEvent);for(const Re in oe)this._fireEvent(Re,oe[Re]);Q&&this._fireEvent("move",Q.originalEvent);for(const Re in k){const{originalEvent:Ze}=k[Re];this._fireEvent(Re,Ze)}const he={};let we;for(const Re in this._eventsInProgress){const{handlerName:Ze,originalEvent:Xe}=this._eventsInProgress[Re];this._handlersById[Ze].isActive()||(delete this._eventsInProgress[Re],we=T[Ze]||Xe,he[`${Re}end`]=we)}for(const Re in he)this._fireEvent(Re,he[Re]);const Me=E9(this._eventsInProgress);if(B&&(K||Q)&&!Me){this._updatingCamera=!0;const Re=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Ze=Xe=>Xe!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new LFe("renderFrame",{timeStamp:k})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const M9="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class FFe 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,oe){const he=k.clone(),we=this._extendCameraOptions(oe);he.bearing=K,he.pitch=Q;const Me=o.cZ.convert(T),Re=o.cZ.convert(B),Ze=.5*(Me.lat+Re.lat),Xe=.5*(Me.lng+Re.lng),dt=o.eJ(Ze,Xe),_t=o.c9([],dt),bt=o.c9([],o.eK([],_t,[0,1,0])),Mt=o.eK([],bt,_t),ss=[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],Jt=[dt,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,Xe),o.eJ(Re.lat,Xe)];let Lt=o.eL.fromPoints(Jt.map(qr=>[o.dY(bt,qr),o.dY(Mt,qr),o.dY(_t,qr)]));const ps=o.bI([],Lt.center,ss);o.eM(ps)===0&&o.eN(ps,0,0,1),o.c9(ps,ps),o.dV(ps,ps,o.cy),he.center=o.eO(ps);const Gs=he.getWorldToCameraMatrix(),Ls=o.aP(new Float64Array(16),Gs);Lt=o.eL.applyTransform(Lt,o.X([],Gs,ss));const sn=this._extendAABB(Lt,he,we,K);if(!sn)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Lt=sn,o.bI(ps,ps,Gs);const Bs=.5*(Lt.max[2]-Lt.min[2]),nn=this._minimumAABBFrustumDistance(he,Lt),yn=o.dV([],[0,0,1],Bs),Tn=o.dW(yn,ps,yn),Gn=nn+(he.pitch===0?0:o.eP(ps,Tn)),zn=he.globeCenterInViewSpace,Dn=o.cv([],ps,[zn[0],zn[1],zn[2]]);o.c9(Dn,Dn),o.dV(Dn,Dn,Gn);const Mr=o.dW([],ps,Dn);o.bI(Mr,Mr,Ls);const kn=o.bk/o.cy,pr=o.es(Mr),ta=o.c4(Math.max(pr*kn-o.bk,Number.EPSILON),0),ka=Math.min(he.zoomFromMercatorZAdjusted(ta),we.maxZoom);return ka>.5*(o.ef+o.b2)?(he.setProjection({name:"mercator"}),he.zoom=ka,this._cameraForBounds(he,T,B,K,Q,oe)):{center:he.center,zoom:ka,bearing:K,pitch:Q}}_extendAABB(k,T,B,K){const Q=.5*((B.padding.left||0)+(B.padding.right||0)),oe=.5*((B.padding.top||0)+(B.padding.bottom||0)),he=oe,we=Q,Me=Q,Re=oe,Ze=T.width-(we+Me),Xe=T.height-(he+Re),dt=o.cv([],k.max,k.min),_t=Math.min(Ze/dt[0],Xe/dt[1]),bt=Math.min(T.scaleZoom(T.scale*_t),B.maxZoom);if(isNaN(bt))return null;const Mt=T.scale/T.zoomScale(bt),ss=new o.eL([k.min[0]-we*Mt,k.min[1]-Re*Mt,k.min[2]],[k.max[0]+Me*Mt,k.max[1]+he*Mt,k.max[2]]),Jt=(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 ss.center[0]-=Jt.x*Mt,ss.center[1]+=Jt.y*Mt,ss}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,oe){if(k.projection.name==="globe")return this._cameraForBoundsOnGlobe(k,T,B,K,Q,oe);const he=k.clone(),we=this._extendCameraOptions(oe);he.bearing=K,he.pitch=Q;const Me=o.cZ.convert(T),Re=o.cZ.convert(B),Ze=new o.cZ(Me.lng,Re.lat),Xe=new o.cZ(Re.lng,Me.lat),dt=he.project(Me),_t=he.project(Re),bt=this.queryTerrainElevation(Me),Mt=this.queryTerrainElevation(Re),ss=this.queryTerrainElevation(Ze),Jt=this.queryTerrainElevation(Xe),Lt=[[dt.x,dt.y,Math.min(bt||0,Mt||0,ss||0,Jt||0)],[_t.x,_t.y,Math.max(bt||0,Mt||0,ss||0,Jt||0)]];let ps=o.eL.fromPoints(Lt);const Gs=he.getWorldToCameraMatrix(),Ls=o.aP(new Float64Array(16),Gs);ps=o.eL.applyTransform(ps,Gs);const sn=this._extendAABB(ps,he,we,K);if(!sn)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");ps=sn;const Bs=.5*o.cv([],ps.max,ps.min)[2],nn=this._minimumAABBFrustumDistance(he,ps),yn=[0,0,1,0];o.c6(yn,yn,Gs),o.eQ(yn,yn);const Tn=o.dV([],yn,nn+Bs),Gn=o.dW([],ps.center,Tn);o.bI(ps.center,ps.center,Ls),o.bI(Gn,Gn,Ls);const zn=he.unproject(new o.P(ps.center[0],ps.center[1])),Dn=o.eR(he.projection,zn),Mr=Math.pow(2,Dn),kn=Math.min(he._zoomFromMercatorZ(Gn[2]*he.pixelsPerMeter*Mr/he.worldSize),we.maxZoom);return he.mercatorFromTransition&&kn<.5*(o.ef+o.b2)?(he.setProjection({name:"globe"}),he.zoom=kn,this._cameraForBounds(he,T,B,K,Q,oe)):{center:zn,zoom:kn,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 oe=o.P.convert(k),he=o.P.convert(T),we=new o.P(Math.min(oe.x,he.x),Math.min(oe.y,he.y)),Me=new o.P(Math.max(oe.x,he.x),Math.max(oe.y,he.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(oe,he))return this;const Re=this.transform.pointLocation3D(we),Ze=this.transform.pointLocation3D(Me),Xe=this.transform.pointLocation3D(new o.P(we.x,Me.y)),dt=this.transform.pointLocation3D(new o.P(Me.x,we.y)),_t=[Math.min(Re.lng,Ze.lng,Xe.lng,dt.lng),Math.min(Re.lat,Ze.lat,Xe.lat,dt.lat)],bt=[Math.max(Re.lng,Ze.lng,Xe.lng,dt.lng),Math.max(Re.lat,Ze.lat,Xe.lat,dt.lat)],Mt=K&&K.pitch?K.pitch:this.getPitch(),ss=this._cameraForBounds(this.transform,_t,bt,B,Mt,K);return this._fitInternal(ss,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,oe=!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&&(oe=!0,B.pitch=+k.pitch),"fov"in k&&(B.fov=+k.fov);const he=typeof k.padding=="number"?this._extendPadding(k.padding):k.padding;if(k.padding!=null&&!B.isPaddingEqual(he))if(k.retainPadding===!1){const we=B.clone();we.padding=he,B.setLocationAtPoint(B.center,we.centerPoint)}else B.padding=he;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)),oe&&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(M9),this.transform.getFreeCameraOptions()}setFreeCameraOptions(k,T){const B=this.transform;if(!B.projection.supportsFreeCamera)return o.w(M9),this;this.stop();const K=B.zoom,Q=B.pitch,oe=B.bearing;B.setFreeCameraOptions(k);const he=K!==B.zoom,we=Q!==B.pitch,Me=oe!==B.bearing;return this.fire(new o.h("movestart",T)).fire(new o.h("move",T)),he&&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(),oe=this.getPitch(),he=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:oe,Xe="fov"in k?+k.fov:we,dt=this._extendPadding(k.padding),_t=o.P.convert(k.offset);let bt,Mt,ss;if(B.projection.name==="globe"){const zn=o.bT.fromLngLat(B.center),Dn=_t.rotate(-B.angle);zn.x+=Dn.x/B.worldSize,zn.y+=Dn.y/B.worldSize;const Mr=zn.toLngLat(),kn=o.cZ.convert(k.center||Mr);this._normalizeCenter(kn),bt=B.centerPoint.add(Dn),Mt=new o.P(zn.x,zn.y).mult(B.worldSize),ss=new o.P(o.a7(kn.lng),o.a8(kn.lat)).mult(B.worldSize).sub(Mt)}else{bt=B.centerPoint.add(_t);const zn=B.pointLocation(bt),Dn=o.cZ.convert(k.center||zn);this._normalizeCenter(Dn),Mt=B.project(zn),ss=B.project(Dn).sub(Mt)}const Jt=B.zoomScale(Me-K);let Lt,ps;k.around&&(Lt=o.cZ.convert(k.around),ps=B.locationPoint(Lt));const Gs=this._zooming||Me!==K,Ls=this._rotating||Q!==Re,sn=this._pitching||Ze!==oe,Bs=Xe!==we,nn=!B.isPaddingEqual(dt),yn=k.retainPadding===!1?B.clone():B,Tn=zn=>Dn=>{if(Gs&&(zn.zoom=o.am(K,Me,Dn)),Ls&&(zn.bearing=o.am(Q,Re,Dn)),sn&&(zn.pitch=o.am(oe,Ze,Dn)),Bs&&(zn.fov=o.am(we,Xe,Dn)),nn&&(yn.interpolatePadding(he,dt,Dn),bt=yn.centerPoint.add(_t)),Lt)zn.setLocationAtPoint(Lt,ps);else{const Mr=zn.zoomScale(zn.zoom-K),kn=Me>K?Math.min(2,Jt):Math.max(.5,Jt),pr=Math.pow(kn,1-Dn),ta=zn.unproject(Mt.add(ss.mult(Dn*pr)).mult(Mr));zn.setLocationAtPoint(zn.renderWorldCopies?ta.wrap():ta,bt)}return k.preloadOnly||this._fireMoveEvents(T),zn};if(k.preloadOnly){const zn=this._emulate(Tn,k.duration,B);return this._preloadTiles(zn),this}const Gn={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Gs,this._rotating=Ls,this._pitching=sn,this._padding=nn,this._easeId=k.easeId,this._prepareEase(T,k.noMoveStart,Gn),this._ease(Tn(B),zn=>{B.cameraElevationReference==="sea"&&B.recenterOnTerrain(),this._afterEase(T,zn)},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 Gr=o.cB(k,["center","zoom","bearing","pitch","fov","around","padding","retainPadding"]);return this.jumpTo(Gr,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(),oe=this.getPitch(),he=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:oe,Xe="fov"in k?+k.fov:we,dt=Xe!==we,_t=this._extendPadding(k.padding),bt=B.zoomScale(Me-K),Mt=o.P.convert(k.offset);let ss=B.centerPoint.add(Mt);const Jt=B.pointLocation(ss),Lt=o.cZ.convert(k.center||Jt);this._normalizeCenter(Lt);const ps=B.project(Jt),Gs=B.project(Lt).sub(ps);let Ls=k.curve;const sn=Math.max(B.width,B.height),Bs=sn/bt,nn=Gs.mag();if("minZoom"in k){const Gr=o.b1(Math.min(k.minZoom,K,Me),B.minZoom,B.maxZoom),Sr=sn/B.zoomScale(Gr-K);Ls=Math.sqrt(Sr/nn*2)}const yn=Ls*Ls;function Tn(Gr){const Sr=(Bs*Bs-sn*sn+(Gr?-1:1)*yn*yn*nn*nn)/(2*(Gr?Bs:sn)*yn*nn);return Math.log(Math.sqrt(Sr*Sr+1)-Sr)}function Gn(Gr){return(Math.exp(Gr)-Math.exp(-Gr))/2}function zn(Gr){return(Math.exp(Gr)+Math.exp(-Gr))/2}const Dn=Tn(0);let Mr=function(Gr){return zn(Dn)/zn(Dn+Ls*Gr)},kn=function(Gr){return sn*((zn(Dn)*(Gn(Sr=Dn+Ls*Gr)/zn(Sr))-Gn(Dn))/yn)/nn;var Sr},pr=(Tn(1)-Dn)/Ls;if(Math.abs(nn)<1e-6||!isFinite(pr)){if(Math.abs(sn-Bs)<1e-6)return this.easeTo(k,T);const Gr=Bsk.maxDuration&&(k.duration=0);const ta=Q!==Re,ka=Ze!==oe,qr=!B.isPaddingEqual(_t),Jr=k.retainPadding===!1?B.clone():B,si=Gr=>Sr=>{const Hr=Sr*pr,Ha=1/Mr(Hr);Gr.zoom=Sr===1?Me:K+Gr.scaleZoom(Ha),ta&&(Gr.bearing=o.am(Q,Re,Sr)),ka&&(Gr.pitch=o.am(oe,Ze,Sr)),dt&&(Gr.fov=o.am(we,Xe,Sr)),qr&&(Jr.interpolatePadding(he,_t,Sr),ss=Jr.centerPoint.add(Mt));const $r=Sr===1?Lt:Gr.unproject(ps.add(Gs.mult(kn(Hr))).mult(Ha));return Gr.setLocationAtPoint(Gr.renderWorldCopies?$r.wrap():$r,ss),Gr._updateCameraOnTerrain(),k.preloadOnly||this._fireMoveEvents(T),Gr};if(k.preloadOnly){const Gr=this._emulate(si,k.duration,B);return this._preloadTiles(Gr),this}return this._zooming=!0,this._rotating=ta,this._pitching=ka,this._padding=qr,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=[],oe=k(B.clone());for(let he=0;he<=K;he++){const we=oe(he/K);Q.push(we.clone())}return Q}_preloadTiles(k,T){}}const yoe=/^(https?:|mailto:)/i;class XT{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,oe)=>(Q.value&&(K+=`${Q.key}=${Q.value}${oeK.length-Q.length),k=k.filter((K,Q)=>{for(let oe=Q+1;oefunction(Q){const oe=new DOMParser().parseFromString(Q,"text/html");return Array.from(oe.body.querySelectorAll("*")).reverse().forEach(he=>{const we=he.textContent||"";if(he.tagName!=="A")return void he.replaceWith(...he.childNodes);const Me=he.getAttribute("href");if(!Me||!yoe.test(Me))return void he.replaceWith(oe.createTextNode(we));const Re=oe.createElement("a");Re.href=Me,Re.textContent=we,Re.rel="noopener nofollow";const Ze=he.getAttribute("class");Ze&&(Re.className=Ze),he.replaceWith(Re)}),oe.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 voe{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 Ff{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 QT{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 boe={"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 $6 extends o.h{constructor(k,T,B,K){const{point:Q,lngLat:oe,originalEvent:he,target:we}=k;super(k.type,{point:Q,lngLat:oe,originalEvent:he,target:we}),this.preventDefault=()=>{k.preventDefault()},this.id=T,this.interaction=B,this.feature=K}}class P9{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 oe=!1;const he=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 Xe of Ze){if(Yd(Xe,we,he,Me))continue;const dt=new o.dP(we,Xe),_t=rg(Xe,we,Me);Q&&dt.id!==void 0&&(dt.state=this.map.getFeatureState(dt));const bt=B?this.prevHoveredFeatures.get(_t):null,Mt=new $6(k,Me,Re,dt),ss=bt?bt.stop:Re.handler(Mt);if(B&&this.hoveredFeatures.set(_t,{feature:we,stop:ss}),ss!==!1){oe=!0;break}}if(oe)break}}if(oe)break}if(!oe)for(const[we,Me]of K){const{handler:Re,target:Ze}=Me;if(!Ze&&Re(new $6(k,we,Me,null))!==!1)break}}}function U6(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 _oe=/matrix.*\((.+)\)/,woe={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"},q6={showCompass:!0,showZoom:!0,visualizePitch:!1};class pY{constructor(k,T,B=!1){this._clickTolerance=10,this.element=T,this.mouseRotate=new O6({clickTolerance:k.dragRotate._mouseRotate._clickTolerance}),this.map=k,B&&(this.mousePitch=new S9({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 oe=this.mousePitch.mousemoveWindow(k,T),he=oe&&oe.pitchDelta;he&&B.setPitch(B.getPitch()+he)}}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 V6={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%)"},xY=/\s+/,pf={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class Vk 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:oe=!1,clickTolerance:he=0,rotation:we=pf.rotation,rotationAlignment:Me=pf.rotationAlignment,pitchAlignment:Re=pf.pitchAlignment,occludedOpacity:Ze=pf.occludedOpacity,altitude:Xe=pf.altitude}=k||{};this._anchor=B,this._color=K,this._scale=Q,this._draggable=oe,this._clickTolerance=he,this._rotation=we,this._rotationAlignment=Me,this._pitchAlignment=Re,this._occludedOpacity=Ze,this._altitude=Xe,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 dt=this._element.classList;for(const _t in V6)dt.remove(`mapboxgl-marker-anchor-${_t}`);dt.add(`mapboxgl-marker-anchor-${this._anchor}`),k&&k.className&&dt.add(...k.className.trim().split(xY)),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||pf.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) ${V6[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)),oe=Math.abs(Q.x)+Math.abs(Q.y);if(oe===0)return"";const he=K/oe;return`rotateX(${-Q.y*he}deg) rotateY(${Q.x*he}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),oe=T.project(new o.cZ(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(Q);B=o.fa(Math.atan2(oe.y,oe.x))-90}else B=-T.getBearing();else if(K==="horizon"){const Q=o.an(4,6,T.getZoom()),oe=o.fc(T.transform);oe.y+=Q*T.transform.height;const he=k.sub(oe),we=o.fa(Math.atan2(he.y,he.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=gY(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}`,q_=["waiting","active","active-error","background","background-error"].map(Vv),sj={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0,showUserHeading:!1,showButton:!0,followUserLocation:!0},R3={maxWidth:100,unit:"metric"},JT={kilometer:"km",meter:"m",mile:"mi",foot:"ft","nautical-mile":"nm"},vY=/\s+/,Il={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",altitude:0},V_=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function H6(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 Xd=typeof document<"u"?document.currentScript:null;return o.fd(Xd&&Xd.src&&o.fe(Xd.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 FFe{constructor(L){o.eT.mark(o.eU.create);const k=L;if((L={...woe,...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 Ff,this._domRenderTaskQueue=new Ff,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.aw(),this._locale={...boe,...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 QT(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 DFe(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 U_(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 XT({customAttribution:L.customAttribution})),this._logoControl=new voe,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 P9(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 oe=k.filter(he=>this.getLayer(he));Q=oe.length?this.queryRenderedFeatures(K,{layers:oe}):[]}else Q=this.queryRenderedFeatures(K,{target:k});return Q};if(L==="mouseenter"||L==="mouseover"){let K=!1;return{listener:T,targets:k,delegates:{mousemove:oe=>{const he=B(oe.point);he.length?K||(K=!0,T.call(this,new Sl(L,this,oe.originalEvent,{features:he}))):K=!1},mouseout:()=>{K=!1}}}}if(L==="mouseleave"||L==="mouseout"){let K=!1;return{listener:T,targets:k,delegates:{mousemove:he=>{B(he.point).length?K=!0:K&&(K=!1,T.call(this,new Sl(L,this,he.originalEvent)))},mouseout:he=>{K&&(K=!1,T.call(this,new Sl(L,this,he.originalEvent)))}}}}{const K=Q=>{const oe=B(Q.point);oe.length&&(Q.features=oe,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 dp(this,T).load(L),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new dp(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:oe}={}){this._lazyInitEmptyStyle();const he=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(he,{data:new o.b({width:we,height:Me},Re),pixelRatio:T,stretchX:K,stretchY:Q,content:oe,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(he,{data:new o.b({width:we,height:Me},new Uint8Array(Re.data)),pixelRatio:T,stretchX:K,stretchY:Q,content:oe,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:oe,data:he}=K;if(Q===void 0||oe===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)||oe!==(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}, ${oe}) 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:oe},new Uint8Array(he)),B.usvg=!1,B.icon=void 0,Me=!0):B.data.replace(he,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 oe=window.getComputedStyle(Q).transform;oe&&oe!=="none"&&(T=oe.match(_oe)[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 Hh(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 oe=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),oe=this._updateAverageElevation(B),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):oe=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 he=this._sourcesDirty||this._styleDirty||this._placementDirty||oe;if(he||this._repaint)this.triggerRepaint();else{const we=this.idle();if(we&&(oe=this._updateAverageElevation(B,!0)),oe)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||he||(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 oe=Math.abs(K-Q);if(oe>1){if(this._isInitialLoad||B)return this._averageElevation.jumpTo(Q),T(Q);this._averageElevation.easeTo(Q,L,300)}else if(oe>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 voe&&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 oe=new Uint8Array(T.drawingBufferWidth*T.drawingBufferHeight*4);return T.readPixels(0,0,T.drawingBufferWidth,T.drawingBufferHeight,T.RGBA,T.UNSIGNED_BYTE,oe),oe}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&&Mh(),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&&Mh(),this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(L){this._showCollisionBoxes!==L&&(this._showCollisionBoxes=L,L&&Mh(),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={...q6,...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 pY(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,...sj,...L},o.aW(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=uh(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(...q_);for(const T of yY[L])k.add(Vv(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(Vv("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??sj.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??sj.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??sj.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??sj.fitBoundsOptions,this}setShowUserLocation(L){return this.options.showUserLocation=L??sj.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 Vk({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=g("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Vk({element:this._circleElement,pitchAlignment:"map"})}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),this._removeDeviceOrientationListener(),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove(Vv("waiting")),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:XT,ScaleControl:class{constructor(L={}){this.options={...R3,...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]),oe=K.distanceTo(Q);if(this.options.unit==="imperial"){const he=3.2808*oe;he>5280?this._setScale(L,he/5280,"mile"):this._setScale(L,he,"foot")}else this.options.unit==="nautical"?this._setScale(L,oe/1852,"nautical-mile"):oe>=1e3?this._setScale(L,oe/1e3,"kilometer"):this._setScale(L,oe,"meter")}_setScale(L,k,T){this._map._requestDomTask(()=>{const B=function(Q){const oe=Math.pow(10,`${Math.floor(Q)}`.length-1);let he=Q/oe;return he=he>=10?10:he>=5?5:he>=3?3:he>=2?2:he>=1?1:function(we){const Me=Math.pow(10,Math.ceil(-Math.log(we)/Math.LN10));return Math.round(we*Me)/Me}(he),oe*he}(k),K=B/k;this._container.innerHTML=T!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:T}).format(B):`${B} ${JT[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,oe;K<=5?(Q=0,oe=K-1):this._visibleFloorStart===0?(Q=0,oe=3):this._visibleFloorStart>=K-3?(Q=K-3-1,oe=K-1):(Q=this._visibleFloorStart,oe=this._visibleFloorStart+3-1),Boe&&(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(oe=>this._createFloorButton(oe));const B=this._visibleFloorStart===0,K=this._visibleFloorStart>=T-3;if(B)this._createFloorButton(k[0]);else{const oe=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);g("span","mapboxgl-ctrl-icon",oe).setAttribute("aria-hidden","true"),this._container.appendChild(oe)}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(oe=>this._createFloorButton(oe)),K)this._createFloorButton(k[T-1]);else{const oe=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);g("span","mapboxgl-ctrl-icon",oe).setAttribute("aria-hidden","true"),this._container.appendChild(oe)}}_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(Il),L),this._altitude=this.options.altitude,o.aW(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(L&&L.className?L.className.trim().split(vY):[])}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,oe=B.xk.transform.width-K/2;if(B.y+Lk.transform.height-Q){if(oe)return"bottom-left";if(he)return"bottom-right"}return oe?"left":he?"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=gY(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=H6(this.options.offset),oe=this._anchor=this._getAnchor(Q.y),he=H6(this.options.offset,oe),we=K.add(he).round();k._requestDomTask(()=>{this._container&&oe&&(this._container.style.transform=`${V6[oe]} 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(V_);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:Vk,Style:dp,LngLat:o.cZ,LngLatBounds:o.eI,Point:o.P,MercatorCoordinate:o.bT,FreeCameraOptions:o.ff,Evented:o.E,config:o.eS,prewarm:function(){cu().acquire(js)},clearPrewarmedResources:function(){const L=ch;L&&(L.isPreloaded()&&L.numActive()===1?(L.release(js),ch=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 Ts.workerCount},set workerCount(L){(function(k){Ts.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 $t.workerUrl},set workerUrl(L){$t.workerUrl=L},get workerClass(){return $t.workerClass},set workerClass(L){$t.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})})(M7t);var hDs=M7t.exports;const _u=ru(hDs),Gyt={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},Wyt={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 mDs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function fDs({listings:s,isLoading:t}){const n=Zn(),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;_u.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((v,y)=>v+y.longitude,0)/h.length,x=h.reduce((v,y)=>v+y.latitude,0)/h.length;m=[g,x],f=h.length===1?12:10}return a.current=new _u.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:f,center:m}),a.current.addControl(new _u.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,A,E;const f=Gyt[m.status]||"#10B981",g=((S=m.photos)==null?void 0:S.find(I=>I.is_primary))||((A=m.photos)==null?void 0:A[0]),v=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${m.slug||m.id}`:`/public/listing/${m.slug||m.id}`,y=document.createElement("div");y.className="cursor-pointer",y.innerHTML=`
`;const b=new _u.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${g!=null&&g.photo_url?``:""}
${mDs(m.price)}
${m.property_address||""}
${m.city}, ${m.state}
${Wyt[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 _u.Marker(y).setLngLat([m.longitude,m.latitude]).setPopup(b).addTo(a.current);i.current.push(w)}),h.length>1){const m=new _u.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(xn,{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(Gyt).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:Wyt[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const o7e={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},pDs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},y$="#0d0d0d",Kyt="#1a1a1a",Mu="#c9a84c",vM="#f0d78c";function I7t(){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}=YRs(),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:v}=KRs({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}),y=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.")),A=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(ve=>ve.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,Z,X]=V.split("-").map(Number),ae=Math.floor(Date.UTC(G,Z-1,X)/864e5),le=W.length>0?W[ae%W.length]:void 0,re=O.filter(ve=>!le||ve.id!==le.id),te=Array.from(new Set(O.map(ve=>ve.city).filter(Boolean))).slice(0,8),J=O.filter(ve=>(ve.price||0)>=1e6).length,ce=U.length;return{featured:le,restListings:re,luxeCount:J,cities:te,activeCount:ce}},[x]);return e.jsxs(e.Fragment,{children:[e.jsxs(Dl,{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:y$,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: ${Mu}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${Mu}, 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(br,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:NG,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(br,{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 ${Mu}`,color:Mu},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 ${Mu}`,color:Mu},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx(mr,{className:"w-5 h-5"}):e.jsx(TE,{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(br,{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 ${Mu}`,color:Mu},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:uDs,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:Mu}}),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:vM},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 ${Mu}`,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:Mu}}),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(YI,{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:Mu,color:y$},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:Mu},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(ui,{className:"h-4 w-4 shrink-0",style:{color:Mu}}),O.type==="neighborhood"&&e.jsx(wi,{className:"h-4 w-4 shrink-0",style:{color:Mu}}),O.type==="zip"&&e.jsx(va,{className:"h-4 w-4 shrink-0",style:{color:Mu}}),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(o7e).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(pDs).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(mr,{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:vM},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(wl,{className:"h-4 w-4 animate-bounce"})]})]})]}),R.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:Kyt,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:Mu}})]},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(wn,{className:"h-4 w-4",style:{color:Mu}}),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:vM},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(br,{to:A(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:Mu,color:y$},children:o7e[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(ui,{className:"h-3.5 w-3.5",style:{color:Mu}}),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:vM},children:y(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(n2,{className:"h-4 w-4",style:{color:Mu}}),E.bedrooms," bd"]}),E.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(C0,{className:"h-4 w-4",style:{color:Mu}}),E.bathrooms," ba"]}),E.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(w_,{className:"h-4 w-4",style:{color:Mu}}),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:Mu},children:["View Residence ",e.jsx(Qa,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:Kyt},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:Mu}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:Mu}})]}),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:vM},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."})]}),v?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(xn,{className:"aspect-[4/5] bg-white/5"}),e.jsx(xn,{className:"h-6 w-32 bg-white/5"}),e.jsx(xn,{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,Z,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(br,{to:A(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:Mu,border:`1px solid ${Mu}`},children:o7e[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(ui,{className:"h-3 w-3",style:{color:Mu}}),O.city,O.state?`, ${O.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:vM},children:y(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(wi,{className:"h-3 w-3"}),O.agent.name,(((Z=O.agent.brokerage)==null?void 0:Z.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 ${Mu}`},children:e.jsx(va,{className:"h-8 w-8",style:{color:Mu}})}),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:Mu,color:y$},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:Mu}}),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:vM},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(fDs,{listings:x,isLoading:v})})]})}),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%, ${y$} 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:Mu}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:Mu}})]}),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:vM},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:Mu,color:y$},children:["Explore LevelUp",e.jsx(Qa,{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:NG,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(CRs,{}),e.jsx(ARs,{})]})}const gDs=j.lazy(()=>ri(()=>import("./PublicHomeValue-dOO53UR7.js"),[]));function xDs(){const s=qu(),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(I7t,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(j.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(gDs,{})}):r.startsWith("public/")?null:e.jsx(Wtt,{slugOverride:r})}const yDs=j.lazy(()=>ri(()=>import("./CommercialMarketplace-ioOS8W47.js"),[]));function vDs(){const t=qu().pathname.slice(1);return t?t.startsWith("public/")?null:e.jsx(Wtt,{slugOverride:t}):e.jsx(j.Suspense,{fallback:e.jsx("div",{className:"min-h-screen bg-[#0a0d12]"}),children:e.jsx(yDs,{})})}function $Le({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 L7t=s=>st({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}),bDs=()=>st({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}}),_Ds=s=>st({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}),R7t=()=>{const s=Zt();return mt({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"]}),ne.success("Agent card created")},onError:t=>ne.error(t.message)})},D7t=()=>{const s=Zt();return mt({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"]}),ne.success("Agent card updated")},onError:t=>ne.error(t.message)})},wu=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},F7t=s=>st({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 ULe({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,v]=j.useState(!1),y=async b=>{if(b.preventDefault(),!i.trim()){ne.error("Please enter your name");return}v(!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}),wu(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)),ne.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{ne.error("Something went wrong. Please try again.")}finally{v(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(Us,{children:[e.jsx($s,{children:r==="booking"?"Book a Call":r==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(Er,{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:y,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 jDs=s=>st({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}),NDs=s=>st({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}),kDs=()=>{const s=Zt();return mt({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]}),ne.success("Block added")},onError:t=>ne.error(t.message)})},SDs=()=>{const s=Zt();return mt({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"]}),ne.success("Block updated")},onError:t=>ne.error(t.message)})},CDs=()=>{const s=Zt();return mt({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"]}),ne.success("Block removed")},onError:t=>ne.error(t.message)})};function ADs(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 EDs(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 TDs={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 MDs({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=EDs(n.video_url),i=r||!!a,l=r?ADs(n.video_url):a||n.video_url;return e.jsx("div",{className:TDs[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 PDs={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 IDs({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=j.useState(0);if(r.length===0)return null;const l=PDs[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(d2,{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(kd,{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 LDs={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 RDs({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=LDs[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const DDs={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 FDs({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=DDs[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:()=>wu(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(Ir,{className:`h-4 w-4 ${i.icon}`})]},o))})}const JHe={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 ODs({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 zDs={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 BDs({block:s,cardId:t,variant:n}){const a=s.config.platforms||[],i=zDs[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=JHe[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>wu(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(ODs,{path:c.icon,color:c.color})},o)})})]})}function qLe({cardId:s,variant:t}){const{data:n}=jDs(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(MDs,{block:l,variant:t},l.id);case"testimonials":return e.jsx(IDs,{block:l,variant:t},l.id);case"specialties":return e.jsx(RDs,{block:l,variant:t},l.id);case"custom_links":return e.jsx(FDs,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(BDs,{block:i,cardId:s,variant:t})]})}async function $Ds(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 UDs(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 VLe(s){const{first:t,last:n}=UDs(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 $Ds(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),ne.success("Contact saved!")}function qDs({card:s}){var y;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((y=s.profile)==null?void 0:y.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,w)=>{wu(s.id,"button_click",b),w()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:ne.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:ne.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:ne.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),wu(s.id,"button_click","book"))},m=()=>{var b,w;wu(s.id,"contact_saved"),VLe({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()=>{wu(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),ne.success("Link copied!")},g=()=>{a("referral"),n(!0),wu(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),wu(s.id,"button_click","connect")},v={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(Ii,{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(no,{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(pn,{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(Ea,{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(ei,{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($Le,{card:s,variant:"standard"}),e.jsx(qLe,{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(ji,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs($,{variant:"ghost",onClick:()=>{wu(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(ei,{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(Yn,{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(lc,{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(Hd,{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:()=>wu(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:v[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(ULe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function VDs({card:s}){var y;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((y=s.profile)==null?void 0:y.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,w)=>{wu(s.id,"button_click",b),w()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:ne.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:ne.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:ne.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),wu(s.id,"button_click","book"))},m=()=>{var b,w;wu(s.id,"contact_saved"),VLe({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()=>{wu(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),ne.success("Link copied!")},g=()=>{a("referral"),n(!0),wu(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),wu(s.id,"button_click","connect")},v={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(Ii,{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:no,label:"Text",handler:d},{icon:pn,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(Ea,{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(ei,{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($Le,{card:s,variant:"luxury"}),e.jsx(qLe,{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(ji,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{wu(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(ei,{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(Yn,{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(lc,{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(Hd,{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:()=>wu(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:v[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(ULe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function HDs({card:s}){var w,S,A,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:((A=s.bold_theme_colors)==null?void 0:A.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)=>{wu(s.id,"button_click",I),P()},u=()=>d("call",()=>{var I;(I=s.profile)!=null&&I.phone?window.location.href=`tel:${s.profile.phone}`:ne.error("Phone number not available")}),h=()=>d("text",()=>{var I;(I=s.profile)!=null&&I.phone?window.location.href=`sms:${s.profile.phone}`:ne.error("Phone number not available")}),m=()=>d("email",()=>{var I;(I=s.profile)!=null&&I.email?window.location.href=`mailto:${s.profile.email}`:ne.error("Email not available")}),f=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),wu(s.id,"button_click","book"))},g=()=>{var I,P;wu(s.id,"contact_saved"),VLe({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()=>{wu(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),ne.success("Link copied!")},v=()=>{a("referral"),n(!0),wu(s.id,"button_click","refer")},y=()=>{a("connect"),n(!0),wu(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(Ii,{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:no,label:"Text",handler:h},{icon:pn,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(Ea,{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(ei,{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($Le,{card:s,variant:"bold"}),e.jsx(qLe,{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(ji,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{wu(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(ei,{className:"h-4 w-4",style:{color:o.accent}})," Leave a Review"]}),s.show_refer_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(Yn,{className:"h-4 w-4",style:{color:o.accent}})," Refer a 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(lc,{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(Hd,{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:()=>wu(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(ULe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function GDs({card:s}){var y;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((y=s.profile)==null?void 0:y.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,w)=>{wu(s.id,"button_click",b),w()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:ne.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:ne.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:ne.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),wu(s.id,"button_click","book"))},m=()=>{var b,w;wu(s.id,"contact_saved"),VLe({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()=>{wu(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),ne.success("Link copied!")},g=()=>{a("referral"),n(!0),wu(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),wu(s.id,"button_click","connect")},v={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(Ii,{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:no,label:"Text",handler:d},{icon:pn,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(Ea,{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(ei,{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($Le,{card:s,variant:"classic"}),e.jsx(qLe,{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(ji,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{wu(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(ei,{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(Yn,{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(lc,{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(Hd,{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:()=>wu(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:v[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(ULe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function Ktt({card:s}){switch(s.theme){case"luxury":return e.jsx(VDs,{card:s});case"bold":return e.jsx(HDs,{card:s});case"classic":return e.jsx(GDs,{card:s});case"standard":default:return e.jsx(qDs,{card:s})}}function WDs(){const s=qu();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(KDs,{slug:t})}function KDs({slug:s}){return e.jsx(YDs,{slug:s})}function YDs({slug:s}){var i;const{data:t,isLoading:n,error:r}=L7t(s);if(j.useEffect(()=>{t!=null&&t.id&&wu(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(xn,{className:"h-28 w-28 rounded-full"}),e.jsx(xn,{className:"h-6 w-48"}),e.jsx(xn,{className:"h-4 w-36"})]}),e.jsx(xn,{className:"h-12 w-full"}),e.jsx(xn,{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(Dl,{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(Ktt,{card:t})]})}function O7t({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(""),[v,y]=j.useState(!1),[b,w]=j.useState(!1),S=async A=>{if(A.preventDefault(),!l.trim()){ne.error("Please enter your name");return}y(!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{ne.error("Something went wrong. Please try again.")}finally{y(!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(ma,{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:A=>o(A.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:A=>h(A.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:A=>d(A.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:A=>x(A.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:v,children:v?"Sending...":t})]})}function ZDs(){const s=qu();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(XDs,{shareToken:t})}function XDs({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:v}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(v||!x){c(!0),a(!1);return}const{data:y}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",x.owner_user_id).single();let b;if(y!=null&&y.brokerage_id){const{data:S}=await q.from("brokerages").select("name").eq("id",y.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:y==null?void 0:y.name,owner_email:y==null?void 0:y.email,owner_phone:y==null?void 0:y.phone,owner_avatar:y==null?void 0:y.avatar_url,owner_title:(y==null?void 0:y.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 v=x.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(v)return`https://www.youtube.com/embed/${v[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 y=x.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(y)return`https://www.loom.com/embed/${y[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(xn,{className:"h-12 w-3/4 mx-auto"}),e.jsx(xn,{className:"h-64 w-full"}),e.jsx(xn,{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,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: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})]})]})},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=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(Ir,{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(O7t,{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 QDs(){const{user:s}=_s(),t=Sa(),{data:n}=Ow();return st({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 vkr(s){const{user:t}=_s();return st({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 z7t(s){const{user:t}=_s(),n=Zt();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]),st({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 JDs(){const s=Zt(),t=Sa();return mt({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 B7t(){const s=Zt();return mt({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 eFs(){const s=Zt();return mt({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 $7t(s){return st({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 tFs(s){const{user:t}=_s();return st({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 sFs(s){return st({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 nFs(){return mt({mutationFn:async s=>{const{error:t}=await q.from("open_house_survey_responses").insert(s);if(t)throw t}})}function rFs(s){const{user:t}=_s();return st({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 aFs(){const s=Zt();return mt({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 iFs(){const s=Zt();return mt({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 oFs(){const s=Zt();return mt({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 lFs(){const s=Zt();return mt({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 cFs(){return mt({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 dFs(){return mt({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 uFs(){return mt({mutationFn:async s=>{await q.rpc("increment_open_house_scan",{_slug:s})}})}async function U7t(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 hFs(s){const{user:t}=_s();return st({queryKey:["open-house-rooms",s],queryFn:()=>U7t(s),enabled:!!t&&!!s})}function mFs(s){return st({queryKey:["public-open-house-rooms",s],queryFn:()=>U7t(s),enabled:!!s})}function fFs(){const s=Zt();return mt({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 pFs(){const s=Zt();return mt({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 gFs(){const s=Zt();return mt({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 xFs(){const s=Zt();return mt({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 yFs(){const s=Zt();return mt({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=Zt();return mt({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 bFs(){const s=Zt();return mt({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 _Fs(s){const{user:t}=_s();return st({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=Zt();return mt({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 jFs=Object.defineProperty,CL=(s,t)=>jFs(s,"name",{value:t,configurable:!0}),Ytt="Switch",[NFs,bkr]=ep(Ytt),[kFs,Ztt]=NFs(Ytt);function q7t(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]=dy({prop:n,defaultProp:a??!1,onChange:c,caller:Ytt}),[g,x]=j.useState(null),[v,y]=j.useState(null),b=j.useRef(!1),[w,S]=j.useReducer(I=>I+1,0),A=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:A,bubbleInput:v,setBubbleInput:y};return e.jsx(kFs,{scope:t,...E,children:H7t(h)?h(E):r})}CL(q7t,"SwitchProvider");var SFs="SwitchTrigger",CFs=j.forwardRef(CL(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:v}=Ztt(SFs,t),y=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=CL(()=>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":Xtt(d),"data-disabled":c?"":void 0,disabled:c,value:o,...r,ref:y,onClick:Ra(n,w=>{g(),m(S=>!S),v&&x&&(f.current=w.isPropagationStopped(),f.current||w.stopPropagation())})})},"SwitchTrigger")),V7t=j.forwardRef(CL(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(q7t,{__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(CFs,{...m,ref:n,__scopeSwitch:r}),f&&e.jsx(MFs,{__scopeSwitch:r})]})})},"Switch")),AFs="SwitchThumb",EFs=j.forwardRef(CL(function(t,n){const{__scopeSwitch:r,...a}=t,i=Ztt(AFs,r);return e.jsx(Ei.span,{"data-state":Xtt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:n})},"SwitchThumb")),TFs="SwitchBubbleInput",MFs=j.forwardRef(CL(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:v}=Ztt(TFs,t),y=Vo(a,v),b=HW(i),w=j.useRef(!1),S=j.useRef(c),A=j.useRef(o);j.useEffect(()=>{const I=x;if(!I)return;const P=window.HTMLInputElement.prototype,D=Object.getOwnPropertyDescriptor(P,"checked").set,O=o!==A.current;A.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:y,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 H7t(s){return typeof s=="function"}CL(H7t,"isFunction");function Xtt(s){return s?"checked":"unchecked"}CL(Xtt,"getState");const jn=j.forwardRef(({className:s,...t},n)=>e.jsx(V7t,{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(EFs,{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")})}));jn.displayName=V7t.displayName;const PFs=["Excellent","Good","Neutral","Bad","Very Bad"],IFs=[5,4,3,2,1];function LFs({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=nFs(),[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"}),PFs.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}),IFs.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(Ct,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}function eGe(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function RFs({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:[eGe(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(fa,{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(kd,{className:"h-6 w-6"})}),l.kind==="video"?eGe(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 DFs({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"?eGe(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(kd,{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 l7e={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:no},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:Ea},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:Qr},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:su}},FFs=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function OFs(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 zFs({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(Ne=>Ne[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,v]=j.useState(a||""),[y,b]=j.useState(!1),[w,S]=j.useState(null),[A,E]=j.useState(""),[I,P]=j.useState(""),[R,D]=j.useState(""),[O,U]=j.useState([]),[W,V]=j.useState(""),[G,Z]=j.useState(""),[X,ae]=j.useState(""),[le,re]=j.useState(""),te=OFs(s.price),J=s.tour_mode==="rooms",{data:ce=[]}=mFs(J?s.id:void 0),ve=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),fe=Ne=>{u(Ne),m(""),E(""),P(""),D(""),U([]),V(""),Z(""),ae(""),re("")},ue=()=>{u(null)},be=Ne=>{U(Be=>Be.includes(Ne)?Be.filter(Se=>Se!==Ne):[...Be,Ne])},Ee=Ne=>Ne==="showing"?{preferred_date:A||null,preferred_time:I||null,alternate_date:R||null}:Ne==="disclosure"?{requested_documents:O}:Ne==="offer"?{offer_amount:W||null,financing:G||null,timeline:X||null,pre_approved:le||null}:{},ke=d?d==="showing"?!!A:d==="question"?h.trim().length>0:!0:!1,Ie=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 Ne=Ee(d),{error:Be}=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,...Ne}});if(Be)throw Be;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:Ne}}).catch(()=>{}),S(d),_a({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{ue(),S(null)},1400)}catch(Ne){_a({title:"Something went wrong",description:Ne.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(ui,{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(n2,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(C0,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(w_,{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(Ii,{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(pn,{className:"h-4 w-4"})})]})]}),J&&ce.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(RFs,{rooms:ce}),e.jsx(DFs,{rooms:ce})]}),ve.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:ve.map(Ne=>{const Be=l7e[Ne],Se=Be.icon;return e.jsxs("button",{onClick:()=>fe(Ne),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(Se,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:Be.label})]},Ne)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(Vy,{open:!!d,onOpenChange:Ne=>!Ne&&ue(),children:e.jsx(uy,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(I0,{className:"text-left",children:[e.jsx(L0,{children:l7e[d].title}),e.jsxs(IB,{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(Vr,{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:Ne=>g(Ne.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:Ne=>v(Ne.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:A,onChange:Ne=>E(Ne.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:Ne=>P(Ne.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:Ne=>D(Ne.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:FFs.map(Ne=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(ai,{checked:O.includes(Ne),onCheckedChange:()=>be(Ne)}),e.jsx("span",{children:Ne})]},Ne))})]}),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:Ne=>V(Ne.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Financing"}),e.jsxs(ms,{value:G,onValueChange:Z,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:le,onValueChange:re,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:Ne=>m(Ne.target.value),placeholder:l7e[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx($,{onClick:Ie,disabled:y||!ke,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:y?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const BFs=F2({first_name:yl().trim().min(1,"First name is required").max(50),last_name:yl().trim().max(50).optional(),email:yl().trim().email("Please enter a valid email").max(255).optional().or(fx("")),phone:yl().trim().max(20).optional().or(fx(""))}),$Fs=[{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 G7t({slug:s}={}){var ze;const t=Wi(),n=s||t.slug,[r]=Nc(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=$7t(n),d=cFs(),u=dFs(),h=uFs(),m=j.useRef(!1),[f,g]=j.useState("welcome"),[x,v]=j.useState(null),[y,b]=j.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[w,S]=j.useState(""),[A,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(()=>{v(null),b({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),S(""),E(!1),P(!1),D(""),U(""),V(i),g(a?"info":"welcome")},[a]),Z=j.useCallback((Ve,ht)=>{l!=null&&l.id&&q.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:Ve,first_name:ht.first_name??y.first_name,last_name:ht.last_name??y.last_name,email:ht.email??y.email,phone:ht.phone??y.phone,visitor_intent:ht.visitor_intent??w,message:ht.message,wants_market_updates:ht.wants_market_updates??A,has_agent:ht.has_agent??I,working_with_agent_name:ht.working_with_agent_name??R,visitor_address:ht.visitor_address??y.visitor_address}}).catch(Qe=>console.error("Guest book lead notify failed:",Qe))},[l==null?void 0:l.id,y,w,A,I,R]);j.useEffect(()=>{if(!a||f!=="done")return;V(i);const Ve=setInterval(()=>{V(ht=>ht<=1?(clearInterval(Ve),G(),0):ht-1)},1e3);return()=>clearInterval(Ve)},[a,f,G]),j.useEffect(()=>{if(!a)return;g(ht=>ht==="welcome"?"info":ht);let Ve=null;return(async()=>{var ht,Qe;try{Ve=await((Qe=(ht=navigator.wakeLock)==null?void 0:ht.request)==null?void 0:Qe.call(ht,"screen"))}catch{}})(),()=>{var ht;try{(ht=Ve==null?void 0:Ve.release)==null||ht.call(Ve)}catch{}}},[a]);const X=j.useCallback(()=>{var ht;const Ve=document.documentElement;document.fullscreenElement||(ht=Ve.requestFullscreen||Ve.webkitRequestFullscreen)==null||ht.call(Ve).catch(()=>{})},[]),{data:ae,isLoading:le}=sFs(l==null?void 0:l.id),re=!!(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 Ve=`oh_scan_${l.id}`;if(sessionStorage.getItem(Ve)){m.current=!0;return}m.current=!0,sessionStorage.setItem(Ve,"1"),h.mutate(n)},[n,l==null?void 0:l.id]),j.useEffect(()=>{f==="pending_survey"&&(le||g(re&&((ae==null?void 0:ae.length)??0)>0?"survey":"done"))},[f,le,re,ae]);const ce=Ve=>{if(!Ve)return"";const[ht,Qe]=Ve.split(":"),at=parseInt(ht),rt=at>=12?"PM":"AM";return`${at>12?at-12:at||12}:${Qe} ${rt}`},ve=async()=>{U("");const Ve=BFs.safeParse(y);if(!Ve.success){U(Ve.error.issues[0].message);return}if(!y.email&&!y.phone){U("Please provide either an email or phone number");return}const ht=(l==null?void 0:l.kind)==="virtual";let Qe=null;if(!x&&(l!=null&&l.id))try{const at=await d.mutateAsync({open_house_id:l.id,first_name:y.first_name.trim(),last_name:y.last_name.trim()||void 0,email:y.email.trim()||void 0,phone:y.phone.trim()||void 0,visitor_address:J&&y.visitor_address.trim()?y.visitor_address.trim():void 0,wants_market_updates:A,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():void 0,partial_signin:ht?!1:te});Qe=at.id,v(at.id)}catch{if(ht){U("We could not start the virtual tour. Please try again.");return}}if(ht){te?g("intent"):(Qe&&Z(Qe,{}),g("done"));return}if(!te){Qe&&Z(Qe,{}),re?!le&&ae&&ae.length>0?g("survey"):g("pending_survey"):g("done");return}g("intent")},fe=async Ve=>{S(Ve);try{let ht=x;if(ht?await u.mutateAsync({visitor_id:ht,visitor_intent:Ve,wants_market_updates:A,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():null,partial_signin:!1}):(ht=(await d.mutateAsync({open_house_id:l.id,first_name:y.first_name.trim(),last_name:y.last_name.trim()||void 0,email:y.email.trim()||void 0,phone:y.phone.trim()||void 0,visitor_address:J&&y.visitor_address.trim()?y.visitor_address.trim():void 0,visitor_intent:Ve,wants_market_updates:A,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():void 0,partial_signin:!1})).id,v(ht)),ht&&Z(ht,{visitor_intent:Ve,wants_market_updates:A,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():null}),(l==null?void 0:l.kind)==="virtual"){g("done");return}re?!le&&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,be=((ze=ue==null?void 0:ue.name)==null?void 0:ze.split(" ").map(Ve=>Ve[0]).join("").slice(0,2))||"?",Ee=l.event_type==="community",ke=l.kind==="virtual",Ie=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(ke&&(Ie||f==="done"))return!Ie&&!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(Dl,{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"})]}),Ie&&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(zFs,{openHouse:l,visitorId:Ie?"preview":x,visitorName:Ie?"Preview Visitor":`${y.first_name} ${y.last_name}`.trim(),visitorEmail:Ie?"":y.email,visitorPhone:Ie?"":y.phone,previewMode:Ie})]});const Ne=`${ke?"Virtual Open House":Ee?"Community Event":"Open House"} — ${l.property_address}`,Se=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?Js(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(Dl,{children:[e.jsx("title",{children:Ne}),e.jsx("meta",{name:"description",content:Se||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:Ne}),e.jsx("meta",{property:"og:description",content:Se||`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:Ne}),e.jsx("meta",{name:"twitter:description",content:Se||`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(Ii,{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:be})]}),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(ui,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!ke&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ea,{className:"h-3 w-3"}),Js(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(ca,{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(wi,{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(ui,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!ke&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ea,{className:"h-3 w-3"}),Js(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(ca,{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(Qa,{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(Va,{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:y.first_name,onChange:Ve=>b(ht=>({...ht,first_name:Ve.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:y.last_name,onChange:Ve=>b(ht=>({...ht,last_name:Ve.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:y.email,onChange:Ve=>b(ht=>({...ht,email:Ve.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:y.phone,onChange:Ve=>b(ht=>({...ht,phone:Ve.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:y.visitor_address,onChange:Ve=>b(ht=>({...ht,visitor_address:Ve.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:A,onChange:Ve=>E(Ve.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(jn,{checked:I,onCheckedChange:P})]})]}),I&&e.jsx(pe,{value:R,onChange:Ve=>D(Ve.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:ve,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(Qa,{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(Va,{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:$Fs.map(Ve=>e.jsxs("button",{onClick:()=>fe(Ve.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:Ve.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Ve.label})]},Ve.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(LFs,{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(Vr,{className:"h-8 w-8 text-green-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"You're all set!"}),e.jsxs("p",{className:"text-slate-500 text-sm mt-1",children:["Thanks for signing in, ",y.first_name,". ",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(Qr,{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(nV,{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(IJ,{className:"h-3 w-3"})})]})]})})]})}function UFs(s){return st({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 qFs(){const s=Zt();return mt({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 VFs(s){const t=Zt();return mt({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 HFs(s){const t=Zt();return mt({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 GFs=F2({first_name:yl().trim().min(1,"First name is required").max(50),last_name:yl().trim().max(50).optional(),email:yl().trim().email("Please enter a valid email").max(255),phone:yl().trim().max(20).optional().or(fx("")),message:yl().trim().max(500).optional().or(fx(""))}),c7e=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}`},WFs=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 W7t({slug:s}={}){const t=Wi(),n=s||t.slug,{data:r,isLoading:a,error:i}=$7t(n),l=qFs(),[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,v]=j.useState(!1),y=j.useMemo(()=>WFs(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(", "),A=async()=>{g("");const P=GFs.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}),v(!0)}catch(R){g((R==null?void 0:R.message)||"Something went wrong. Please try again.")}},E=j.useMemo(()=>{if(!r||!y)return"";const P=V=>String(V).padStart(2,"0"),R=`${y.getFullYear()}${P(y.getMonth()+1)}${P(y.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,y,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(Dl,{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}${y?` on ${Js(y,"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:[y&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ea,{className:"h-4 w-4 text-[#d4b978]"}),Js(y,"EEEE, MMMM d, yyyy")]}),r.start_time&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ca,{className:"h-4 w-4 text-[#d4b978]"}),c7e(r.start_time),r.end_time?` – ${c7e(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(Lce,{icon:e.jsx(va,{className:"h-4 w-4"}),label:"Price",value:`$${Number(r.price).toLocaleString()}`}):null,r.beds?e.jsx(Lce,{icon:e.jsx(C4,{className:"h-4 w-4"}),label:"Beds",value:String(r.beds)}):null,r.baths?e.jsx(Lce,{icon:e.jsx(C0,{className:"h-4 w-4"}),label:"Baths",value:String(r.baths)}):null,r.sqft?e.jsx(Lce,{icon:e.jsx(M4,{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(Vr,{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 ",y?Js(y,"EEEE, MMMM d"):"soon",r.start_time?` at ${c7e(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(vv,{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(ui,{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(jn,{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:A,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(Qa,{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(Ii,{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(ui,{className:"h-4 w-4"}),"Get directions to ",r.property_address]})})]})]})}function Lce({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 _kr(s){const{user:t}=_s();return st({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 wkr(){const s=Zt(),{user:t}=_s();return mt({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 jkr(){const s=Zt();return mt({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 KFs(s){return st({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 W4=(s,t,n)=>n>t?t:n{};const AL={},K7t=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s),Y7t=s=>typeof s=="object"&&s!==null,Z7t=s=>/^0[^.\s]+$/u.test(s);function X7t(s){let t;return()=>(t===void 0&&(t=s()),t)}const ek=s=>s,Uae=(...s)=>s.reduce((t,n)=>r=>n(t(r))),Xte=(s,t,n)=>{const r=t-s;return r?(n-s)/r:1};class sst{constructor(){this.subscriptions=[]}add(t){return tst(this.subscriptions,t),()=>EEe(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,BN=s=>s/1e3,Q7t=(s,t)=>t?s*(1e3/t):0,J7t=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,ZFs=1e-7,XFs=12;function QFs(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=J7t(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>ZFs&&++oQFs(i,0,1,s,n);return i=>i===0||i===1?i:J7t(a(i),t,r)}const eBt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,tBt=s=>t=>1-s(1-t),sBt=qae(.33,1.53,.69,.99),nst=tBt(sBt),nBt=eBt(nst),rBt=s=>s>=1?1:(s*=2)<1?.5*nst(s):.5*(2-Math.pow(2,-10*(s-1))),rst=s=>1-Math.sin(Math.acos(s)),aBt=tBt(rst),iBt=eBt(rst),JFs=qae(.42,0,1,1),eOs=qae(0,0,.58,1),oBt=qae(.42,0,.58,1),tOs=s=>Array.isArray(s)&&typeof s[0]!="number",lBt=s=>Array.isArray(s)&&typeof s[0]=="number",sOs={linear:ek,easeIn:JFs,easeInOut:oBt,easeOut:eOs,circIn:rst,circInOut:iBt,circOut:aBt,backIn:nst,backInOut:nBt,backOut:sBt,anticipate:rBt},nOs=s=>typeof s=="string",Yyt=s=>{if(lBt(s)){GLe(s.length===4);const[t,n,r,a]=s;return qae(t,n,r,a)}else if(nOs(s))return sOs[s];return s},Rce=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function rOs(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 aOs=40;function cBt(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=Rce.reduce((w,S)=>(w[S]=rOs(i),w),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:m,render:f,postRender:g}=l,x=()=>{const w=AL.useManualTiming,S=w?a.timestamp:performance.now();n=!1,w||(a.delta=r?1e3/60:Math.max(Math.min(S-a.timestamp,aOs),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))},v=()=>{n=!0,r=!0,a.isProcessing||s(x)};return{schedule:Rce.reduce((w,S)=>{const A=l[S];return w[S]=(E,I=!1,P=!1)=>(n||v(),A.schedule(E,I,P)),w},{}),cancel:w=>{for(let S=0;S(Y4e===void 0&&f_.set(sb.isProcessing||AL.useManualTiming?sb.timestamp:performance.now()),Y4e),set:s=>{Y4e=s,queueMicrotask(iOs)}},dBt=s=>t=>typeof t=="string"&&t.startsWith(s),uBt=dBt("--"),oOs=dBt("var(--"),ast=s=>oOs(s)?lOs.test(s.split("/*")[0].trim()):!1,lOs=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Zyt(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const eK={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},Qte={...eK,transform:s=>W4(0,1,s)},Dce={...eK,default:1},fee=s=>Math.round(s*1e5)/1e5,ist=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function cOs(s){return s==null}const dOs=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ost=(s,t)=>n=>!!(typeof n=="string"&&dOs.test(n)&&n.startsWith(s)||t&&!cOs(n)&&Object.prototype.hasOwnProperty.call(n,t)),hBt=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match(ist);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},uOs=s=>W4(0,255,s),u7e={...eK,transform:s=>Math.round(uOs(s))},r8={test:ost("rgb","red"),parse:hBt("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+u7e.transform(s)+", "+u7e.transform(t)+", "+u7e.transform(n)+", "+fee(Qte.transform(r))+")"};function hOs(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 tGe={test:ost("#"),parse:hOs,transform:r8.transform},Vae=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),gA=Vae("deg"),D4=Vae("%"),Bo=Vae("px"),mOs=Vae("vh"),fOs=Vae("vw"),Xyt={...D4,parse:s=>D4.parse(s)/100,transform:s=>D4.transform(s*100)},HU={test:ost("hsl","hue"),parse:hBt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+D4.transform(fee(t))+", "+D4.transform(fee(n))+", "+fee(Qte.transform(r))+")"},My={test:s=>r8.test(s)||tGe.test(s)||HU.test(s),parse:s=>r8.test(s)?r8.parse(s):HU.test(s)?HU.parse(s):tGe.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?r8.transform(s):HU.transform(s),getAnimatableNone:s=>{const t=My.parse(s);return t.alpha=0,My.transform(t)}},pOs=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function gOs(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match(ist))==null?void 0:t.length)||0)+(((n=s.match(pOs))==null?void 0:n.length)||0)>0}const mBt="number",fBt="color",xOs="var",yOs="var(",Qyt="${}",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 kG(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(vOs,c=>(My.test(c)?(r.color.push(i),a.push(fBt),n.push(My.parse(c))):c.startsWith(yOs)?(r.var.push(i),a.push(xOs),n.push(c)):(r.number.push(i),a.push(mBt),n.push(parseFloat(c))),++i,Qyt)).split(Qyt);return{values:n,split:o,indexes:r,types:a}}function bOs(s){return kG(s).values}function pBt({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:My.test(s)?My.getAnimatableNone(s):s,jOs=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:wOs(s);function NOs(s){const t=kG(s);return pBt(t)(t.values.map((r,a)=>jOs(r,t.split[a])))}const rC={test:gOs,parse:bOs,createTransformer:_Os,getAnimatableNone:NOs};function h7e(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 kOs({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=h7e(c,o,s+1/3),i=h7e(c,o,s),l=h7e(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function TEe(s,t){return n=>n>0?t:s}const jf=(s,t,n)=>s+(t-s)*n,m7e=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},SOs=[tGe,r8,HU],COs=s=>SOs.find(t=>t.test(s));function Jyt(s){const t=COs(s);if(!t)return!1;let n=t.parse(s);return t===HU&&(n=kOs(n)),n}const e0t=(s,t)=>{const n=Jyt(s),r=Jyt(t);if(!n||!r)return TEe(s,t);const a={...n};return i=>(a.red=m7e(n.red,r.red,i),a.green=m7e(n.green,r.green,i),a.blue=m7e(n.blue,r.blue,i),a.alpha=jf(n.alpha,r.alpha,i),r8.transform(a))},sGe=new Set(["none","hidden"]);function AOs(s,t){return sGe.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function EOs(s,t){return n=>jf(s,t,n)}function lst(s){return typeof s=="number"?EOs:typeof s=="string"?ast(s)?TEe:My.test(s)?e0t:POs:Array.isArray(s)?gBt:typeof s=="object"?My.test(s)?e0t:TOs:TEe}function gBt(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>lst(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function MOs(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=rC.createTransformer(t),r=kG(s),a=kG(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?sGe.has(s)&&!a.values.length||sGe.has(t)&&!r.values.length?AOs(s,t):Uae(gBt(MOs(r,a),a.values),n):TEe(s,t)};function xBt(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?jf(s,t,n):lst(s)(s,t)}const IOs=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>kf.update(t,n),stop:()=>EL(t),now:()=>sb.isProcessing?sb.timestamp:f_.now()}},yBt=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=MEe?1/0:t}function LOs(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(cst(r),MEe);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:BN(a)}}const dx={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 nGe(s,t){return s*Math.sqrt(1-t*t)}const ROs=12;function DOs(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,m=u-n,f=nGe(d,l),g=Math.exp(-h);return f7e-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=nGe(Math.pow(d,2),l);return(-a(d)+f7e>0?-1:1)*((m-f)*g)/x}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-f7e+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=DOs(a,i,o);if(s=h2(s),isNaN(c))return{stiffness:dx.stiffness,damping:dx.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const OOs=["duration","bounce"],zOs=["stiffness","damping","mass"];function t0t(s,t){return t.some(n=>s[n]!==void 0)}function BOs(s){let t={velocity:dx.velocity,stiffness:dx.stiffness,damping:dx.damping,mass:dx.mass,isResolvedFromDuration:!1,...s};if(!t0t(s,zOs)&&t0t(s,OOs))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*W4(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:dx.mass,stiffness:a,damping:i}}else{const n=FOs({...s,velocity:0});t={...t,...n,mass:dx.mass},t.isResolvedFromDuration=!0}return t}function PEe(s=dx.visualDuration,t=dx.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}=BOs({...n,velocity:-BN(n.velocity||0)}),g=m||0,x=d/(2*Math.sqrt(c*u)),v=l-i,y=BN(Math.sqrt(c/u)),b=Math.abs(v)<5;r||(r=b?dx.restSpeed.granular:dx.restSpeed.default),a||(a=b?dx.restDelta.granular:dx.restDelta.default);let w,S,A,E,I,P;if(x<1)A=nGe(y,x),E=(g+x*y*v)/A,w=D=>{const O=Math.exp(-x*y*D);return l-O*(E*Math.sin(A*D)+v*Math.cos(A*D))},I=x*y*E+v*A,P=x*y*v-E*A,S=D=>Math.exp(-x*y*D)*(I*Math.sin(A*D)+P*Math.cos(A*D));else if(x===1){w=O=>l-Math.exp(-y*O)*(v+(g+y*v)*O);const D=g+y*v;S=O=>Math.exp(-y*O)*(y*D*O-g)}else{const D=y*Math.sqrt(x*x-1);w=V=>{const G=Math.exp(-x*y*V),Z=Math.min(D*V,300);return l-G*((g+x*y*v)*Math.sinh(Z)+D*v*Math.cosh(Z))/D};const O=(g+x*y*v)/D,U=x*y*O-v*D,W=x*y*v-O*D;S=V=>{const G=Math.exp(-x*y*V),Z=Math.min(D*V,300);return G*(U*Math.sinh(Z)+W*Math.cosh(Z))}}const R={calculatedDuration:f&&h||null,velocity:D=>h2(S(D)),next:D=>{if(!f&&x<1){const U=Math.exp(-x*y*D),W=Math.sin(A*D),V=Math.cos(A*D),G=l-U*(E*W+v*V),Z=h2(U*(I*W+P*V));return o.done=Math.abs(Z)<=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=h2(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(cst(R),MEe),O=yBt(U=>R.next(D*U).value,D,30);return D+"ms "+O},toTransition:()=>{}};return R}PEe.applyToOptions=s=>{const t=LOs(s,100,PEe);return s.ease=t.ease,s.duration=h2(t.duration),s.type="keyframes",s};const $Os=5;function vBt(s,t,n){const r=Math.max(t-$Os,0);return Q7t(n-s(r),t-r)}function rGe({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=>y+b(P),S=P=>{const R=b(P),D=w(P);m.done=Math.abs(R)<=d,m.value=m.done?y:D};let A,E;const I=P=>{f(m.value)&&(A=P,E=PEe({keyframes:[m.value,g(m.value)],velocity:vBt(w,P,m.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return I(0),{calculatedDuration:null,next:P=>{let R=!1;return!E&&A===void 0&&(R=!0,S(P),I(P)),A!==void 0&&P>=A?E.next(P-A):(!R&&S(P),m)}}}function UOs(s,t,n){const r=[],a=n||AL.mix||xBt,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=UOs(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(W4(s[0],s[i-1],u)):d}function VOs(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=Xte(0,t,r);s.push(jf(n,1,a))}}function HOs(s){const t=[0];return VOs(t,s.length-1),t}function GOs(s,t){return s.map(n=>n*t)}function WOs(s,t){return s.map(()=>t||oBt).splice(0,s.length-1)}function pee({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=tOs(r)?r.map(Yyt):Yyt(r),i={done:!1,value:t[0]},l=GOs(n&&n.length===t.length?n:HOs(t),s),o=qOs(l,t,{ease:Array.isArray(a)?a:WOs(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const KOs=s=>s!==null;function WLe(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(KOs),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const YOs={decay:rGe,inertia:rGe,tween:pee,keyframes:pee,spring:PEe};function bBt(s){typeof s.type=="string"&&(s.type=YOs[s.type])}class dst{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 ZOs=s=>s/100;class IEe extends dst{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!==f_.now()&&this.tick(f_.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;bBt(t);const{type:n=pee,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||pee;c!==pee&&typeof o[0]!="number"&&(this.mixKeyframes=Uae(ZOs,xBt(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=cst(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:v}=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 y=this.currentTime-d*(this.playbackSpeed>=0?1:-1),b=this.playbackSpeed>=0?y<0:y>a;this.currentTime=Math.max(y,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=W4(0,1,D)*o}let A;b?(this.delayState.value=u[0],A=this.delayState):A=S.next(w),i&&!b&&(A.value=i(A.value));let{done:E}=A;!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!==rGe&&(A.value=WLe(u,this.options,v,this.speed)),x&&x(A.value),I&&this.finish(),A}then(t,n){return this.finished.then(t,n)}get duration(){return BN(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+BN(t)}get time(){return BN(this.currentTime)}set time(t){t=h2(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 vBt(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(f_.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=BN(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=IOs,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(f_.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 XOs(s){for(let t=1;ts*180/Math.PI,aGe=s=>{const t=a8(Math.atan2(s[1],s[0]));return iGe(t)},QOs={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:aGe,rotateZ:aGe,skewX:s=>a8(Math.atan(s[1])),skewY:s=>a8(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},iGe=s=>(s=s%360,s<0&&(s+=360),s),s0t=aGe,n0t=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),r0t=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),JOs={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:n0t,scaleY:r0t,scale:s=>(n0t(s)+r0t(s))/2,rotateX:s=>iGe(a8(Math.atan2(s[6],s[5]))),rotateY:s=>iGe(a8(Math.atan2(-s[2],s[0]))),rotateZ:s0t,rotate:s0t,skewX:s=>a8(Math.atan(s[4])),skewY:s=>a8(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function oGe(s){return s.includes("scale")?1:0}function lGe(s,t){if(!s||s==="none")return oGe(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=JOs,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=QOs,a=o}if(!a)return oGe(t);const i=r[t],l=a[1].split(",").map(t8s);return typeof i=="function"?i(l):l[i]}const e8s=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return lGe(n,t)};function t8s(s){return parseFloat(s.trim())}const tK=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],sK=new Set([...tK,"pathRotation"]),a0t=s=>s===eK||s===Bo,s8s=new Set(["x","y","z"]),n8s=tK.filter(s=>!s8s.has(s));function r8s(s){const t=[];return n8s.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const fI={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})=>lGe(t,"x"),y:(s,{transform:t})=>lGe(t,"y")};fI.translateX=fI.x;fI.translateY=fI.y;const r7=new Set;let cGe=!1,dGe=!1,uGe=!1;function _Bt(){if(dGe){const s=Array.from(r7).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=r8s(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)})}dGe=!1,cGe=!1,r7.forEach(s=>s.complete(uGe)),r7.clear()}function wBt(){r7.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(dGe=!0)})}function a8s(){uGe=!0,wBt(),_Bt(),uGe=!1}class ust{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?(r7.add(this),cGe||(cGe=!0,kf.read(wBt),kf.resolveKeyframes(_Bt))):(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])}XOs(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),r7.delete(this)}cancel(){this.state==="scheduled"&&(r7.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const i8s=s=>s.startsWith("--");function jBt(s,t,n){i8s(t)?s.style.setProperty(t,n):s.style[t]=n}const o8s={};function NBt(s,t){const n=X7t(s);return()=>o8s[t]??n()}const l8s=NBt(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),kBt=NBt(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),rQ=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,i0t={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:rQ([0,.65,.55,1]),circOut:rQ([.55,0,1,.45]),backIn:rQ([.31,.01,.66,-.59]),backOut:rQ([.33,1.53,.69,.99])};function SBt(s,t){if(s)return typeof s=="function"?kBt()?yBt(s,t):"ease-out":lBt(s)?rQ(s):Array.isArray(s)?s.map(n=>SBt(n,t)||i0t.easeOut):i0t[s]}function c8s(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=SBt(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 CBt(s){return typeof s=="function"&&"applyToOptions"in s}function d8s({type:s,...t}){return CBt(s)&&kBt()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class ABt extends dst{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,GLe(typeof t.type!="string");const d=d8s(t);this.animation=c8s(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=WLe(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),jBt(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 BN(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+BN(t)}get time(){return BN(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=h2(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&&l8s()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),ek):a(this)}}const EBt={anticipate:rBt,backInOut:nBt,circInOut:iBt};function u8s(s){return s in EBt}function h8s(s){typeof s.ease=="string"&&u8s(s.ease)&&(s.ease=EBt[s.ease])}const p7e=10;class m8s extends ABt{constructor(t){h8s(t),bBt(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 IEe({...l,autoplay:!1}),c=Math.max(p7e,f_.now()-this.startTime),d=W4(0,p7e,c-p7e),u=o.sample(c).value,{name:h}=this.options;i&&h&&jBt(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const o0t=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(rC.test(s)||s==="0")&&!s.startsWith("url("));function f8s(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function b8s(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&&(TBt.has(n)||y8s.has(n)&&x8s(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const _8s=40;class w8s extends dst{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,v;this._animation&&(this._animation.stop(),(x=this.stopTimeline)==null||x.call(this)),(v=this.keyframeResolver)==null||v.cancel()},this.createdAt=f_.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)||ust;this.keyframeResolver=new f(o,(x,v,y)=>this.onKeyframesResolved(x,v,m,!y),c,d,u),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(t,n,r,a){var y,b;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=r;this.resolvedAt=f_.now();let h=!0;p8s(t,i,l,o)||(h=!1,(AL.instantAnimations||!c)&&(u==null||u(WLe(t,r,n))),t[0]=t[t.length-1],hGe(r),r.repeat=0);const f={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>_8s?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},g=h&&!d&&b8s(f),x=(b=(y=f.motionValue)==null?void 0:y.owner)==null?void 0:b.current;let v;if(g)try{v=new m8s({...f,element:x})}catch{v=new IEe(f)}else v=new IEe(f);v.finished.then(()=>{this.notifyFinished()}).catch(ek),this.pendingTimeline&&(this.stopTimeline=v.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=v}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(),a8s()),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 MBt(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 l0t=30,j8s=s=>!isNaN(parseFloat(s));class N8s{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=f_.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=f_.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=j8s(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 sst);const r=this.events[t].add(n);return t==="change"?()=>{r(),kf.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=f_.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>l0t)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,l0t);return Q7t(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 SG(s,t){return new N8s(s,t)}function PBt(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function hst(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?PBt(n,s):n}const k8s={type:"spring",stiffness:500,damping:25,restSpeed:10},S8s=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),C8s={type:"keyframes",duration:.8},A8s={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},E8s=(s,{keyframes:t})=>t.length>2?C8s:sK.has(s)?s.startsWith("scale")?S8s(t[1]):k8s:A8s,T8s=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function M8s(s){for(const t in s)if(!T8s.has(t))return!0;return!1}const mst=(s,t,n,r={},a,i)=>l=>{const o=hst(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-h2(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};M8s(o)||Object.assign(u,E8s(s,u)),u.duration&&(u.duration=h2(u.duration)),u.repeatDelay&&(u.repeatDelay=h2(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(hGe(u),u.delay===0&&(h=!0)),(AL.instantAnimations||AL.skipAnimations||a!=null&&a.shouldSkipAnimations||o.skipAnimations)&&(h=!0,hGe(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const m=WLe(u.keyframes,o);if(m!==void 0){kf.update(()=>{u.onUpdate(m),u.onComplete()});return}}return o.isSync?new IEe(u):new w8s(u)},P8s=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function I8s(s){const t=P8s.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}function IBt(s,t,n=1){const[r,a]=I8s(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return K7t(l)?parseFloat(l):l}return ast(a)?IBt(a,t,n+1):a}function c0t(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function fst(s,t,n,r){if(typeof t=="function"){const[a,i]=c0t(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]=c0t(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function a7(s,t,n){const r=s.getProps();return fst(r,t,n!==void 0?n:r.custom,s)}const LBt=new Set(["width","height","top","left","right","bottom",...tK]),mGe=s=>Array.isArray(s);function L8s(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,SG(n))}function R8s(s){return mGe(s)?s[s.length-1]||0:s}function D8s(s,t){const n=a7(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=R8s(i[l]);L8s(s,l,o)}}const ub=s=>!!(s&&s.getVelocity);function F8s(s){return!!(ub(s)&&s.add)}function fGe(s,t){const n=s.getValue("willChange");if(F8s(n))return n.add(t);if(!n&&AL.WillChange){const r=new AL.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function pst(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const O8s="framerAppearId",RBt="data-"+pst(O8s);function DBt(s){return s.props[RBt]}function z8s({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function FBt(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?PBt(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),v=o[g];if(v===void 0||m&&z8s(m,g))continue;const y={delay:n,...hst(i||{},g)};u&&(y.skipAnimations=!0);const b=x.get();if(b!==void 0&&!x.isAnimating()&&!Array.isArray(v)&&v===b&&!y.velocity){kf.update(()=>x.set(v));continue}let w=!1;if(window.MotionHandoffAnimation){const E=DBt(s);if(E){const I=window.MotionHandoffAnimation(E,g,kf);I!==null&&(y.startTime=I,w=!0)}}fGe(s,g);const S=d??s.shouldReduceMotion;x.start(mst(g,x,v,S&&LBt.has(g)?{type:!1}:y,s,w));const A=x.animation;A&&h.push(A)}if(l){const g=()=>kf.update(()=>{l&&D8s(s,l)});h.length?Promise.all(h).then(g):g()}return h}function pGe(s,t,n={}){var c;const r=a7(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(FBt(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:m}=a;return B8s(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 B8s(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(pGe(c,t,{...l,delay:n+(typeof r=="function"?0:r)+MBt(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function $8s(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>pGe(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=pGe(s,t,n);else{const a=typeof t=="function"?a7(s,t,n.custom):t;r=Promise.all(FBt(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const U8s={test:s=>s==="auto",parse:s=>s},OBt=s=>t=>t.test(s),zBt=[eK,Bo,D4,gA,fOs,mOs,U8s],d0t=s=>zBt.find(OBt(s));function q8s(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||Z7t(s):!0}const V8s=new Set(["brightness","contrast","saturate","opacity"]);function H8s(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match(ist)||[];if(!r)return s;const a=n.replace(r,"");let i=V8s.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const G8s=/\b([a-z-]*)\(.*?\)/gu,gGe={...rC,getAnimatableNone:s=>{const t=s.match(G8s);return t?t.map(H8s).join(" "):s}},xGe={...rC,getAnimatableNone:s=>{const t=rC.parse(s);return rC.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},u0t={...eK,transform:Math.round},W8s={rotate:gA,pathRotation:gA,rotateX:gA,rotateY:gA,rotateZ:gA,scale:Dce,scaleX:Dce,scaleY:Dce,scaleZ:Dce,skew:gA,skewX:gA,skewY:gA,distance:Bo,translateX:Bo,translateY:Bo,translateZ:Bo,x:Bo,y:Bo,z:Bo,perspective:Bo,transformPerspective:Bo,opacity:Qte,originX:Xyt,originY:Xyt,originZ:Bo},LEe={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,...W8s,zIndex:u0t,fillOpacity:Qte,strokeOpacity:Qte,numOctaves:u0t},K8s={...LEe,color:My,backgroundColor:My,outlineColor:My,fill:My,stroke:My,borderColor:My,borderTopColor:My,borderRightColor:My,borderBottomColor:My,borderLeftColor:My,filter:gGe,WebkitFilter:gGe,mask:xGe,WebkitMask:xGe},BBt=s=>K8s[s],Y8s=new Set([gGe,xGe]);function $Bt(s,t){let n=BBt(s);return Y8s.has(n)||(n=rC),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Z8s=new Set(["auto","none","0"]);function X8s(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}const gst=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"];function xst(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 yGe=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function Z4e(s){return Y7t(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:yst}=cBt(queueMicrotask,!1),cS={x:!1,y:!1};function UBt(){return cS.x||cS.y}function J8s(s){return s==="x"||s==="y"?cS[s]?null:(cS[s]=!0,()=>{cS[s]=!1}):cS.x||cS.y?null:(cS.x=cS.y=!0,()=>{cS.x=cS.y=!1})}function qBt(s,t){const n=xst(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function ezs(s){return!(s.pointerType==="touch"||UBt())}function tzs(s,t,n={}){const[r,a,i]=qBt(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",g)},h=v=>{d&&(d(v),d=void 0),u()},m=v=>{o=!1,window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),c&&(c=!1,h(v))},f=()=>{o=!0,window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",m,a)},g=v=>{if(v.pointerType!=="touch"){if(o){c=!0;return}h(v)}},x=v=>{if(!ezs(v))return;c=!1;const y=t(l,v);typeof y=="function"&&(d=y,l.addEventListener("pointerleave",g,a))};l.addEventListener("pointerenter",x,a),l.addEventListener("pointerdown",f,a)}),i}const VBt=(s,t)=>t?s===t?!0:VBt(s,t.parentElement):!1,vst=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,szs=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function nzs(s){return szs.has(s.tagName)||s.isContentEditable===!0}const rzs=new Set(["INPUT","SELECT","TEXTAREA"]);function azs(s){return rzs.has(s.tagName)||s.isContentEditable===!0}const X4e=new WeakSet;function h0t(s){return t=>{t.key==="Enter"&&s(t)}}function g7e(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const izs=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=h0t(()=>{if(X4e.has(n))return;g7e(n,"down");const a=h0t(()=>{g7e(n,"up")}),i=()=>g7e(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 m0t(s){return vst(s)&&!UBt()}const f0t=new WeakSet;function ozs(s,t,n={}){const[r,a,i]=qBt(s,n),l=o=>{const c=o.currentTarget;if(!m0t(o)||f0t.has(o))return;X4e.add(c),n.stopPropagation&&f0t.add(o);const d=t(c,o),u={...a,capture:!0},h=(g,x)=>{window.removeEventListener("pointerup",m,u),window.removeEventListener("pointercancel",f,u),X4e.has(c)&&X4e.delete(c),m0t(g)&&typeof d=="function"&&d(g,{success:x})},m=g=>{h(g,c===window||c===document||n.useGlobalTarget||VBt(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),Z4e(o)&&(o.addEventListener("focus",d=>izs(d,a)),!nzs(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function bst(s){return Y7t(s)&&"ownerSVGElement"in s}const Q4e=new WeakMap;let qM;const HBt=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:bst(r)&&"getBBox"in r?r.getBBox()[t]:r[n],lzs=HBt("inline","width","offsetWidth"),czs=HBt("block","height","offsetHeight");function dzs({target:s,borderBoxSize:t}){var n;(n=Q4e.get(s))==null||n.forEach(r=>{r(s,{get width(){return lzs(s,t)},get height(){return czs(s,t)}})})}function uzs(s){s.forEach(dzs)}function hzs(){typeof ResizeObserver>"u"||(qM=new ResizeObserver(uzs))}function mzs(s,t){qM||hzs();const n=xst(s);return n.forEach(r=>{let a=Q4e.get(r);a||(a=new Set,Q4e.set(r,a)),a.add(t),qM==null||qM.observe(r)}),()=>{n.forEach(r=>{const a=Q4e.get(r);a==null||a.delete(t),a!=null&&a.size||qM==null||qM.unobserve(r)})}}const J4e=new Set;let GU;function fzs(){GU=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};J4e.forEach(t=>t(s))},window.addEventListener("resize",GU)}function pzs(s){return J4e.add(s),GU||fzs(),()=>{J4e.delete(s),!J4e.size&&typeof GU=="function"&&(window.removeEventListener("resize",GU),GU=void 0)}}function p0t(s,t){return typeof s=="function"?pzs(s):mzs(s,t)}function gzs(s){return bst(s)&&s.tagName==="svg"}const xzs=[...zBt,My,rC],yzs=s=>xzs.find(OBt(s)),g0t=()=>({translate:0,scale:1,origin:0,originPoint:0}),WU=()=>({x:g0t(),y:g0t()}),x0t=()=>({min:0,max:0}),d0=()=>({x:x0t(),y:x0t()}),vzs=new WeakMap;function KLe(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function Jte(s){return typeof s=="string"||Array.isArray(s)}const _st=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],wst=["initial",..._st];function YLe(s){return KLe(s.animate)||wst.some(t=>Jte(s[t]))}function GBt(s){return!!(YLe(s)||s.variants)}function bzs(s,t,n){for(const r in t){const a=t[r],i=n[r];if(ub(a))s.addValue(r,a);else if(ub(i))s.addValue(r,SG(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,SG(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const vGe={current:null},WBt={current:!1},_zs=typeof window<"u";function wzs(){if(WBt.current=!0,!!_zs)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>vGe.current=s.matches;s.addEventListener("change",t),t()}else vGe.current=!1}const y0t=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let REe={};function KBt(s){REe=s}function jzs(){return REe}class Nzs{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=ust,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=f_.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(WBt.current||wzs(),this.shouldReduceMotion=vGe.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(),EL(this.notifyUpdate),EL(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&&TBt.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new ABt({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:h2(u)}),m=l(h);this.valueSubscriptions.set(t,()=>{m(),h.cancel()});return}const r=sK.has(t);r&&this.onBindTransform&&this.onBindTransform();const a=n.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&kf.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 REe){const n=REe[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):d0()}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=SG(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"&&(K7t(r)||Z7t(r))?r=parseFloat(r):!yzs(r)&&rC.test(n)&&(r=$Bt(t,n)),this.setBaseTarget(t,ub(r)?r.get():r)),ub(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=fst(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&&!ub(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 sst),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){yst.render(this.render)}}class YBt extends Nzs{constructor(){super(...arguments),this.KeyframeResolver=Q8s}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;ub(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class a6{constructor(t){this.isMounted=!1,this.node=t}update(){}}function ZBt({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function kzs({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function Szs(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 x7e(s){return s===void 0||s===1}function bGe({scale:s,scaleX:t,scaleY:n}){return!x7e(s)||!x7e(t)||!x7e(n)}function TO(s){return bGe(s)||XBt(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function XBt(s){return v0t(s.x)||v0t(s.y)}function v0t(s){return s&&s!=="0%"}function DEe(s,t,n){const r=s-n,a=t*r;return n+a}function b0t(s,t,n,r,a){return a!==void 0&&(s=DEe(s,a,r)),DEe(s,n,r)+t}function _Ge(s,t=0,n=1,r,a){s.min=b0t(s.min,t,n,r,a),s.max=b0t(s.max,t,n,r,a)}function QBt(s,{x:t,y:n}){_Ge(s.x,t.translate,t.scale,t.originPoint),_Ge(s.y,n.translate,n.scale,n.originPoint)}const _0t=.999999999999,w0t=1.0000000000001;function Czs(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;c_0t&&(t.x=1),t.y_0t&&(t.y=1)}function s4(s,t){s.min+=t,s.max+=t}function j0t(s,t,n,r,a=.5){const i=jf(s.min,s.max,a);_Ge(s,t,n,i,r)}function N0t(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function e3e(s,t,n){const r=n??s;j0t(s.x,N0t(t.x,r.x),t.scaleX,t.scale,t.originX),j0t(s.y,N0t(t.y,r.y),t.scaleY,t.scale,t.originY)}function JBt(s,t){return ZBt(Szs(s.getBoundingClientRect(),t))}function Azs(s,t,n){const r=JBt(s,n),{scroll:a}=t;return a&&(s4(r.x,a.offset.x),s4(r.y,a.offset.y)),r}const Ezs={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Tzs=tK.length;function Mzs(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=k0t(s,t.target.x),r=k0t(s,t.target.y);return`${n}% ${r}%`}},Pzs={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=rC.parse(s);if(a.length>5)return r;const i=rC.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=jf(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},wGe={borderRadius:{...kZ,applyTo:[...gst]},borderTopLeftRadius:kZ,borderTopRightRadius:kZ,borderBottomLeftRadius:kZ,borderBottomRightRadius:kZ,boxShadow:Pzs};function t9t(s,{layout:t,layoutId:n}){return sK.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!wGe[s]||s==="opacity")}function Nst(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)(ub(r[o])||a&&ub(a[o])||t9t(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function Izs(s){return window.getComputedStyle(s)}class Lzs extends YBt{constructor(){super(...arguments),this.type="html",this.renderInstance=e9t}mount(t){GLe(!!t.style),super.mount(t)}readValueFromInstance(t,n){var r;if(sK.has(n))return(r=this.projection)!=null&&r.isProjecting?oGe(n):e8s(t,n);{const a=Izs(t),i=(uBt(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return JBt(t,n)}build(t,n,r){jst(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return Nst(t,n,r)}}const Rzs={offset:"stroke-dashoffset",array:"stroke-dasharray"},Dzs={offset:"strokeDashoffset",array:"strokeDasharray"};function Fzs(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?Rzs:Dzs;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const Ozs=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function s9t(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(jst(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 Ozs)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&&Fzs(h,a,i,l,!1)}const n9t=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"]),r9t=s=>typeof s=="string"&&s.toLowerCase()==="svg";function zzs(s,t,n,r){e9t(s,t,void 0,r);for(const a in t.attrs)s.setAttribute(n9t.has(a)?a:pst(a),t.attrs[a])}function a9t(s,t,n){const r=Nst(s,t,n);for(const a in s)if(ub(s[a])||ub(t[a])){const i=tK.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class Bzs extends YBt{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=d0}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(sK.has(n)){const r=BBt(n);return r&&r.default||0}return n=n9t.has(n)?n:pst(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return a9t(t,n,r)}build(t,n,r){s9t(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){zzs(t,n,r,a)}mount(t){this.isSVGTag=r9t(t.tagName),super.mount(t)}}const $zs=wst.length;function i9t(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?i9t(s.parent)||{}:{};return s.props.initial!==void 0&&(n.initial=s.props.initial),n}const t={};for(let n=0;n<$zs;n++){const r=wst[n],a=s.props[r];(Jte(a)||a===!1)&&(t[r]=a)}return t}function o9t(s,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==s.length)return!1;for(let r=0;rPromise.all(t.map(({animation:n,options:r})=>$8s(s,n,r)))}function Hzs(s){let t=Vzs(s),n=S0t(),r=!0,a=!1;const i=d=>(u,h)=>{var f;const m=a7(s,h,d==="exit"?(f=s.presenceContext)==null?void 0:f.custom:void 0);if(m){const{transition:g,transitionEnd:x,...v}=m;u={...u,...v,...x}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=i9t(s.parent)||{},m=[],f=new Set;let g={},x=1/0;for(let y=0;yx&&A,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 le=s.getValue(ae);le&&(le.liveStyle=!1)};for(const ae in V){const le=U[ae],re=W[ae];if(g.hasOwnProperty(ae))continue;let te=!1;mGe(le)&&mGe(re)?te=!o9t(le,re)||P:te=le!==re,te?le!=null?G(ae):f.add(ae):le!==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 Z=I&&P;R&&(!Z||D)&&m.push(...O.map(ae=>{const le={type:b};if(typeof ae=="string"&&(r||a)&&!Z&&s.manuallyAnimateOnMount&&s.parent){const{parent:re}=s,te=a7(re,ae);if(re.enteringChildren&&te){const{delayChildren:J}=te.transition||{};le.delay=MBt(re.enteringChildren,s,J)}}return{animation:ae,options:le}}))}if(f.size){const y={};if(typeof u.initial!="boolean"){const b=a7(s,Array.isArray(u.initial)?u.initial[0]:u.initial);b&&b.transition&&(y.transition=b.transition)}f.forEach(b=>{const w=s.getBaseTarget(b),S=s.getValue(b);S&&(S.liveStyle=!0),y[b]=w??null}),m.push({animation:y})}let v=!!m.length;return r&&(u.initial===!1||u.initial===u.animate)&&!s.manuallyAnimateOnMount&&(v=!1),r=!1,a=!1,v?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=S0t(),a=!0}}}function Gzs(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!o9t(t,s):!1}function dR(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function S0t(){return{animate:dR(!0),whileInView:dR(),whileHover:dR(),whileTap:dR(),whileDrag:dR(),whileFocus:dR(),exit:dR()}}function jGe(s,t){s.min=t.min,s.max=t.max}function Qk(s,t){jGe(s.x,t.x),jGe(s.y,t.y)}function C0t(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const l9t=1e-4,Wzs=1-l9t,Kzs=1+l9t,c9t=.01,Yzs=0-c9t,Zzs=0+c9t;function p_(s){return s.max-s.min}function Xzs(s,t,n){return Math.abs(s-t)<=n}function A0t(s,t,n,r=.5){s.origin=r,s.originPoint=jf(t.min,t.max,s.origin),s.scale=p_(n)/p_(t),s.translate=jf(n.min,n.max,s.origin)-s.originPoint,(s.scale>=Wzs&&s.scale<=Kzs||isNaN(s.scale))&&(s.scale=1),(s.translate>=Yzs&&s.translate<=Zzs||isNaN(s.translate))&&(s.translate=0)}function gee(s,t,n,r){A0t(s.x,t.x,n.x,r?r.originX:void 0),A0t(s.y,t.y,n.y,r?r.originY:void 0)}function E0t(s,t,n,r=0){const a=r?jf(n.min,n.max,r):n.min;s.min=a+t.min,s.max=s.min+p_(t)}function Qzs(s,t,n,r){E0t(s.x,t.x,n.x,r==null?void 0:r.x),E0t(s.y,t.y,n.y,r==null?void 0:r.y)}function T0t(s,t,n,r=0){const a=r?jf(n.min,n.max,r):n.min;s.min=t.min-a,s.max=s.min+p_(t)}function FEe(s,t,n,r){T0t(s.x,t.x,n.x,r==null?void 0:r.x),T0t(s.y,t.y,n.y,r==null?void 0:r.y)}function M0t(s,t,n,r,a){return s-=t,s=DEe(s,1/n,r),a!==void 0&&(s=DEe(s,1/a,r)),s}function Jzs(s,t=0,n=1,r=.5,a,i=s,l=s){if(D4.test(t)&&(t=parseFloat(t),t=jf(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=jf(i.min,i.max,r);s===i&&(o-=t),s.min=M0t(s.min,t,n,o,a),s.max=M0t(s.max,t,n,o,a)}function P0t(s,t,[n,r,a],i,l){Jzs(s,t[n],t[r],t[a],t.scale,i,l)}const e7s=["x","scaleX","originX"],t7s=["y","scaleY","originY"];function I0t(s,t,n,r){P0t(s.x,t,e7s,n?n.x:void 0,r?r.x:void 0),P0t(s.y,t,t7s,n?n.y:void 0,r?r.y:void 0)}function L0t(s){return s.translate===0&&s.scale===1}function d9t(s){return L0t(s.x)&&L0t(s.y)}function R0t(s,t){return s.min===t.min&&s.max===t.max}function s7s(s,t){return R0t(s.x,t.x)&&R0t(s.y,t.y)}function D0t(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function u9t(s,t){return D0t(s.x,t.x)&&D0t(s.y,t.y)}function F0t(s){return p_(s.x)/p_(s.y)}function O0t(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function b5(s){return[s("x"),s("y")]}function n7s(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 r7s=gst.length,z0t=s=>typeof s=="string"?parseFloat(s):s,B0t=s=>typeof s=="number"||Bo.test(s);function a7s(s,t,n,r,a,i){a?(s.opacity=jf(0,n.opacity??1,i7s(r)),s.opacityExit=jf(t.opacity??1,0,o7s(r))):i&&(s.opacity=jf(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(Xte(s,t,r))}function l7s(s,t,n){const r=ub(s)?s:SG(s);return r.start(mst("",r,t,n)),r.animation}function ese(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n,r)}const c7s=(s,t)=>s.depth-t.depth;class d7s{constructor(){this.children=[],this.isDirty=!1}add(t){tst(this.children,t),this.isDirty=!0}remove(t){EEe(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(c7s),this.isDirty=!1,this.children.forEach(t)}}function u7s(s,t){const n=f_.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(EL(r),s(i-t))};return kf.setup(r,!0),()=>EL(r)}function t3e(s){return ub(s)?s.get():s}class h7s{constructor(){this.members=[]}add(t){tst(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&&(EEe(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(EEe(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 s3e={hasAnimatedSinceResize:!0,hasEverUpdated:!1},y7e=["","X","Y","Z"],m7s=1e3;let f7s=0;function v7e(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function m9t(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=DBt(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(n,"transform",kf,!(a||i))}const{parent:r}=s;r&&!r.hasCheckedOptimisedAppear&&m9t(r)}function f9t({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=f7s++,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(x7s),this.nodes.forEach(j7s),this.nodes.forEach(N7s),this.nodes.forEach(y7s)},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;kf.read(()=>{h=window.innerWidth}),s(l,()=>{const f=window.innerWidth;f!==h&&(h=f,this.root.updateBlockedByResize=!0,u&&u(),u=u7s(m,250),s3e.hasAnimatedSinceResize&&(s3e.hasAnimatedSinceResize=!1,this.nodes.forEach(V0t)))})}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()||E7s,{onLayoutAnimationStart:x,onLayoutAnimationComplete:v}=d.getProps(),y=!this.targetLayout||!u9t(this.targetLayout,f),b=!h&&m;if(this.options.layoutRoot||this.resumeFrom||b||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...hst(g,"layout"),onPlay:x,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(u,b,w.path)}else h||V0t(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(),EL(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(k7s),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&&m9t(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&&!p_(this.snapshot.measuredBox.x)&&!p_(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=A==null?void 0:A(I);P?(m.x.translate=P.x,m.x.scale=jf(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=jf(l.y.scale,1,I),m.y.origin=l.y.origin,m.y.originPoint=l.y.originPoint):(H0t(m.x,l.x,I),H0t(m.y,l.y,I)),this.setTargetDelta(m),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(FEe(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),C7s(this.relativeTarget,this.relativeTargetOrigin,f,I),S&&s7s(this.relativeTarget,S)&&(this.isProjectionDirty=!1),S||(S=d0()),Qk(S,this.relativeTarget)),v&&(this.animationValues=h,a7s(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&&(EL(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=kf.update(()=>{s3e.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=SG(0)),this.motionValue.jump(0,!1),this.currentAnimation=l7s(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(m7s),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&&p9t(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||d0();const h=p_(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const m=p_(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+m}Qk(o,c),e3e(o,u),gee(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new h7s),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&&v7e("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(U0t),this.root.sharedNodes.clear()}}}function p7s(s){s.updateLayout()}function g7s(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")b5(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],f=p_(m);m.min=r[h].min,m.max=m.min+f});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";jGe(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else p9t(i,t.layoutBox,r)&&b5(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],f=p_(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=WU();gee(o,r,t.layoutBox);const c=WU();l?gee(c,s.applyTransform(a,!0),t.measuredBox):gee(c,r,t.layoutBox);const d=!d9t(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=d0();FEe(x,t.layoutBox,m.layoutBox,g);const v=d0();FEe(v,r,f.layoutBox,g),u9t(x,v)||(u=!0),h.options.layoutRoot&&(s.relativeTarget=v,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 x7s(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 y7s(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function v7s(s){s.clearSnapshot()}function U0t(s){s.clearMeasurements()}function b7s(s){s.isLayoutDirty=!0,s.updateLayout()}function q0t(s){s.isLayoutDirty=!1}function _7s(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 V0t(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function j7s(s){s.resolveTargetDelta()}function N7s(s){s.calcProjection()}function k7s(s){s.resetSkewAndRotation()}function S7s(s){s.removeLeadSnapshot()}function H0t(s,t,n){s.translate=jf(t.translate,0,n),s.scale=jf(t.scale,1,n),s.origin=t.origin,s.originPoint=t.originPoint}function G0t(s,t,n,r){s.min=jf(t.min,n.min,r),s.max=jf(t.max,n.max,r)}function C7s(s,t,n,r){G0t(s.x,t.x,n.x,r),G0t(s.y,t.y,n.y,r)}function A7s(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const E7s={duration:.45,ease:[.4,0,.1,1]},W0t=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),K0t=W0t("applewebkit/")&&!W0t("chrome/")?Math.round:ek;function Y0t(s){s.min=K0t(s.min),s.max=K0t(s.max)}function T7s(s){Y0t(s.x),Y0t(s.y)}function p9t(s,t,n){return s==="position"||s==="preserve-aspect"&&!Xzs(F0t(t),F0t(n),.2)}function M7s(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const P7s=f9t({attachResizeListener:(s,t)=>ese(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}),b7e={current:void 0},g9t=f9t({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!b7e.current){const s=new P7s({});s.mount(window),s.setOptions({layoutScroll:!0}),b7e.current=s}return b7e.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),kst=j.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function Z0t(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function I7s(...s){return t=>{let n=!1;const r=s.map(a=>{const i=Z0t(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:v,right:y,bottom:b,direction:w}=c.current;if(t||i===!1||!o.current||!f||!g)return;const S=w==="rtl",A=n==="left"?S?`right: ${y}`:`left: ${v}`:S?`left: ${v}`:`right: ${y}`,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; ${A}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(R7s,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:j.cloneElement(s,{ref:h})})}const F7s=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=Jtt(O7s),h=j.useId(),m=j.useRef(n),f=j.useRef(r);est(()=>{m.current=n,f.current=r});let g=!0,x=j.useMemo(()=>(g=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:v=>{u.set(v,!0);for(const y of u.values())if(!y)return;r&&r()},register:v=>(u.set(v,!1),()=>{var y;u.delete(v),!m.current&&!u.size&&((y=f.current)==null||y.call(f))})}),[n,u,r]);return i&&g&&(x={...x}),j.useMemo(()=>{u.forEach((v,y)=>u.set(y,!1))},[n]),j.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(D7s,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(HLe.Provider,{value:x,children:s})};function O7s(){return new Map}function x9t(s=!0){const t=j.useContext(HLe);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 Fce=s=>s.key||"";function X0t(s){const t=[];return j.Children.forEach(s,n=>{j.isValidElement(n)&&t.push(n)}),t}const nK=({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]=x9t(l),m=j.useMemo(()=>X0t(s),[s]),f=l&&!u?[]:m.map(Fce),g=j.useRef(!0),x=j.useRef(m),v=Jtt(()=>new Map),y=j.useRef(new Set),[b,w]=j.useState(m),[S,A]=j.useState(m);est(()=>{g.current=!1,x.current=m;for(let P=0;P{const R=Fce(P),D=l&&!u?!1:m===S||f.includes(R),O=()=>{if(y.current.has(R))return;if(v.has(R))y.current.add(R),v.set(R,!0);else return;let U=!0;v.forEach(W=>{W||(U=!1)}),U&&(I==null||I(),A(x.current),l&&(h==null||h()),r&&r())};return e.jsx(F7s,{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)})})},y9t=j.createContext({strict:!1}),Q0t={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 J0t=!1;function z7s(){if(J0t)return;const s={};for(const t in Q0t)s[t]={isEnabled:n=>Q0t[t].some(r=>!!n[r])};KBt(s),J0t=!0}function v9t(){return z7s(),jzs()}function B7s(s){const t=v9t();for(const n in s)t[n]={...t[n],...s[n]};KBt(t)}const $7s=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 OEe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||$7s.has(s)}let b9t=s=>!OEe(s);function U7s(s){typeof s=="function"&&(b9t=t=>t.startsWith("on")?!OEe(t):s(t))}try{U7s(require("@emotion/is-prop-valid").default)}catch{}function q7s(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||ub(s[a])||(b9t(a)||n===!0&&OEe(a)||!t&&!OEe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const ZLe=j.createContext({});function V7s(s,t){if(YLe(s)){const{initial:n,animate:r}=s;return{initial:n===!1||Jte(n)?n:void 0,animate:Jte(r)?r:void 0}}return s.inherit!==!1?t:{}}function H7s(s){const{initial:t,animate:n}=V7s(s,j.useContext(ZLe));return j.useMemo(()=>({initial:t,animate:n}),[evt(t),evt(n)])}function evt(s){return Array.isArray(s)?s.join(" "):s}const Sst=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function _9t(s,t,n){for(const r in t)!ub(t[r])&&!t9t(r,n)&&(s[r]=t[r])}function G7s({transformTemplate:s},t){return j.useMemo(()=>{const n=Sst();return jst(n,t,s),Object.assign({},n.vars,n.style)},[t])}function W7s(s,t){const n=s.style||{},r={};return _9t(r,n,s),Object.assign(r,G7s(s,t)),r}function K7s(s,t){const n={},r=W7s(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 w9t=()=>({...Sst(),attrs:{}});function Y7s(s,t,n,r){const a=j.useMemo(()=>{const i=w9t();return s9t(i,t,r9t(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};_9t(i,s.style,s),a.style={...i,...a.style}}return a}const Z7s=["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 Cst(s){return typeof s!="string"||s.includes("-")?!1:!!(Z7s.indexOf(s)>-1||/[A-Z]/u.test(s))}function X7s(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??Cst(s)?Y7s:K7s)(t,r,a,s),d=q7s(t,typeof s=="string",i),u=s!==j.Fragment?{...d,...c,ref:n}:{},{children:h}=t,m=j.useMemo(()=>ub(h)?h.get():h,[h]);return j.createElement(s,{...u,children:m})}function Q7s({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:J7s(n,r,a,s),renderState:t()}}function J7s(s,t,n,r){const a={},i=r(s,{});for(const m in i)a[m]=t3e(i[m]);let{initial:l,animate:o}=s;const c=YLe(s),d=GBt(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"&&!KLe(h)){const m=Array.isArray(h)?h:[h];for(let f=0;f(t,n)=>{const r=j.useContext(ZLe),a=j.useContext(HLe),i=()=>Q7s(s,t,r,a);return n?i():Jtt(i)},eBs=j9t({scrapeMotionValuesFromProps:Nst,createRenderState:Sst}),tBs=j9t({scrapeMotionValuesFromProps:a9t,createRenderState:w9t}),sBs=Symbol.for("motionComponentSymbol");function nBs(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 N9t=j.createContext({});function mU(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function rBs(s,t,n,r,a,i){var w,S;const{visualElement:l}=j.useContext(ZLe),o=j.useContext(y9t),c=j.useContext(HLe),d=j.useContext(kst),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(N9t);g&&!g.projection&&a&&(g.type==="html"||g.type==="svg")&&aBs(m.current,n,a,x);const v=j.useRef(!1);j.useInsertionEffect(()=>{g&&v.current&&g.update(n,c)});const y=n[RBt],b=j.useRef(!!y&&typeof window<"u"&&!((w=window.MotionHandoffIsComplete)!=null&&w.call(window,y))&&((S=window.MotionHasOptimisedAnimation)==null?void 0:S.call(window,y)));return est(()=>{f.current=!0,g&&(v.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 A;(A=window.MotionHandoffMarkAsComplete)==null||A.call(window,y)}),b.current=!1),g.enteringChildren=void 0)}),g}function aBs(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:k9t(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&mU(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function k9t(s){if(s)return s.options.allowProjection!==!1?s.projection:k9t(s.parent)}function _7e(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&B7s(r);const i=n?n==="svg":Cst(s),l=i?tBs:eBs;function o(d,u){let h;const m={...j.useContext(kst),...d,layoutId:iBs(d)},{isStatic:f}=m,g=H7s(d),x=l(d,f);if(!f&&typeof window<"u"){oBs();const v=lBs(m);h=v.MeasureLayout,g.visualElement=rBs(s,x,m,a,v.ProjectionNode,i)}return e.jsxs(ZLe.Provider,{value:g,children:[h&&g.visualElement?e.jsx(h,{visualElement:g.visualElement,...m}):null,X7s(s,d,nBs(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[sBs]=s,c}function iBs({layoutId:s}){const t=j.useContext(Qtt).id;return t&&s!==void 0?t+"-"+s:s}function oBs(s,t){j.useContext(y9t).strict}function lBs(s){const t=v9t(),{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 cBs(s,t){if(typeof Proxy>"u")return _7e;const n=new Map,r=(i,l)=>_7e(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,_7e(l,void 0,s,t)),n.get(l))})}const dBs=(s,t)=>t.isSVG??Cst(s)?new Bzs(t):new Lzs(t,{allowProjection:s!==j.Fragment});class uBs extends a6{constructor(t){super(t),t.animationState||(t.animationState=Hzs(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();KLe(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 hBs=0;class mBs extends a6{constructor(){super(...arguments),this.id=hBs++,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=a7(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 fBs={animation:{Feature:uBs},exit:{Feature:mBs}};function Hae(s){return{point:{x:s.pageX,y:s.pageY}}}const pBs=s=>t=>vst(t)&&s(t,Hae(t));function xee(s,t,n,r){return ese(s,t,pBs(n),r)}const S9t=({current:s})=>s?s.ownerDocument.defaultView:null,tvt=(s,t)=>Math.abs(s-t);function gBs(s,t){const n=tvt(s.x,t.x),r=tvt(s.y,t.y);return Math.sqrt(n**2+r**2)}const svt=new Set(["auto","scroll"]);class C9t{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=Oce(this.lastRawMoveEventInfo,this.transformPagePoint));const g=w7e(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,v=gBs(g.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!v)return;const{point:y}=g,{timestamp:b}=sb;this.history.push({...y,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=Oce(x,this.transformPagePoint),kf.update(this.updatePoint,!0)},this.handlePointerUp=(g,x)=>{this.end();const{onEnd:v,onSessionEnd:y,resumeAnimation:b}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=w7e(g.type==="pointercancel"?this.lastMoveEventInfo:Oce(x,this.transformPagePoint),this.history);this.startEvent&&v&&v(g,w),y&&y(g,w)},!vst(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=Hae(t),d=Oce(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=sb;this.history=[{...u,timestamp:h}];const{onSessionStart:m}=n;m&&m(t,w7e(d,this.history));const f={passive:!0,capture:!0};this.removeListeners=Uae(xee(this.contextWindow,"pointermove",this.handlePointerMove,f),xee(this.contextWindow,"pointerup",this.handlePointerUp,f),xee(this.contextWindow,"pointercancel",this.handlePointerUp,f)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(svt.has(r.overflowX)||svt.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),kf.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),EL(this.updatePoint)}}function Oce(s,t){return t?{point:t(s.point)}:s}function nvt(s,t){return{x:s.x-t.x,y:s.y-t.y}}function w7e({point:s},t){return{point:s,delta:nvt(s,A9t(t)),offset:nvt(s,xBs(t)),velocity:yBs(t,.1)}}function xBs(s){return s[0]}function A9t(s){return s[s.length-1]}function yBs(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=A9t(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>h2(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>h2(t)*2&&(r=s[1]);const i=BN(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?jf(n,s,r.max):Math.min(s,n)),s}function rvt(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 bBs(s,{top:t,left:n,bottom:r,right:a}){return{x:rvt(s.x,n,a),y:rvt(s.y,t,r)}}function avt(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=Xte(t.min,t.max-r,s.min):r>a&&(n=Xte(s.min,s.max-a,t.min)),W4(0,1,n)}function jBs(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 NGe=.35;function NBs(s=NGe){return s===!1?s=0:s===!0&&(s=NGe),{x:ivt(s,"left","right"),y:ivt(s,"top","bottom")}}function ivt(s,t,n){return{min:ovt(s,t),max:ovt(s,n)}}function ovt(s,t){return typeof s=="number"?s:s[t]||0}const kBs=new WeakMap;class SBs{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=d0(),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(Hae(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=J8s(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),b5(y=>{let b=this.getAxisMotionValue(y).get()||0;if(D4.test(b)){const{projection:w}=this.visualElement;if(w&&w.layout){const S=w.layout.layoutBox[y];S&&(b=p_(S)*(parseFloat(b)/100))}}this.originPoint[y]=b}),x&&kf.update(()=>x(h,m),!1,!0),fGe(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},o=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:x,onDrag:v}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:y}=m;if(g&&this.currentDirection===null){this.currentDirection=ABs(y),this.currentDirection!==null&&x&&x(this.currentDirection);return}this.updateAxis("x",m.point,y),this.updateAxis("y",m.point,y),this.visualElement.render(),v&&kf.update(()=>v(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 C9t(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:S9t(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&&kf.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||!zce(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&&mU(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=bBs(r.layoutBox,t):this.constraints=!1,this.elastic=NBs(n),a!==this.constraints&&!mU(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&b5(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=jBs(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!mU(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=Azs(r,a.root,this.visualElement.getTransformPagePoint());let l=_Bs(a.layout.layoutBox,i);if(n){const o=n(kzs(l));this.hasMutatedConstraints=!!o,o&&(l=ZBt(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=b5(u=>{if(!zce(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 fGe(this.visualElement,t),r.start(mst(t,r,0,n,this.visualElement,!1))}stopAnimation(){b5(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){b5(n=>{const{drag:r}=this.getProps();if(!zce(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]-jf(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!mU(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};b5(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(),b5(l=>{if(!zce(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(jf(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;kBs.set(this.visualElement,this);const t=this.visualElement.current,n=xee(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),m=d.target,f=m!==t&&azs(m);u&&h&&!f&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();mU(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=CBs(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),kf.read(a);const o=ese(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(b5(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=NGe,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function lvt(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function CBs(s,t,n){const r=p0t(s,lvt(n)),a=p0t(t,lvt(n));return()=>{r(),a()}}function zce(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function ABs(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class EBs extends a6{constructor(t){super(t),this.removeGroupControls=ek,this.removeListeners=ek,this.controls=new SBs(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ek}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 j7e=s=>(t,n)=>{s&&kf.update(()=>s(t,n),!1,!0)};class TBs extends a6{constructor(){super(...arguments),this.removePointerDownListener=ek}onPointerDown(t){this.session=new C9t(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:S9t(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:j7e(t),onStart:j7e(n),onMove:j7e(r),onEnd:(i,l)=>{delete this.session,a&&kf.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=xee(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 N7e=!1;class MBs 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),N7e&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),s3e.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}),N7e=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||kf.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(),yst.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;N7e=!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 E9t(s){const[t,n]=x9t(),r=j.useContext(Qtt);return e.jsx(MBs,{...s,layoutGroup:r,switchLayoutGroup:j.useContext(N9t),isPresent:t,safeToRemove:n})}const PBs={pan:{Feature:TBs},drag:{Feature:EBs,ProjectionNode:g9t,MeasureLayout:E9t}};function cvt(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&&kf.postRender(()=>i(t,Hae(t)))}class IBs extends a6{mount(){const{current:t}=this.node;t&&(this.unmount=tzs(t,(n,r)=>(cvt(this.node,r,"Start"),a=>cvt(this.node,a,"End"))))}unmount(){}}class LBs extends a6{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=Uae(ese(this.node.current,"focus",()=>this.onFocus()),ese(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function dvt(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&&kf.postRender(()=>i(t,Hae(t)))}class RBs extends a6{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=ozs(t,(a,i)=>(dvt(this.node,i,"Start"),(l,{success:o})=>dvt(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const kGe=new WeakMap,k7e=new WeakMap,DBs=s=>{const t=kGe.get(s.target);t&&t(s)},FBs=s=>{s.forEach(DBs)};function OBs({root:s,...t}){const n=s||document;k7e.has(n)||k7e.set(n,{});const r=k7e.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(FBs,{root:s,...t})),r[a]}function zBs(s,t,n){const r=OBs(t);return kGe.set(s,n),r.observe(s),()=>{kGe.delete(s),r.unobserve(s)}}const BBs={some:0,all:1};class $Bs extends a6{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:BBs[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=zBs(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(UBs(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function UBs({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const qBs={inView:{Feature:$Bs},tap:{Feature:RBs},focus:{Feature:LBs},hover:{Feature:IBs}},VBs={layout:{ProjectionNode:g9t,MeasureLayout:E9t}},HBs={...fBs,...qBs,...PBs,...VBs},Fr=cBs(HBs,dBs),GBs={some:0,all:1};function WBs(s,t,{root:n,margin:r,amount:a="some"}={}){const i=xst(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:GBs[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function KBs(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 WBs(s.current,c,d)},[t,s,n,a,r]),l}function YBs(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 uvt(s){return s.visitor_intent==="buying"&&!s.has_agent}function ZBs({token:s}={}){var f;const t=Wi(),n=s||t.token,{data:r,isLoading:a,isError:i}=KFs(n);Zt();const l=(f=r==null?void 0:r.open_houses)==null?void 0:f.id,{data:o}=st({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(uvt).length)||0,m=g=>{if(!g)return"";const[x,v]=g.split(":"),y=parseInt(x);return`${y>12?y-12:y||12}:${v} ${y>=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(Yn,{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(sh,{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:Js(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(go,{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(nK,{children:o.map((g,x)=>{var b;const v=YBs(g.visitor_intent),y=uvt(g);return e.jsxs(Fr.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 ${y?"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 ${y?"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||""]}),y&&e.jsx($e,{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($e,{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($e,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${v.color}`,children:[v.emoji," ",v.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:Js(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(bb,{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 XBs(){const t=qu().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(ZBs,{token:n})}if(t.startsWith("rsvp/")){const n=t.slice(5);if(n)return e.jsx(W7t,{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(G7t,{slug:t})}function QBs({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(Fr.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(Fr.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(Fr.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(ui,{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(pn,{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(Ah,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function T9t({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=ck(a,new Date);if(R4(a)&&!bv(a))return null;const o=bv(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(Fr.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(Fr.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 M9t({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(Fr.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 kh(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 hvt(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 JBs=[{key:"contract_date",label:"Contract Accepted",icon:GN},{key:"earnest_money_due_date",label:"Earnest Money",icon:su},{key:"inspection_date",label:"Inspection",icon:Kr},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:Qr},{key:"appraisal_date",label:"Appraisal",icon:va},{key:"loan_approval_date",label:"Loan Approval",icon:Dq},{key:"title_docs_due_date",label:"Title & Disclosures",icon:Qr},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:VI},{key:"target_close_date",label:"Target Close",icon:Ea}];function e9s(s,t){const n=Js(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 t9s(s,t){const n=Js(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 I9t({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=JBs.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 v=kh(g);if(x==="google")window.open(e9s(f,v),"_blank");else{const y=t9s(f,v),b=document.createElement("a");b.href=y,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:v})=>{const y=kh(g),b=R4(y)&&!bv(y),w=bv(y),S=!b&&!w,A=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(ma,{className:"w-3 h-3",style:{color:"hsl(var(--portal-surface))"}}):e.jsx(v,{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:Js(y,"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:A})]}),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(vv,{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 L9t({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(Qr,{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(ji,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function R9t({slug:s,wrapper:t}){const n=Zn(),[r,a]=j.useState(null),{data:i=[]}=st({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){ne.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(Ct,{className:"w-4 h-4 animate-spin",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(_f,{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(Vr,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}}):e.jsx(ca,{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 D9t({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(Dy,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(zy,{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:Js(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 rK=[{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"}],s9s=[{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 n9s(s){return st({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 r9s(){const s=Sa(),{brokerageId:t}=_s();return st({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 a9s(){const s=Zt();return mt({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 F9t(){const s=Zt();return mt({mutationFn:async t=>{const{error:n}=await q.from("vendors").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function i9s(){const s=Sa(),t=Zt();return mt({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 O9t(s){return st({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 mvt(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 z9t(s,t){return st({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 B9t({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=O9t({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);mvt({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(cl,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(pn,{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(Ea,{className:"w-3.5 h-3.5"})}].filter(A=>A.action!==b.action_type).map(A=>{const E=d(b,A.action);return!E||E===w?null:e.jsxs("button",{onClick:()=>{mvt({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:A.action}),window.open(E,A.action==="call"||A.action==="email"?"_self":"_blank")},className:"inline-flex items-center gap-1 text-slate-500 hover:text-slate-700 hover:underline",title:A.label,children:[A.icon,e.jsx("span",{className:"text-xs",children:A.label})]},A.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(Ea,{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(pn,{className:"w-3.5 h-3.5"});case"website":return e.jsx(cl,{className:"w-3.5 h-3.5"})}},g=b=>{var w;return((w=rK.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(wn,{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"})]})]}),v=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(je,{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))}),v]});const y=o.reduce((b,w)=>((b[w.category]=b[w.category]||[]).push(w),b),{});return e.jsxs(je,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[x,e.jsx("div",{className:"space-y-4",children:Object.entries(y).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))}),v]})}function o9s(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 l9s(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 $9t({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=o9s(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)},v=()=>{f("share_sms");const E=encodeURIComponent(g());window.location.href=`sms:?&body=${E}`},y=()=>{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?l9s(c):null,A=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(wn,{className:"w-4 h-4 text-[#406E71]"}),e.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",i||"your agent"]})]})}),e.jsx("div",{className:"aspect-video bg-slate-900",children:A?e.jsx("video",{src: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(dl,{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(Qa,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[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(Ah,{className:"w-3.5 h-3.5"}),"Text"]}),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(pn,{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(ma,{className:"w-3.5 h-3.5"}):e.jsx(Za,{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(Qa,{className:"w-4 h-4 text-slate-400"})]})})]})}function U9t(s){return st({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 q9t(){const s=Zt();return mt({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 c9s(){const s=Zt();return mt({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 V9t(){const s=Sa();return st({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 H9t({portalId:s,clientName:t,agentName:n,agentAvatar:r,deviceFingerprint:a}){const{data:i,isLoading:l}=U9t(s),o=q9t(),[c,d]=j.useState(""),u=`portal_msg_name_${s}`,[h,m]=j.useState(()=>localStorage.getItem(u)||t||""),f=j.useRef(null);j.useEffect(()=>{var v;(v=f.current)==null||v.scrollIntoView({block:"nearest"})},[i==null?void 0:i.length]);const g=async()=>{const v=c.trim();if(!v)return;const y=(h||t||"").trim();if(!y){ne.error("Please add your name first");return}try{localStorage.setItem(u,y),await o.mutateAsync({portalId:s,senderType:"client",senderName:y,body:v,deviceFingerprint:a,portalUrl:window.location.href}),d(""),ne.success("Message sent")}catch(b){ne.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(no,{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(Ct,{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(v=>{const y=v.sender_type==="agent";return e.jsx("div",{className:`flex ${y?"justify-start":"justify-end"}`,children:e.jsxs("div",{className:"max-w-[85%] rounded-2xl px-4 py-3",style:{background:y?"hsl(var(--portal-surface-2))":"hsl(var(--portal-gold) / 0.12)",border:`1px solid ${y?"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:[y&&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:[y?n||"Your agent":v.sender_name||"You"," ·"," ",Js(new Date(v.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:v.body})]})},v.id)}),e.jsx("div",{ref:f})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[!t&&e.jsx("input",{value:h,onChange:v=>m(v.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:v=>d(v.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(Ct,{className:"w-4 h-4 animate-spin"}):e.jsx(Zr,{className:"w-4 h-4"}),"Send message"]})]})]})}function d9s(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function u9s(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 h9s={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. 🎉"}},G9t=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function XLe(s){return G9t.map(t=>{if(t==="Active")return{key:"Active",label:d9s(s),description:u9s(s)};const n=h9s[t];return{key:t,label:n.label,description:n.description}})}function zEe(s){if(!s)return 0;const t=G9t.indexOf(s);return t>=0?t:0}function m9s({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var G,Z,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,v=n==null?void 0:n.stage_mapping;let y=XLe(x);v&&v.length>0&&(y=v.map((ae,le)=>{var re,te;return{key:`custom-${le}`,label:ae.label||((re=y[le])==null?void 0:re.label)||`Stage ${le+1}`,description:ae.description||((te=y[le])==null?void 0:te.description)||"",video_url:ae.video_url||void 0}}));const b=v&&v.length>0?Math.min(zEe(f==null?void 0:f.name),y.length-1):zEe(f==null?void 0:f.name),w=y[b],S=w==null?void 0:w.video_url,A=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=(Z=t==null?void 0:t.deal_pipeline)==null?void 0:Z.deal_type,D=ae=>ae==="listing"?"Your Sale":ae==="buy-side"?"Your Purchase":"Transaction",O=y.length>1?Math.round((b+1)/y.length*100):0,{data:U=[]}=O9t({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(Fr.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(Tf,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),e.jsxs(Fr.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(ui,{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(f9s,{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 ",y.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 le=ae==="primary"?P:R,re=r===ae;return e.jsx("button",{onClick:()=>a(ae),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:re?"hsl(var(--portal-surface-3))":"transparent",color:re?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:re?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:D(le)},ae)})}),e.jsxs(Fr.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(JC,{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(S7e,{href:`tel:${i.phone}`,icon:Da,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(S7e,{href:`sms:${i.phone}`,icon:Ah,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(S7e,{href:`mailto:${i.email}`,icon:pn,label:"Email",sub:i.email})]})]}),e.jsxs(JC,{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(C7e,{icon:Ea,label:"Target close",value:fvt(m.target_close_date)}),(m==null?void 0:m.contract_date)&&e.jsx(C7e,{icon:ca,label:"Under contract",value:fvt(m.contract_date)}),e.jsx(C7e,{icon:wl,label:"Progress",value:`${O}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[A&&e.jsx($9t,{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(T9t,{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(JC,{children:e.jsx(P9t,{currentStage:w,nextStepText:n.next_step_text,nextStepVideoUrl:S||n.next_step_video_url})}),e.jsx(JC,{children:e.jsx(M9t,{journeyStages:y,currentIndex:b})}),o&&o.length>0&&e.jsx(JC,{children:e.jsx(D9t,{updates:o})}),(n==null?void 0:n.id)&&e.jsx(JC,{children:e.jsx(H9t,{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(JC,{children:e.jsx(I9t,{deal:m,portal:n})}),(n==null?void 0:n.slug)&&e.jsx(R9t,{slug:n.slug,wrapper:ae=>e.jsx(JC,{children:ae})}),c&&c.length>0&&e.jsx(JC,{children:e.jsx(L9t,{documents:c})}),W&&e.jsx(JC,{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(eV,{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(wl,{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(B9t,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:f==null?void 0:f.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function JC({children:s}){return e.jsx(Fr.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 S7e({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 C7e({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 f9s({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(Fr.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 fvt(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 p9s({portal:s,dealData:t,agentProfile:n,customQuestions:r,deviceFingerprint:a,onComplete:i}){var v,y;const[l,o]=j.useState({first_name:((v=s.client_name)==null?void 0:v.split(" ")[0])||"",last_name:((y=s.client_name)==null?void 0:y.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=mt({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),ne.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(ui,{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 g9s(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 W9t(){const s=Sa();return st({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 x9s(s){return st({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 y9s(){const s=Sa(),t=Zt();return mt({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 K9t(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 st({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 b9s(s){return st({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 Y9t({slug:s}){var le,re,te,J,ce,ve;const[t,n]=j.useState(!1),[r,a]=j.useState("primary"),[i]=j.useState(()=>{const fe=`portal_fp_${s}`;let ue=localStorage.getItem(fe);return ue||(ue=localStorage.getItem("portal_fp"),ue?localStorage.setItem(fe,ue):(ue=crypto.randomUUID(),localStorage.setItem(fe,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}=b9s(d),h=(le=l==null?void 0:l.deal_pipeline)==null?void 0:le.owner_user_id,{data:m}=st({queryKey:["portal-stages",h],queryFn:async()=>{const{data:fe,error:ue}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(ue)throw ue;return fe},enabled:!!h}),{data:f}=st({queryKey:["portal-agent",h],queryFn:async()=>{const{data:fe,error:ue}=await q.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(ue)throw ue;return fe},enabled:!!h}),{data:g}=x9s(h),x=r==="linked"&&u?u:l,v=x==null?void 0:x.id,y=g9s(g,x==null?void 0:x.branding_override),b=y.portal_theme==="azure"?"azure":"noir";j.useEffect(()=>{const fe=`portal-theme-${b}`;return document.body.classList.add(fe),()=>document.body.classList.remove(fe)},[b]);const{data:w}=st({queryKey:["portal-updates-public",v],queryFn:async()=>{const{data:fe,error:ue}=await q.from("portal_updates").select("*").eq("portal_id",v).order("created_at",{ascending:!1});if(ue)throw ue;return fe},enabled:!!v}),S=(re=x==null?void 0:x.deal_pipeline)==null?void 0:re.id,{data:A}=st({queryKey:["portal-documents",S],queryFn:async()=>{const{data:fe,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 fe},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}=st({queryKey:["portal-onboarding-check",E,i],queryFn:async()=>{const{data:fe,error:ue}=await q.from("portal_onboarding_submissions").select("id").eq("portal_id",E).eq("device_fingerprint",i).maybeSingle();if(ue)throw ue;return fe&&I&&localStorage.setItem(I,"1"),fe},enabled:!!E&&!!(l!=null&&l.require_onboarding)&&!P,staleTime:5*60*1e3}),O=!!(l!=null&&l.require_onboarding)&&!P&&!R&&!t,{data:U}=st({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:fe,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 fe},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(Ct,{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(Tf,{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 fe=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(p9s,{portal:l,dealData:fe,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,Z=!!u,X=fe=>fe==="listing"?"Your Sale":fe==="buy-side"?"Your Purchase":"Transaction",ae=fe=>fe==="listing"?e.jsx(va,{className:"w-3.5 h-3.5"}):e.jsx(__,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(m9s,{portal:l,linkedPortal:u,activePortal:x,activeTab:r,onTabChange:a,agentProfile:f,branding:y,updates:w,documents:A})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(QBs,{dealData:x==null?void 0:x.deal_pipeline,agentProfile:f,welcomeMessage:(x==null?void 0:x.welcome_message)||y.welcome_message,isWon:(ve=(ce=x==null?void 0:x.deal_pipeline)==null?void 0:ce.deal_pipeline_stages)==null?void 0:ve.is_won_stage,branding:y}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[Z&&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(fe=>{const ue=r===fe,be=fe==="primary"?V:G;return e.jsxs("button",{onClick:()=>a(fe),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(be),e.jsx("span",{style:{fontSize:"1rem"},children:X(be)})]},fe)})}),e.jsx(_9s,{portal:x,updates:w,documents:A,agentProfile:f}),v&&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(H9t,{portalId:v,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(Tf,{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 _9s({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=XLe(c);d&&d.length>0&&(u=d.map((x,v)=>{var y,b;return{key:`custom-${v}`,label:x.label||((y=u[v])==null?void 0:y.label)||`Stage ${v+1}`,description:x.description||((b=u[v])==null?void 0:b.description)||"",video_url:x.video_url||void 0}}));const h=d&&d.length>0?Math.min(zEe(l==null?void 0:l.name),u.length-1):zEe(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($9t,{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(T9t,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(M9t,{journeyStages:u,currentIndex:h}),m&&e.jsx(P9t,{currentStage:m,nextStepText:s.next_step_text,nextStepVideoUrl:f||s.next_step_video_url}),e.jsx(I9t,{deal:i,portal:s}),(s==null?void 0:s.slug)&&e.jsx(R9t,{slug:s.slug}),n&&n.length>0&&e.jsx(L9t,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(B9t,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(D9t,{updates:t})]})}function Z9t({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,v]=j.useState(""),[y,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:A,isLoading:E,error:I}=st({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}=st({queryKey:["portal-referral-agent",A==null?void 0:A.owner_user_id],queryFn:async()=>{const{data:D}=await q.from("profiles").select("id, name, avatar_url").eq("id",A.owner_user_id).single();return D},enabled:!!(A!=null&&A.owner_user_id)}),R=async D=>{if(D.preventDefault(),!A||!h.trim()){ne.error("Please enter your friend's name");return}if(!f.trim()&&!x.trim()){ne.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:A.id,owner_user_id:A.owner_user_id,referrer_name:o.trim()||A.client_name||null,referrer_email:d.trim()||null,friend_name:h.trim(),friend_email:f.trim()||null,friend_phone:x.trim()||null,friend_interest:y,friend_message:w.trim()||null});if(O)throw O;l(!0)}catch(O){ne.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(xn,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):I||!A||!A.referral_enabled?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx("span",{className:"text-2xl",children:"🔒"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Referral Page Unavailable"}),e.jsx("p",{className:"text-slate-500",children:"This referral link is no longer active."})]})}):i?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-emerald-50 via-teal-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(ma,{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(Va,{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(dl,{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(dl,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:A.referral_cta_headline||"Refer a Friend"}),e.jsxs("p",{className:"text-sm text-white/70",children:["Send ",(P==null?void 0:P.name)||"your agent"," someone you trust."]}),A.referral_reward_text&&e.jsxs("p",{className:"text-xs text-white/60 mt-2",children:["You'll get: ",e.jsx("span",{className:"text-white font-medium",children:A.referral_reward_text})," when they close."]})]})]}),e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-6 relative z-10",children:e.jsxs("form",{onSubmit: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=>v(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 ${y===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:A.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(Ct,{className:"w-4 h-4 animate-spin"}):e.jsx(dl,{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=qu().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(Z9t,{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(Y9t,{slug:t})}function j9s(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 BEe({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(()=>j9s(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 X9t({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(Os,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(Fs,{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($s,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ui,{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(BEe,{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(BEe,{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(su,{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($e,{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(A7e,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(A7e,{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(A7e,{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(Bce,{icon:e.jsx(n2,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(Bce,{icon:e.jsx(C0,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(Bce,{icon:e.jsx(M4,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(Bce,{icon:e.jsx(Ea,{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(K1,{label:"MLS #",value:s.mlsNumber}),e.jsx(K1,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(K1,{label:"Lot Size",value:s.lotSize}),e.jsx(K1,{label:"Garage",value:s.garageSpaces}),e.jsx(K1,{label:"Stories",value:s.stories}),e.jsx(K1,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(K1,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(K1,{label:"Heating",value:s.heating}),e.jsx(K1,{label:"Cooling",value:s.cooling}),e.jsx(K1,{label:"Parking",value:s.parking}),e.jsx(K1,{label:"Elementary",value:s.elementarySchool}),e.jsx(K1,{label:"Middle",value:s.middleSchool}),e.jsx(K1,{label:"High",value:s.highSchool}),e.jsx(K1,{label:"Listed By",value:s.listAgentFullName}),e.jsx(K1,{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 Bce({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 K1({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 A7e({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 $ce({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,v=Math.min(1,x/t);o(Math.round(u+(s-u)*h(v))),v<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 N9s({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:v}=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]),y=w=>`$${w.toLocaleString()}`,b=n>s?(l-s)/(n-s)*100:50;return e.jsxs(je,{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(Zl,{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(Le,{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:y(l)})]}),e.jsxs("div",{className:"relative",children:[e.jsx(bx,{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:y(s)}),e.jsxs("span",{children:["Suggested ",y(t)]}),e.jsx("span",{children:y(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:y(l)}),e.jsxs("span",{className:"text-muted-foreground",children:["Commission (",u,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",y(g)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Closing (",m,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",y(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:["−",y(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(t7,{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:y(v)})]})]}),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 Q9t({tokenOverride:s}={}){var Ie,Fe,Ne,Be,Se,Ae,Ce,qe,ze,Ve,ht,Qe;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,v]=j.useState(""),[y,b]=j.useState(!1),[w,S]=j.useState(!1),[A,E]=j.useState(null),[I,P]=j.useState(null),[R,D]=j.useState(!1),{toast:O}=Bi();j.useEffect(()=>{n&&(async()=>{const{data:at}=await q.from("cmas").select("*").eq("share_token",n).eq("status","shared").maybeSingle();if(!at){u(!1);return}a(at);const[{data:rt},{data:Ke}]=await Promise.all([q.from("cma_comps").select("*").eq("cma_id",at.id).order("position"),q.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",at.agent_id).maybeSingle()]);c((rt||[]).filter(ft=>ft.selected)),l(Ke);const Je=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",Je),await q.from("cma_views").insert({cma_id:at.id,visitor_token:Je,user_agent:navigator.userAgent}),u(!1)})()},[n]);const U=async at=>{if(!r)return;const rt=localStorage.getItem("cma_visitor_token")||"";await q.from("cma_views").insert({cma_id:r.id,visitor_token:rt,reactions:{[at]:!0}}),q.functions.invoke("cma-reply-notify",{body:{shareToken:n,reaction:at,visitorToken:rt}}).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 at=localStorage.getItem("cma_visitor_token")||"",{data:rt,error:Ke}=await q.functions.invoke("cma-reply-notify",{body:{shareToken:n,message:h,visitorToken:at,viewerName:f.trim()||void 0,viewerEmail:x.trim()||void 0}});if(b(!1),Ke||!(rt!=null&&rt.success)){O({title:"Could not send",description:(Ke==null?void 0:Ke.message)||(rt==null?void 0:rt.error),variant:"destructive"});return}m(""),S(!0),O({title:"Message sent to your agent"})},G=j.useMemo(()=>{const at=o.map(rt=>{const Ke=rt.snapshot,Je=(Ke==null?void 0:Ke.soldPrice)||(Ke==null?void 0:Ke.price);return Je&&(Ke!=null&&Ke.sqft)?Je/Ke.sqft:null}).filter(rt=>!!rt).sort((rt,Ke)=>rt-Ke);return at.length?Math.round(at[Math.floor(at.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(Ct,{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 Z=r.subject||{},X=(Ie=r.settings)==null?void 0:Ie.personalVideo,ae=(Fe=Z.photos)==null?void 0:Fe[0],le=r.contact_first_name?r.contact_first_name:null,re=((i==null?void 0:i.name)||"A").split(" ").map(at=>at[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,ve=r.price_low??null,fe=r.price_likely??null,ue=r.price_high??null,be=ve&&fe&&ue,Ee=fe&&Z.sqft?Math.round(fe/Z.sqft):null,ke=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:re}),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(wi,{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(pn,{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:Z.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($e,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(wn,{className:"w-3 h-3 mr-1"}),le?`Prepared for ${le}`: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:Z.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(ui,{className:"w-4 h-4"}),Z.city,", ",Z.state," ",Z.zip]}),be&&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($ce,{to:fe,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($ce,{to:ve,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($ce,{to:fe,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($ce,{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(Ou,{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 ",((Ne=i==null?void 0:i.name)==null?void 0:Ne.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:at=>at.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:Z.bedrooms??"—"},{label:"Baths",value:Z.bathrooms??"—"},{label:"Sq Ft",value:((Be=Z.sqft)==null?void 0:Be.toLocaleString())??"—"},{label:"Year Built",value:Z.yearBuilt??"—"}].map((at,rt)=>e.jsx(je,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${rt*80}ms`},children:e.jsxs(Le,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:at.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:at.label})]})},rt))}),((Ae=(Se=r.settings)==null?void 0:Se.priceOverride)==null?void 0:Ae.enabled)&&((qe=(Ce=r.settings)==null?void 0:Ce.priceOverride)==null?void 0:qe.note)&&e.jsx(je,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(Le,{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})]})}),be&&e.jsx(N9s,{low:ve,likely:fe,high:ue}),G&&Ee&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(je,{className:"md:col-span-2",children:e.jsxs(Le,{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 ",Z.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",G,"/sqft"]}),". Applied to your home's ",(ze=Z.sqft)==null?void 0:ze.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(G*(Z.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(je,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(Le,{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"]})]}),ke!==null&&ke!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${ke>0?"text-emerald-600":"text-rose-600"}`,children:[ke>0?"▲":"▼"," ",Math.abs(ke),"% ",ke>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($e,{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((at,rt)=>{var ft;const Ke=at.snapshot,Je=Ke.soldPrice||Ke.price;return e.jsxs(je,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${I===rt?"ring-2 ring-primary":""}`,style:{animationDelay:`${rt*60}ms`},onClick:()=>E(rt),onMouseEnter:()=>P(rt),onMouseLeave:()=>P(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(BEe,{photos:Ke.photos,className:"w-full h-44"}),e.jsxs($e,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",rt+1]}),e.jsx($e,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:Ke.status})]}),e.jsxs(Le,{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 · ",((ft=Ke.sqft)==null?void 0:ft.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:["$",Je==null?void 0:Je.toLocaleString()]}),Ke.sqft&&Je?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(Je/Ke.sqft),"/sqft"]}):null]})]})]},rt)})})]}),e.jsx(X9t,{comp:A!==null?(Ve=o[A])==null?void 0:Ve.snapshot:null,open:A!==null,onClose:()=>E(null)}),e.jsx(je,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(Le,{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",le?`, ${le}`:"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((ht=i==null?void 0:i.name)==null?void 0:ht.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:$y,label:"Seems fair"},{kind:"lower",icon:tC,label:"I'd price lower"},{kind:"higher",icon:Zl,label:"I'd price higher"},{kind:"ready_to_list",icon:yb,label:"Ready to list"},{kind:"want_walkthrough",icon:Ta,label:"Want a walkthrough"},{kind:"need_time",icon:Ea,label:"Need more time"},{kind:"have_questions",icon:J5,label:"I have questions"}].map(({kind:at,icon:rt,label:Ke})=>e.jsxs($,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>U(at),children:[e.jsx(rt,{className:"w-4 h-4 mr-2"}),Ke]},at))}),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(Ah,{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! ",((Qe=i==null?void 0:i.name)==null?void 0:Qe.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:at=>g(at.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:x,onChange:at=>v(at.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:at=>m(at.target.value)}),e.jsx($,{onClick:V,disabled:!h.trim()||y,className:"mt-2",children:y?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(je,{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:re}),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(pn,{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(cl,{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(Ah,{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(pn,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function k9s(){const t=qu().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(Q9t,{tokenOverride:t})}const SGe="levelup_affiliate_ref",S9s=30,C9s=()=>{const[s]=Nc();j.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(SGe,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},A9s=()=>{try{const s=localStorage.getItem(SGe);if(!s)return null;const t=JSON.parse(s),n=S9s*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(SGe),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},$Ee="/assets/levelup-logo-header-_ZX7DvlA.png",E9s="/assets/scale-your-team-ku4MPatU.png";function T9s({open:s,onOpenChange:t}){return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{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(wi,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(Er,{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 Gae="/assets/mission_control-BJ-Kz8rX.png",QLe="/assets/crm-CsLftmB2.png",JLe="/assets/deal_pipeline-XYgypvwv.png",e6e="/assets/staging_studio-5iLDjnv0.png",t6e="/assets/coaching-CSQEA81I.png",s6e="/assets/marketing_studio-Brx1ZOnN.png",M9s=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Gae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:QLe},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:JLe},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:e6e},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:t6e},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:s6e}];function P9s({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(wn,{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 X2={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"]}},I9s=[{icon:ef,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:yd,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:Ea,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Ah,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Qr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:dl,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],L9s=[{category:"Marketing Studio",icon:gm,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:ph,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:Sv,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:Qx,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:af,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:wi,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],R9s=[{icon:Yn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:wn,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:Rg,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ui,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Gl,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:Qp,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],D9s=[{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."}],F9s=()=>{const{user:s,loading:t}=_s(),n=Zn(),[r]=Nc();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(""),[v,y]=j.useState(!1),[b,w]=j.useState(!1),S=(I,P=!1)=>{o({tier:I,skipTrial:P}),d(!0)};C9s(),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"&&ne.error("Checkout was canceled. Feel free to try again when you're ready!")},[r]);const A=async(I,P=!1)=>{if(!u){ne.error("Please enter your email address");return}if(!m.trim()){ne.error("Please enter your full name");return}y(!0),i(I+(P?"_direct":""));const R=A9s();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"),ne.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(D){console.error("Checkout error:",D),ne.error(D.message||"Failed to start checkout. Please try again.")}finally{y(!1),i(null),d(!1),o(null)}},E=()=>{l&&A(l.tier,l.skipTrial)};return t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#4a6b6d]",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-white border-t-transparent"})}):e.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:e.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center",children:e.jsx("img",{src:$Ee,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(wn,{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(Qa,{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(ei,{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(Qp,{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(Tf,{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:Gae,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(Zl,{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(ef,{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(Ea,{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(wi,{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(T4,{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:I9s.map((I,P)=>e.jsxs(je,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(St,{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(Et,{className:"text-xl font-sans",children:I.title})]}),e.jsx(Le,{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:L9s.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(ma,{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(wn,{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:M9s.map(I=>e.jsx(P9s,{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(wn,{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:R9s.map((I,P)=>e.jsxs(je,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(St,{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(Et,{className:"text-lg font-semibold text-white",children:I.title})]}),e.jsx(Le,{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(Qa,{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(wi,{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(ma,{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(Ea,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:E9s,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:D9s.map((I,P)=>e.jsx(je,{className:"bg-muted/30 border-0",children:e.jsxs(Le,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(R=>e.jsx(ei,{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(Qa,{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(je,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(St,{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(Et,{className:"text-xl font-sans",children:X2.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:X2.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:X2.individual_agent.period})]}),e.jsx(Vn,{className:"text-base mt-2",children:X2.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(ca,{className:"w-4 h-4"}),X2.individual_agent.trial]})]}),e.jsx(Le,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:X2.individual_agent.features.map((I,P)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(ma,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:I})]},P))})}),e.jsxs(gEe,{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(je,{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(St,{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(wi,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-xl font-sans",children:X2.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:X2.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:X2.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:X2.brokerage_over_25.period})]}),e.jsx(Vn,{className:"text-base mt-2",children:X2.brokerage_over_25.description})]}),e.jsx(Le,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:X2.brokerage_over_25.features.map((I,P)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(ma,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:I})]},P))})}),e.jsx(gEe,{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(Tf,{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(je,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Le,{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(wi,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(je,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Le,{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(jc,{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(je,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Le,{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(u2,{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(je,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Le,{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(Qr,{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(Qa,{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:$Ee,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(T9s,{open:b,onOpenChange:w}),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx($s,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(Er,{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:v,children:v?"Loading...":"Continue to Checkout"})]})})]})},pvt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Dl,{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(br,{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(br,{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(br,{to:"/sms-opt-in",className:"text-primary hover:underline",children:"SMS opt-in page"})," ","and"," ",e.jsx(br,{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"}),"."]})]})]})]})})]}),gvt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Dl,{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"})]})]})]})]})})]}),O9s=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Dl,{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(br,{to:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," and the"," ",e.jsx(br,{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"}),"."]})]})]})]})})]}),xvt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Dl,{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(br,{to:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," and"," ",e.jsx(br,{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"}),"."]})]})]})]})})]}),yvt="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.",z9s="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.",B9s=F2({name:yl().trim().max(200).optional().or(fx("")),phone:yl().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:yl().trim().email("Enter a valid email").max(320).optional().or(fx(""))}),$9s=F2({name:yl().trim().min(1,"Name is required").max(200),phone:yl().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:yl().trim().email("Enter a valid email").max(320).optional().or(fx(""))});function U9s(){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=Zn(),[x,v]=j.useState(""),[y,b]=j.useState(""),[w,S]=j.useState(""),[A,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(!1),O=async W=>{var X;if(W.preventDefault(),!A){ne.error("Please check the marketing consent box to enroll.");return}const V=B9s.safeParse({name:x,phone:y,email:w});if(!V.success){ne.error(((X=V.error.issues[0])==null?void 0:X.message)??"Please check your inputs.");return}P(!0);const{data:G,error:Z}=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),Z||!(G!=null&&G.ok)){ne.error("We could not record your opt-in. Please try again.");return}D(!0),ne.success("Your SmartSign marketing opt-in was recorded.")},U=async W=>{var Z;if(W.preventDefault(),!l){ne.error("Please check the consent box to opt in.");return}const V=$9s.safeParse({name:s,phone:n,email:a});if(!V.success){ne.error(((Z=V.error.issues[0])==null?void 0:Z.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:yvt,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),G){ne.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(Dl,{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(no,{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(je,{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(YJ,{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(br,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"})," ","and"," ",e.jsx(br,{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=>v(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:y,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:A,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:z9s})]})}),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:!A||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(je,{className:"p-8 text-center",children:[e.jsx(Vr,{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(je,{className:"p-8 text-center",children:[e.jsx(Vr,{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(je,{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:yvt})]})}),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(br,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(br,{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(Rm,{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 n6e="/assets/levelup-logo-horizontal-DEFNc0ms.png",q9s=F2({email:yl().email("Invalid email address"),password:yl().min(6,"Password must be at least 6 characters")}),J9t="https://dashboard.relevelup.com",Uce="/oauth-connect",V9s=`${J9t}/profile?reset=true`,n3e="levelupOAuthRouteHistory";function vvt(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function H9s(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(n3e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(n3e,JSON.stringify([{route:s,at:t}])),!1}}function G9s(){sessionStorage.removeItem(n3e)}const W9s=()=>{const{signIn:s,user:t,loading:n}=_s(),r=(t==null?void 0:t.id)??null,a=Zn(),[i]=Nc(),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),[v,y]=j.useState(!1),[b,w]=j.useState(null),[S,A]=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 Z="";try{Z=sessionStorage.getItem("accountPausedReason")||""}catch{}return Z?`Your account is paused. ${Z}`:"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 Z=new URL("/auth",J9t);Z.searchParams.set("next",`${Uce}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(Z.toString());return}if(l){const Z=`${Uce}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",Z);return}o&&vvt(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),j.useEffect(()=>{if(n||!r||U.current)return;const Z=l?`${Uce}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!vvt(Z)){sessionStorage.removeItem("redirectAfterLogin"),U.current=!0,a("/dashboard",{replace:!0});return}const X=Z.startsWith(Uce)||Z.startsWith("/oauth/consent")||Z.startsWith("/.lovable/oauth/consent");if(X&&H9s("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||(G9s(),sessionStorage.removeItem("redirectAfterLogin")),a(Z,{replace:!0})},[l,n,a,r]);const W=async Z=>{Z.preventDefault(),h({}),O(null),A(null),I(!1),d(!0);const X=new FormData(Z.currentTarget),ae=X.get("email"),le=X.get("password");try{q9s.parse({email:ae,password:le}),await s(ae,le)}catch(re){if(re instanceof DEs){const te={};re.issues.forEach(J=>{J.path[0]&&(te[J.path[0]]=J.message)}),h(te)}else if(re instanceof Error&&re.name==="AccountPaused")O(re.message);else if(ae)try{const{data:te}=await q.functions.invoke("account-activation-status",{body:{email:ae}});te!=null&&te.needsActivation&&A(ae)}catch{}}finally{d(!1)}},V=async()=>{if(S){R(!0);try{const{data:Z,error:X}=await q.functions.invoke("send-password-reset",{body:{email:S,variant:"activation"}});if(X)throw X;if((Z==null?void 0:Z.sent)===!1)throw new Error("We couldn't send the activation email. Please try again in a moment or contact support.");I(!0),ne.success("Activation email sent! Check your inbox.")}catch(Z){ne.error(Z instanceof Error?Z.message:"Failed to send activation email")}finally{R(!1)}}},G=async()=>{if(!m){ne.error("Please enter your email address");return}x(!0);try{const{data:Z,error:X}=await q.functions.invoke("send-password-reset",{body:{email:m.trim().toLowerCase(),redirectTo:V9s}});if(X)throw X;if((Z==null?void 0:Z.sent)===!1){ne.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}ne.success("Password reset email sent! Check your inbox."),y(!1),f("")}catch(Z){ne.error(Z instanceof Error?Z.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(br,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(Va,{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:n6e,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(je,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(St,{className:"space-y-1 text-center pb-4",children:[e.jsx(Et,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(Vn,{className:"text-gray-600",children:b||"Sign in to access your dashboard"})]}),e.jsxs(Le,{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(Os,{open:v,onOpenChange:y,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(Fs,{className:"bg-white",children:[e.jsxs(Us,{children:[e.jsx($s,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(Er,{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:Z=>f(Z.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(br,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},bvt=()=>q.auth.oauth,K9s="https://dashboard.relevelup.com",Y9s="/oauth-connect",r3e="levelupOAuthRouteHistory",Z9s="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",X9s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function Q9s(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function J9s(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(r3e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(r3e,JSON.stringify([{route:s,at:t}])),!1}}function e$s(){sessionStorage.removeItem(r3e)}async function _vt(s,t,n){const r=await fetch(`${Z9s}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:X9s,"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 E7e(){var x;const{user:s,session:t,loading:n}=_s(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=Nc(),l=i.get("authorization_id")??"",[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState(!1);j.useEffect(()=>{let v=!0;return(async()=>{if(!l){u("Missing authorization_id");return}const y=`${Y9s}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${K9s}${y}`;return}if(n)return;if(!r){if(J9s("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}Q9s(y)&&sessionStorage.setItem("redirectAfterLogin",y),window.location.replace(`/auth?next=${encodeURIComponent(y)}`);return}if(!a)return;e$s(),sessionStorage.removeItem("redirectAfterLogin");const b=bvt(),{data:w,error:S}=b?await b.getAuthorizationDetails(l):await _vt(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!v)return;if(S){u(S.message);return}const A=(w==null?void 0:w.redirect_url)??(w==null?void 0:w.redirect_to);if(A&&!(w!=null&&w.client)){window.location.href=A;return}c(w)})(),()=>{v=!1}},[a,l,n,r]);async function f(v){if(!(t!=null&&t.access_token)){u("Your sign-in session is not ready yet. Please refresh and try again.");return}m(!0);const y=bvt(),{data:b,error:w}=y?v?await y.approveAuthorization(l,{skipBrowserRedirect:!0}):await y.denyAuthorization(l,{skipBrowserRedirect:!0}):await _vt(`/oauth/authorizations/${encodeURIComponent(l)}/consent`,t.access_token,{method:"POST",body:JSON.stringify({action:v?"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(je,{className:"w-full max-w-md",children:e.jsxs(St,{children:[e.jsx(Et,{children:"Authorization error"}),e.jsx(Vn,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(Ct,{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(je,{className:"w-full max-w-md",children:[e.jsxs(St,{children:[e.jsxs(Et,{children:["Connect ",g," to LevelUp"]}),e.jsxs(Vn,{children:[g," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(Le,{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(Ct,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const t$s="https://chatgpt.com/plugins/plugin_asdk_app_6a7b9baf757081918ac4ab6fcbdb2639?q=levelup",wvt="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",s$s="https://tile-portal.lovable.app/mcp-oauth-bridge.html",n$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'."}],r$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 a$s(){const[s,t]=j.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(wvt),t(!0),ne.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{ne.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(A4,{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(je,{className:"border-primary/20 bg-primary/5",children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-5 w-5 text-primary"}),"Install from the ChatGPT Store"]}),e.jsx(Vn,{children:"The easiest way to connect. Tap the button below, then install the LevelUp plugin in ChatGPT."})]}),e.jsx(Le,{children:e.jsx($,{asChild:!0,size:"lg",className:"w-full sm:w-auto",children:e.jsxs("a",{href:t$s,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Open LevelUp in the ChatGPT Store"]})})})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Quick steps"}),e.jsx(Vn,{children:"Share these steps with any agent who wants to connect via the plugin store."})]}),e.jsx(Le,{children:e.jsx("ol",{className:"space-y-4",children:n$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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Manual MCP setup"}),e.jsx(Vn,{children:"Only use this if you are adding LevelUp as a custom MCP server instead of installing the store plugin."})]}),e.jsxs(Le,{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:wvt}),e.jsx($,{variant:"outline",size:"icon",onClick:n,"aria-label":"Copy MCP URL",children:s?e.jsx(Wl,{className:"h-4 w-4 text-green-600"}):e.jsx(Za,{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(Al,{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:s$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:r$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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"What ChatGPT can see"}),e.jsx(Vn,{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(Le,{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(Ir,{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 i$s=()=>{const[s]=Nc(),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(je,{className:"max-w-lg w-full",children:[e.jsxs(St,{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(Wl,{className:"w-10 h-10 text-green-500"})}),e.jsx(Et,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(Vn,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Le,{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(pn,{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."})})]})]})})},o$s=()=>{const{user:s}=_s(),[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(""),o=async u=>{var h;if(!(s!=null&&s.email)){ne.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"),ne.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(m){console.error("Checkout error:",m),ne.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(je,{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(St,{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(Yn,{className:"h-7 w-7 text-primary"})}),e.jsx(Et,{className:"text-xl",children:"Individual Agent"}),e.jsx(Vn,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Le,{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(ma,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(wn,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(je,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(St,{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(wi,{className:"h-7 w-7 text-purple-600"})}),e.jsx(Et,{className:"text-xl",children:"Brokerage"}),e.jsx(Vn,{children:"Unlimited agents — everything in Individual, plus brokerage tools"})]}),e.jsxs(Le,{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(ma,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(wi,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(je,{className:"bg-muted/50",children:e.jsxs(Le,{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(pn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},l$s=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=_s(),a=Zn(),[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()){ne.error("Please enter a brokerage name");return}const{data:m}=await q.auth.getSession(),f=m.session;if(!s||!f){ne.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),ne.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(g){console.error("Error creating brokerage:",g),ne.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(je,{className:"max-w-lg w-full",children:[e.jsxs(St,{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(Ct,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(Et,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(Vn,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(Wl,{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(Ct,{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(je,{className:"max-w-lg w-full",children:[e.jsxs(St,{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(wi,{className:"w-10 h-10 text-primary"})}),e.jsx(Et,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(Vn,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Le,{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(Yn,{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(Wl,{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(Wl,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Wl,{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(Wl,{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(Qa,{className:"w-4 h-4 ml-2"})]})]})]})})},jvt=()=>{const s=Zn(),[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(je,{className:"w-full max-w-md",children:[e.jsxs(St,{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(Et,{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(Vn,{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(Le,{children:e.jsx($,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},qce="https://dashboard.relevelup.com",Nvt=()=>{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:v}=await q.functions.invoke("send-password-reset",{body:{email:x,variant:a==="recovery"?"reset":"activation"}});u(v?"failed":"sent")}catch{u("failed")}},f=async()=>{if(!(!l||!r)){if(t(!0),c(null),window.location.origin!==qce&&window.location.hostname!=="localhost"){window.location.href=`${qce}${window.location.pathname}${window.location.search}`;return}try{const g=new URL(r),x=g.searchParams.get("token")||g.searchParams.get("token_hash"),v=g.searchParams.get("type")||(a==="claim"?"invite":a);if(x){const{error:y}=await q.auth.verifyOtp({token_hash:x,type:v});if(!y){const b=g.searchParams.get("redirect_to");let w=v==="recovery"?"/profile?reset=true":"/dashboard";if(b)try{const S=new URL(b);w=`${S.pathname}${S.search}`}catch{}window.location.replace(`${qce}${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:n6e,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(je,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(St,{className:"text-center",children:[e.jsx(Et,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:i.title}),e.jsx(Vn,{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(Le,{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=`${qce}/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."})]})]})]})})]})},Vce="https://dashboard.relevelup.com",c$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!==Vce&&window.location.hostname!=="localhost"){window.location.href=`${Vce}${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(`${Vce}/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:n6e,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(je,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(St,{className:"text-center",children:[e.jsx(Et,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:u?`Welcome, ${u}`:"Activate Your Account"}),e.jsx(Vn,{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(Le,{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=`${Vce}/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=Zn(),[t]=Nc(),[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),[v,y]=j.useState(!1),[b,w]=j.useState(null),[S,A]=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){ne.error("Invalid invite code"),x(!1);return}if(!V.is_active){ne.error("This invite code is no longer active"),x(!1);return}if(V.max_uses&&V.uses_count>=V.max_uses){ne.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()){ne.error("Please enter your name");return}if(l.length<6){ne.error("Password must be at least 6 characters");return}f(!0);try{const G="https://dashboard.relevelup.com/",{data:Z,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")?ne.error("This email is already registered. Please sign in instead."):ne.error(X.message);return}if(Z.user){await q.rpc("add_default_signup_tag",{user_id:Z.user.id});const ae=n.toUpperCase().trim();S?await q.functions.invoke("assign-brokerage",{body:{userId:Z.user.id,brokerageId:S,inviteCode:ae}}):P?await q.functions.invoke("assign-brokerage",{body:{userId:Z.user.id,trialDays:P,inviteCode:ae}}):await q.functions.invoke("assign-brokerage",{body:{userId:Z.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),ne.success("Account created! You can now access the dashboard."),s("/dashboard")}}catch(G){console.error("Signup error:",G),ne.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(je,{className:"w-full max-w-md",children:[e.jsxs(St,{className:"text-center",children:[e.jsx(Et,{className:"text-2xl font-bold text-primary",children:E?`Join ${E}`:"Join LevelUp"}),e.jsx(Vn,{children:v?E?`Create your account to join ${E}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Le,{children:v?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(Nx,{className:"h-4 w-4"}):e.jsx(Ta,{className:"h-4 w-4"})})]})]}),e.jsx($,{type:"submit",className:"w-full",disabled:m,children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{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(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},Wae=()=>{const{user:s,isCoach:t}=_s();return st({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}})},u$s=()=>{const{data:s}=Wae();return st({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}))}})},Ast=()=>{const{user:s}=_s();return st({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}}})},h$s=s=>st({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}}}),Est=s=>st({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||[]}}),Tst=s=>st({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||[]}}),m$s=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function f$s(){const s=Zn(),{data:t,isLoading:n}=Wae(),{data:r=[],isLoading:a}=u$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(af,{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."})]})});m$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(wn,{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(T7e,{icon:af,label:"Active agents",value:i}),e.jsx(T7e,{icon:Wc,label:"This month",value:"—"}),e.jsx(T7e,{icon:sh,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(je,{children:e.jsx(Le,{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(je,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Le,{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(Ii,{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(Qa,{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($e,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",hu(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function T7e({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 e$t({assignmentId:s}){const{user:t}=_s(),n=Zt(),[r,a]=j.useState(""),[i,l]=j.useState(!1),o=j.useRef(null),{data:c=[]}=st({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(je,{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:hu(new Date(u.created_at),{addSuffix:!0})})]})]},u.id)})}),e.jsx(Le,{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(Zr,{className:"h-4 w-4"})})]})})]})}var p$s=Object.defineProperty,ET=(s,t)=>p$s(s,"name",{value:t,configurable:!0}),t$t="Progress",Mst=100,[g$s,kkr]=ep(t$t),[x$s,y$s]=g$s(t$t),v$s=j.forwardRef(ET(function(t,n){const{__scopeProgress:r,value:a=null,max:i,getValueLabel:l=s$t,...o}=t;(i||i===0)&&!CGe(i)&&console.error(n$t(`${i}`,"Progress"));const c=CGe(i)?i:Mst;a!==null&&!AGe(a,c)&&console.error(r$t(`${a}`,"Progress"));const d=AGe(a,c)?a:null,u=tse(d)?l(d,c):void 0;return e.jsx(x$s,{scope:r,value:d,max:c,children:e.jsx(Ei.div,{"aria-valuemax":c,"aria-valuemin":0,"aria-valuenow":tse(d)?d:void 0,"aria-valuetext":u,role:"progressbar","data-state":Pst(d,c),"data-value":d??void 0,"data-max":c,...o,ref:n})})},"Progress")),b$s="ProgressIndicator",_$s=j.forwardRef(ET(function(t,n){const{__scopeProgress:r,...a}=t,i=y$s(b$s,r);return e.jsx(Ei.div,{"data-state":Pst(i.value,i.max),"data-value":i.value??void 0,"data-max":i.max,...a,ref:n})},"ProgressIndicator"));function s$t(s,t){return`${Math.round(s/t*100)}%`}ET(s$t,"defaultGetValueLabel");function Pst(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}ET(Pst,"getProgressState");function tse(s){return typeof s=="number"}ET(tse,"isNumber");function CGe(s){return tse(s)&&!isNaN(s)&&s>0}ET(CGe,"isValidMaxNumber");function AGe(s,t){return tse(s)&&!isNaN(s)&&s<=t&&s>=0}ET(AGe,"isValidValueNumber");function n$t(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${Mst}\`.`}ET(n$t,"getInvalidMaxError");function r$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 ${Mst} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}ET(r$t,"getInvalidValueError");var a$t=v$s,w$s=_$s;const Yi=j.forwardRef(({className:s,value:t,...n},r)=>e.jsx(a$t,{ref:r,className:Pt("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(w$s,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Yi.displayName=a$t.displayName;function i$t({agentUserId:s}){const t=new Date().getFullYear(),n=`${t}-01-01`,r=`${t}-12-31`,{data:a=[]}=st({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:x,error:v}=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(v)throw v;return x||[]}}),{data:i}=st({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,v)=>x+(Number(v.sale_price)||0),0),d=l.reduce((x,v)=>x+(Number(v.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(Zl,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(M7e,{icon:Im,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(M7e,{icon:Zl,label:"Volume",value:g(c),goal:m,current:c,suffix:m?`of ${g(m)}`:""}),e.jsx(M7e,{icon:su,label:"GCI",value:g(d),goal:f,current:d,suffix:f?`of ${g(f)}`:""})]}),o===0&&e.jsx(je,{children:e.jsxs(Le,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function M7e({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(je,{children:e.jsxs(Le,{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 o$t({assignmentId:s,canEdit:t}){const n=Zt(),[r,a]=j.useState(!1),[i,l]=j.useState(null),{data:o=[]}=st({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(ph,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs($,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(cn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(je,{children:e.jsx(Le,{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(je,{children:e.jsxs(Le,{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($e,{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(pi,{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 ",Js(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(j$s,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function j$s({open:s,onOpenChange:t,assignmentId:n,goal:r,onSaved:a}){var S,A;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(((A=r==null?void 0:r.current_value)==null?void 0:A.toString())||"0"),[x,v]=j.useState((r==null?void 0:r.due_date)||""),[y,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"),v((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 ne.error(I.message);ne.success(r!=null&&r.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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=>v(E.target.value)})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:w,disabled:y,children:r!=null&&r.id?"Save":"Create"})]})]})})}function l$t({assignmentId:s}){const t=Zt(),{user:n}=_s(),r=j.useRef(null),[a,i]=j.useState(!1),{data:l=[]}=st({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:v}=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(v)throw v;ne.success("File uploaded"),o()}catch(g){ne.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 ne.error("Could not get download link");window.open(m.signedUrl,"_blank")},u=async h=>{await mo("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(je,{children:e.jsx(Le,{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(je,{children:e.jsxs(Le,{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(Qr,{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 · `:"",Js(new Date(h.created_at),"PP")]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(ji,{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(qn,{className:"h-4 w-4"})})]})},h.id))})]})}function N$s(){var m,f,g,x;const{id:s}=Wi(),t=Zn(),n=Zt(),{data:r,isLoading:a}=h$s(s),{data:i=[]}=Est(s),{data:l=[]}=Tst(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(Va,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(je,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(Le,{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(Ii,{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($e,{variant:"secondary",className:"capitalize",children:(h.pipeline_stage||"active").replace("_"," ")}),e.jsx($e,{variant:"outline",className:"capitalize",children:h.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(S$s,{value:h.pipeline_stage||"active",onChange:async v=>{await q.from("coaching_assignments").update({pipeline_stage:v}).eq("id",h.id),n.invalidateQueries({queryKey:["coaching-assignment",h.id]}),n.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsx(k$s,{assignment:h}),e.jsxs(pa,{defaultValue:"sessions",children:[e.jsxs(ga,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(Xt,{value:"sessions",children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(Xt,{value:"actions",children:[e.jsx(Sv,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(Xt,{value:"goals",children:[e.jsx(ph,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(Xt,{value:"kpis",children:[e.jsx(Zl,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(Xt,{value:"messages",children:[e.jsx(no,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(Xt,{value:"files",children:[e.jsx(Nv,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(Xt,{value:"notes",children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(Qt,{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(cn,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(je,{children:e.jsx(Le,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(v=>e.jsx(je,{children:e.jsx(Le,{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:Js(new Date(v.scheduled_at),"PPp")}),e.jsx($e,{variant:"outline",className:"capitalize",children:v.status}),v.template&&e.jsx($e,{variant:"secondary",children:v.template}),v.zoom_join_url&&e.jsx("a",{href:v.zoom_join_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary underline",children:"Join Zoom"})]}),v.agenda&&e.jsxs("p",{className:"text-sm mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent's agenda:"})," ",v.agenda]}),v.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:v.summary}),v.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(jc,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:v.private_notes})]})]})})})},v.id))})]}),e.jsxs(Qt,{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(cn,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(je,{children:e.jsx(Le,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(v=>e.jsx(je,{children:e.jsxs(Le,{className:"p-3 flex items-center gap-3",children:[e.jsx(ai,{checked:v.status==="done",onCheckedChange:async y=>{await q.from("coaching_action_items").update({status:y?"done":"open",completed_at:y?new Date().toISOString():null}).eq("id",v.id),n.invalidateQueries({queryKey:["coaching-action-items",h.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:v.status==="done"?"line-through text-muted-foreground":"font-medium",children:v.title}),v.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:v.description})]}),v.due_date&&e.jsx($e,{variant:"outline",children:Js(new Date(v.due_date),"MMM d")}),e.jsx($e,{variant:"secondary",className:"capitalize",children:v.priority})]})},v.id))})]}),e.jsx(Qt,{value:"goals",children:e.jsx(o$t,{assignmentId:h.id,canEdit:!0})}),e.jsx(Qt,{value:"kpis",children:h.agent_id&&e.jsx(i$t,{agentUserId:h.agent_id})}),e.jsx(Qt,{value:"messages",children:e.jsx(e$t,{assignmentId:h.id})}),e.jsx(Qt,{value:"files",children:e.jsx(l$t,{assignmentId:h.id})}),e.jsx(Qt,{value:"notes",className:"space-y-4",children:e.jsx(je,{children:e.jsx(Le,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(C$s,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(A$s,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function k$s({assignment:s}){const t=Zt(),[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 ne.error(c.message);ne.success("Session allowance updated"),t.invalidateQueries({queryKey:["coaching-assignment",s.id]})};return e.jsx(je,{children:e.jsxs(Le,{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(Ea,{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 S$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 C$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),[v,y]=j.useState(!0),[b,w]=j.useState(null),[S,A]=j.useState(!1),E=async()=>{A(!0);const{data:P,error:R}=await q.functions.invoke("coaching-prep-brief",{body:{assignmentId:n}});if(A(!1),R||P!=null&&P.error)return ne.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),ne.error(R.message);if(ne.success("Session saved"),v&&u.trim()&&(P!=null&&P.id)){const{error:D}=await q.functions.invoke("coaching-send-recap",{body:{sessionId:P.id}});D?ne.error("Saved, but recap email failed: "+D.message):ne.success("Recap emailed to agent")}x(!1),r==null||r(),t(!1),h(""),f(""),w(null)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{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($s,{children:"New Session"}),e.jsxs($,{size:"sm",variant:"outline",onClick:E,disabled:S,children:[S?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(wn,{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(wn,{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(jc,{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:v,onCheckedChange:P=>y(!!P)}),e.jsx(Zr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(Nr,{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 A$s({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 ne.error(x.message);ne.success("Action item added"),r==null||r(),t(!1),i(""),o(""),d("")};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:g,disabled:m,children:"Add"})]})]})})}function EGe({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(ei,{style:{width:t,height:t},className:r<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},r))})}function E$s({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(EGe,{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(je,{children:e.jsx(Le,{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(Ii,{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(EGe,{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 T$s({coachId:s,assignmentId:t}){const{user:n}=_s(),[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 ne.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 ne.error(x.message);ne.success("Thanks for your review!"),a({...g,id:r==null?void 0:r.id})};return e.jsx(je,{children:e.jsxs(Le,{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(EGe,{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 Hce=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},P7e=s=>Js(s,"yyyy-MM-dd"),kvt=s=>{const[t,n]=s.split(":").map(Number),r=t>=12?"PM":"AM";return`${t%12||12}:${String(n).padStart(2,"0")} ${r}`};function M$s({assignmentId:s,upcoming:t=[]}){const n=Zt(),[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}=st({queryKey:["coaching-booking-context",s],queryFn:()=>Hce({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,[]),[v,y]=j.useState(()=>Zm(new Date)),b=(f==null?void 0:f.max_advance_days)||30,w=j.useMemo(()=>Am(Eg(x),b-1),[x,b]),S=j.useMemo(()=>{const ae=Zm(v);return ae{const ae=uw(v);return ae>w?w:ae},[v,w]),E=Math.max(0,db(A,S)+1),{data:I={},isFetching:P}=st({queryKey:["coaching-availability",r,P7e(S),E],enabled:!!r&&E>0,queryFn:async()=>(await Hce({action:"availability",booking_type_id:r,start:P7e(S),days:E})).availability||{}}),R=j.useMemo(()=>{const ae=Zm(v),le=uw(v).getDate(),re=ae.getDay(),te=Array.from({length:re},()=>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 le of O){const re=Number(le.split(":")[0]);re<12?ae[0].items.push(le):re<17?ae[1].items.push(le):ae[2].items.push(le)}return ae.filter(le=>le.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,Z=async()=>{if(!(!r||!i||!o)){m(!0);try{await Hce({action:"book",booking_type_id:r,date:i,time:o,agenda:d||null}),ne.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){ne.error(ae.message||"Could not book that session")}finally{m(!1)}}},X=async ae=>{if(await mo("Cancel this coaching session?"))try{await Hce({action:"cancel",session_id:ae}),ne.success("Session cancelled"),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(le){ne.error(le.message||"Could not cancel")}};return g?e.jsx(je,{children:e.jsxs(Le,{className:"p-8 flex items-center justify-center text-muted-foreground gap-2",children:[e.jsx(Ct,{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(je,{children:e.jsxs(Le,{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(Wc,{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($e,{variant:"secondary",children:"All booked up"})]})}),t.length>0&&e.jsx(je,{children:e.jsxs(Le,{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:Js(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(fa,{className:"h-4 w-4 mr-1"})," Join"]})}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>X(ae.id),children:[e.jsx(ju,{className:"h-4 w-4 mr-1"})," Cancel"]})]},ae.id))]})}),e.jsx(je,{children:e.jsxs(Le,{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(ca,{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:Dae(v,x),onClick:()=>y(Av(v,-1)),"aria-label":"Previous month",children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-medium w-28 text-center",children:Js(v,"MMMM yyyy")}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:Zm(Av(v,1))>w,onClick:()=>y(Av(v,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,le)=>e.jsx("div",{className:"text-[11px] text-muted-foreground text-center py-1",children:ae},le))}),e.jsx("div",{className:"grid grid-cols-7 gap-1",children:R.map((ae,le)=>{if(!ae)return e.jsx("div",{},`b${le}`);const re=P7e(ae),te=(I[re]||[]).length,ce=ae>=Eg(x)&&ae<=w&&te>0,ve=i===re;return e.jsxs("button",{disabled:!ce,onClick:()=>{l(re),c(null)},className:`aspect-square rounded-lg border text-sm flex flex-col items-center justify-center gap-1 transition-colors ${ve?"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:Js(ae,"d")}),e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${ve?"bg-primary-foreground":ce?"bg-primary":"bg-transparent"}`})]},re)})}),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(Ct,{className:"h-3 w-3 animate-spin"})," Loading your coach's openings…"]}):e.jsxs(e.Fragment,{children:[e.jsx(wn,{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 · ${Js(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(Ct,{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(le=>e.jsx("button",{onClick:()=>c(le),className:`py-2 rounded-lg border text-sm transition-colors ${o===le?"border-primary bg-primary/10 font-medium":"hover:bg-muted/50"}`,children:kvt(le)},le))})]},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,le])=>e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{l(ae),c(null)},children:[Js(new Date(`${ae}T12:00:00`),"EEE MMM d")," · ",le.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:Z,disabled:h||G,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[h?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Vr,{className:"h-4 w-4 mr-1"}),"Book ",V==null?void 0:V.name," — ",i&&Js(new Date(`${i}T12:00:00`),"MMM d")," at ",kvt(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(je,{children:e.jsx(Le,{className:"p-8 text-center text-muted-foreground",children:"Your coach hasn't opened their coaching calendar yet. Check back soon."})})}function P$s(){const{user:s}=_s(),{isMember:t,pkg:n}=bC(),{data:r}=st({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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between gap-2 space-y-0",children:[e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(Fg,{className:"h-4 w-4 text-primary"})," Coaching prep"]}),a.length>0&&e.jsxs($e,{variant:"secondary",children:[i,"/",a.length," done"]})]}),e.jsxs(Le,{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(br,{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(Vr,{className:"h-4 w-4 mt-0.5 text-primary"}):e.jsx(Dg,{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 I$s(){var m,f,g,x,v,y;const{user:s}=_s(),{data:t,isLoading:n,refetch:r}=Ast(),a=Zt(),i=t==null?void 0:t.id,{data:l=[]}=Est(i),{data:o=[]}=Tst(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(af,{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(je,{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(Ii,{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(wn,{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:[((v=c.coach)==null?void 0:v.is_certified)&&e.jsx($e,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx($e,{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(I7e,{icon:Sv,label:"Open action items",value:d.length}),e.jsx(I7e,{icon:ph,label:"Completed",value:u}),e.jsx(I7e,{icon:Ea,label:"Sessions",value:l.length})]}),e.jsx(P$s,{}),((y=c.coach)==null?void 0:y.id)&&e.jsx(T$s,{coachId:c.coach.id,assignmentId:i}),e.jsxs(pa,{defaultValue:"book",children:[e.jsxs(ga,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(Xt,{value:"book",children:[e.jsx(vv,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Book"})]}),e.jsxs(Xt,{value:"actions",children:[e.jsx(Sv,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Xt,{value:"sessions",children:[e.jsx(Ea,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(Xt,{value:"goals",children:[e.jsx(ph,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(Xt,{value:"kpis",children:[e.jsx(Zl,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(Xt,{value:"messages",children:[e.jsx(no,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(Xt,{value:"files",children:[e.jsx(Nv,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(Qt,{value:"book",children:e.jsx(M$s,{assignmentId:i,upcoming:h})}),e.jsx(Qt,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(je,{children:e.jsx(Le,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(b=>e.jsx(je,{children:e.jsxs(Le,{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($e,{variant:"outline",children:Js(new Date(b.due_date),"MMM d")}),e.jsx($e,{variant:"secondary",className:"capitalize",children:b.priority})]})},b.id))}),e.jsx(Qt,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(je,{children:e.jsx(Le,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(b=>e.jsx(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:Js(new Date(b.scheduled_at),"PPp")}),e.jsx($e,{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(Qt,{value:"goals",children:e.jsx(o$t,{assignmentId:i,canEdit:!1})}),e.jsx(Qt,{value:"kpis",children:s&&e.jsx(i$t,{agentUserId:s.id})}),e.jsx(Qt,{value:"messages",children:e.jsx(e$t,{assignmentId:i})}),e.jsx(Qt,{value:"files",children:e.jsx(l$t,{assignmentId:i})})]})]})})}function I7e({icon:s,label:t,value:n}){return e.jsx(je,{children:e.jsxs(Le,{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 Svt="coaching_access",L7e=s=>((s==null?void 0:s.name)||(s==null?void 0:s.email)||"?").trim().slice(0,2).toUpperCase(),R7e=s=>!!s.expires_at&&new Date(s.expires_at).getTime()<=Date.now();function L$s(){const s=Zt(),[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}=st({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",Svt).order("enabled_at",{ascending:!1});if(O)throw O;return D||[]}}),{data:f=[]}=st({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={}}=st({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 v=j.useMemo(()=>{const D=new Map;return h.forEach(O=>D.set(O.user_id,O)),D},[h]),y=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:Svt,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?(ne.error(W.message),!1):(b(),!0)},S=async D=>{await w(D.id)&&ne.success(`Coaching access granted to ${D.name||D.email}`),n(""),a([])},A=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 ne.error(U.message);ne.success(O?"Access enabled":"Access paused"),b()},E=async D=>{if(!await mo({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 ne.error(U.message);ne.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&&!R7e(D)).length,R=f.filter(D=>!v.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(D7e,{icon:Rm,label:"Granted access",value:P,hint:"Standalone entitlements"}),e.jsx(D7e,{icon:Yn,label:"Coached members",value:y.size,hint:"Active coach assignments"}),e.jsx(D7e,{icon:wn,label:"Total with access",value:new Set([...h.filter(D=>D.enabled&&!R7e(D)).map(D=>D.user_id),...y]).size,hint:"Unique members"})]}),e.jsx(je,{children:e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(VI,{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(Ct,{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=v.get(D.id),U=y.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(Ii,{src:D.avatar_url||void 0}),e.jsx(za,{className:"text-xs",children:L7e(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($e,{variant:"outline",className:"shrink-0",children:"Already granted"}):U?e.jsxs($e,{variant:"outline",className:"shrink-0",children:[e.jsx(nu,{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(lc,{className:"h-4 w-4 mr-1"})," Grant"]})]})]},D.id)})})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Rm,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Members with granted access"}),e.jsx($e,{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(Ct,{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=R7e(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(Ii,{src:(O==null?void 0:O.avatar_url)||void 0}),e.jsx(za,{className:"text-xs",children:L7e(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($e,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:"Expired"}):D.enabled?e.jsx($e,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:"Active"}):e.jsx($e,{variant:"outline",children:"Paused"}),y.has(D.user_id)&&e.jsxs($e,{variant:"outline",children:[e.jsx(nu,{className:"h-3 w-3 mr-1"}),"Has coach"]}),D.tier&&e.jsx($e,{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(Su,{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(jn,{checked:D.enabled&&!U,onCheckedChange:W=>A(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(mr,{className:"h-4 w-4"})})]})]},D.id)})})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Access through a coach assignment"}),e.jsx($e,{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(Ii,{src:(O==null?void 0:O.avatar_url)||void 0}),e.jsx(za,{className:"text-[10px]",children:L7e(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(R$s,{state:o,onClose:()=>c(null),onSave:async D=>{if(!o)return;await w(o.profile.id,D)&&(ne.success("Coaching access saved"),c(null))}})]})}function D7e({icon:s,label:t,value:n,hint:r}){return e.jsx(je,{children:e.jsxs(Le,{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 R$s({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(Os,{open:!!s,onOpenChange:g=>!g&&t(),children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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(jn,{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(Nr,{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 D$s(){const s=Zt(),[t,n]=j.useState(""),[r,a]=j.useState("active"),{data:i=[]}=st({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:v}=await q.from("profiles").select("id, name, email").in("id",x),y=new Map((v||[]).map(b=>[b.id,b]));return(f||[]).map(b=>{var w,S;return{id:b.id,label:((w=y.get(b.user_id))==null?void 0:w.name)||((S=y.get(b.user_id))==null?void 0:S.email)||b.user_id}})}}),{data:l=[],isLoading:o}=st({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:v}=x.length?await q.from("profiles").select("id, name, email").in("id",x):{data:[]},y=new Map((v||[]).map(b=>[b.id,b]));return(f||[]).map(b=>({...b,agent:y.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,v;return r!=="all"&&g.status!==r?!1:f?(((x=g.agent)==null?void 0:x.name)||"").toLowerCase().includes(f)||(((v=g.agent)==null?void 0:v.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 y,b;if(g===f.coach_id||!await mo({title:"Switch coach?",description:`${((y=f.agent)==null?void 0:y.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:v}=await q.from("coaching_assignments").update({coach_id:g}).eq("id",f.id);if(v)return ne.error(v.message);ne.success("Coach switched"),u()},m=async(f,g)=>{var v,y;if(g==="ended"&&!await mo({title:"End assignment?",description:`${((v=f.agent)==null?void 0:v.name)||((y=f.agent)==null?void 0:y.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 ne.error(x.message);ne.success(g==="ended"?"Assignment ended":"Assignment reactivated"),u()};return e.jsx(je,{children:e.jsxs(Le,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach assignments"}),e.jsx($e,{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,v;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:[(v=f.agent)==null?void 0:v.email," · ",f.pipeline_stage||"onboarding",f.status==="ended"&&" · ended"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cJ,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ms,{value:f.coach_id,onValueChange:y=>h(f,y),children:[e.jsx(us,{className:"w-full md:w-56 h-9",children:e.jsx(fs,{})}),e.jsx(hs,{children:i.map(y=>e.jsx(Ge,{value:y.id,children:y.label},y.id))})]}),f.status==="active"?e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(f,"ended"),children:[e.jsx(oV,{className:"h-4 w-4 mr-1"})," End"]}):e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(f,"active"),children:[e.jsx(Sx,{className:"h-4 w-4 mr-1"})," Reactivate"]})]})]},f.id)})})]})})}function F$s(){const s=Zt(),[t,n]=j.useState(""),[r,a]=j.useState([]),[i,l]=j.useState(null),{data:o=[],isLoading:c}=st({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(v=>v.user_id),{data:g}=await q.from("profiles").select("id, name, email, avatar_url").in("id",f),x=new Map((g||[]).map(v=>[v.id,v]));return h.map(v=>({...v,profile:x.get(v.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 ne.error(m.message);const{error:f}=await q.from("coaches").insert({user_id:h.id});if(f&&!String(f.message).includes("duplicate"))return ne.error(f.message);ne.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 ne.error(f.message);ne.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(af,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsxs(pa,{defaultValue:"coaches",className:"space-y-6",children:[e.jsxs(ga,{className:"flex-wrap h-auto",children:[e.jsx(Xt,{value:"coaches",children:"Coaches"}),e.jsx(Xt,{value:"assignments",children:"Assignments"}),e.jsx(Xt,{value:"access",children:"Coaching Access"}),e.jsx(Xt,{value:"applications",children:"Applications"}),e.jsx(Xt,{value:"settings",children:"Settings"})]}),e.jsx(Qt,{value:"assignments",className:"space-y-6",children:e.jsx(D$s,{})}),e.jsx(Qt,{value:"access",className:"space-y-6",children:e.jsx(L$s,{})}),e.jsx(Qt,{value:"applications",className:"space-y-6",children:e.jsx(B$s,{})}),e.jsx(Qt,{value:"settings",className:"space-y-6",children:e.jsx(O$s,{})}),e.jsxs(Qt,{value:"coaches",className:"space-y-6",children:[e.jsx(je,{children:e.jsxs(Le,{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(cn,{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(je,{children:e.jsx(Le,{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(je,{children:e.jsxs(Le,{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($e,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(wn,{className:"h-3 w-3 mr-1"}),"Certified"]}),h.accepting_clients&&e.jsx($e,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>l(h.id),children:[e.jsx(lc,{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(jn,{checked:h.is_certified,onCheckedChange:x=>u(h.id,x)})]})]})},h.id)})})]})]})]})]}),e.jsx(z$s,{coachId:i,onClose:()=>l(null)})]})}function O$s(){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 ne.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 ne.error(d.message);ne.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(je,{children:e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Aw,{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 z$s({coachId:s,onClose:t}){const[n,r]=j.useState(""),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=Zt();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 ne.error(h.message);ne.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(Os,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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(Nr,{children:e.jsx($,{variant:"outline",onClick:t,children:"Close"})})]})})}function B$s(){const s=Zt(),[t,n]=j.useState("pending"),[r,a]=j.useState(null),{data:i=[],isLoading:l}=st({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}=st({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 ne.error(m.message);ne.success(`Marked ${h}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs($e,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(ma,{className:"h-3 w-3 mr-1"}),"Approved"]}):u==="rejected"?e.jsxs($e,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(mr,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs($e,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(ca,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(je,{children:[e.jsxs(Le,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(zz,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs($e,{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(pn,{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(Os,{open:!!r,onOpenChange:u=>!u&&a(null),children:e.jsx(Fs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx(Us,{children:e.jsxs($s,{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(v$,{icon:pn,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(v$,{icon:Da,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(v$,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(v$,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(v$,{icon:Ir,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(v$,{icon:Ir,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx(F7e,{label:"Specialties",children:r.specialties}),e.jsx(F7e,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx(F7e,{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(Nr,{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(mr,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs($,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(ca,{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(ma,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function v$({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 F7e({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 $$s(){const s=Zn(),{data:t}=Wae(),n=Zt(),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),{data:d,refetch:u}=st({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v}=await q.functions.invoke("coach-stripe-status");return v}}),{data:h=[]}=st({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v}=await q.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return v||[]}});j.useEffect(()=>{const v=new URLSearchParams(window.location.search);(v.get("onboarded")||v.get("refresh"))&&u()},[u]);const m=async()=>{var w,S;a(!0);const{data:v,error:y}=await q.functions.invoke("coach-stripe-connect");a(!1);let b=v==null?void 0:v.error;if(!b&&y)try{const A=await((S=(w=y==null?void 0:y.context)==null?void 0:w.json)==null?void 0:S.call(w));b=(A==null?void 0:A.error)||y.message}catch{b=y.message}if(b)return ne.error(b,{duration:1e4});v!=null&&v.url&&(window.location.href=v.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(Va,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(je,{children:e.jsxs(Le,{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(jv,{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($e,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"})," ",g?"Using LevelUp billing":"Connected"]}):f.connected?e.jsxs($e,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(vl,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx($e,{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(Ir,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(je,{children:e.jsxs(Le,{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(cn,{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(v=>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:[v.name,v.is_active&&v.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:["$",(v.price_cents/100).toFixed(0)," / ",v.billing_interval,!v.is_active&&" · Inactive"]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{c(v),l(!0)},children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await mo("Delete this package?")&&(await q.from("coaching_packages").delete().eq("id",v.id),n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(qn,{className:"h-4 w-4"})})]},v.id))})]})}),e.jsx(U$s,{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 U$s({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,v]=j.useState(!0),[y,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),v((r==null?void 0:r.accepting_clients)??!0))},[s,r]);const w=async()=>{if(!i.trim()||!d)return ne.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:A}=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),A)return ne.error(A.message);ne.success("Saved"),a==null||a(),t(!1)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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=>v(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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:w,disabled:y,children:r!=null&&r.id?"Save":"Create"})]})]})})}function Cvt({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),v=s==="photo"?"image/*":"video/*",y=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 ne.error("Not signed in");if(P.size>y)return ne.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),ne.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),ne.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){ne.error(P.message||"Could not access camera")}},A=()=>{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:v,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(Ct,{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(jx,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs($,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(qn,{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:A,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(w_,{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(fa,{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(Ct,{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 c$t(){const{user:s}=_s(),t=Zt(),n=st({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:y}=await q.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(y)throw y;return v},enabled:!!s}),r=st({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:y}=await q.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(y)throw y;return v},enabled:!!s}),a=st({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:y}=await q.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(y)throw y;return v},enabled:!!s}),i=st({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:y}=await q.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(y)throw y;return v},enabled:!!s}),l=st({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:y}=await q.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(y)throw y;return v},enabled:!!s}),o=mt({mutationFn:async()=>{const{data:v,error:y}=await q.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(y)throw y;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:A}=await q.from("agent_availability_slots").insert(S);if(A)throw A;return v},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),ne.success("Scheduler set up successfully!")},onError:v=>ne.error(v.message)}),c=mt({mutationFn:async v=>{const{error:y}=await q.from("agent_booking_settings").update(v).eq("user_id",s.id);if(y)throw y},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),ne.success("Settings updated")},onError:v=>ne.error(v.message)}),d=mt({mutationFn:async v=>{const y={...v,user_id:s.id};if(v.id){const{error:b}=await q.from("agent_booking_types").update(y).eq("id",v.id);if(b)throw b}else{const{error:b}=await q.from("agent_booking_types").insert(y);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ne.success("Booking type saved")},onError:v=>ne.error(v.message)}),u=mt({mutationFn:async v=>{const{error:y}=await q.from("agent_booking_types").delete().eq("id",v);if(y)throw y},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ne.success("Booking type deleted")},onError:v=>ne.error(v.message)}),h=mt({mutationFn:async v=>{const y={...v,user_id:s.id};if(v.id){const{error:b}=await q.from("agent_availability_slots").update(y).eq("id",v.id);if(b)throw b}else{const{error:b}=await q.from("agent_availability_slots").insert(y);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:v=>ne.error(v.message)}),m=mt({mutationFn:async v=>{const{error:y}=await q.from("agent_availability_slots").delete().eq("id",v);if(y)throw y},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:v=>ne.error(v.message)}),f=mt({mutationFn:async v=>{const{blocked_date:y,end_date:b,reason:w}=v,S=D=>{const[O,U,W]=D.split("-").map(Number);return new Date(O,U-1,W)},A=D=>`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}-${String(D.getDate()).padStart(2,"0")}`,E=S(y),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:v=>{t.invalidateQueries({queryKey:["blocked-dates"]}),ne.success(v&&v>1?`${v} dates blocked`:"Date blocked")},onError:v=>ne.error(v.message)}),g=mt({mutationFn:async v=>{const{error:y}=await q.from("agent_blocked_dates").delete().eq("id",v);if(y)throw y},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:v=>ne.error(v.message)}),x=mt({mutationFn:async({id:v,reason:y})=>{const{error:b}=await q.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:y}).eq("id",v);if(b)throw b;await q.functions.invoke("agent-booking",{body:{action:"cancel",booking_id:v}}).catch(w=>console.error("Google calendar cleanup failed:",w))},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),ne.success("Booking cancelled")},onError:v=>ne.error(v.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 Avt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function d$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=Avt.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(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(ca,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(Vn,{children:"Set your available hours for each day"})]}),e.jsx(Le,{className:"space-y-2",children:Avt.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,v;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:y=>t({id:g.id,start_time:y.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:(v=g.end_time)==null?void 0:v.slice(0,5),onBlur:y=>t({id:g.id,end_time:y.target.value})}),e.jsx(jn,{checked:g.is_active,onCheckedChange:y=>t({id:g.id,is_active:y})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(g.id),children:e.jsx(qn,{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(cn,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}function Evt(s){const[t,n,r]=s.split("-").map(Number);return Js(new Date(t,n-1,r),"MMM d, yyyy")}function q$s(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 u$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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(jq,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(Vn,{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(cn,{className:"h-4 w-4 mr-1"})," Block Dates"]})]}),e.jsxs(Le,{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:q$s(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:[Evt(m.start),m.end!==m.start&&` – ${Evt(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(mr,{className:"h-3.5 w-3.5"})})]},m.ids[0]))})]})]})}function V$s(){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}=c$t(),[f,g]=j.useState("1-on-1 Coaching Session"),[x,v]=j.useState(45),y=j.useMemo(()=>t.filter(w=>w.is_coaching_only),[t]);if(a)return e.jsx(je,{children:e.jsxs(Le,{className:"p-6 flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading your calendar…"]})});if(!s)return e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Su,{className:"h-5 w-5"})," Coaching calendar"]}),e.jsx(Vn,{children:"Set up your scheduler once, then open availability for the members assigned to you."})]}),e.jsx(Le,{children:e.jsxs($,{onClick:()=>i.mutate(),disabled:i.isPending,children:[i.isPending&&e.jsx(Ct,{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"),v(45))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"h-5 w-5"})," Coaching session types"]}),e.jsx(Vn,{children:"Only assigned members can book these. They stay hidden from your public booking page."})]}),e.jsxs(Le,{className:"space-y-3",children:[y.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."}):y.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(jn,{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($e,{variant:"secondary",children:"Coaching only"}),e.jsx($,{variant:"ghost",size:"sm",className:"ml-auto h-8 w-8 p-0",onClick:async()=>{await mo({title:"Delete session type?",description:`"${w.name}" will no longer be bookable.`,confirmText:"Delete",destructive:!0})&&c.mutate(w.id)},children:e.jsx(qn,{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=>v(parseInt(w.target.value)||30)})]}),e.jsxs($,{onClick:b,disabled:o.isPending,children:[e.jsx(cn,{className:"h-4 w-4 mr-1"})," Add"]})]})]})]}),e.jsx(d$t,{slots:n,onSave:w=>d.mutate(w),onDelete:w=>u.mutate(w)}),e.jsx(u$t,{blockedDates:r,onAdd:w=>h.mutate(w),onRemove:w=>m.mutate(w)}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Scheduling rules"}),e.jsx(Vn,{children:"Applies to coaching bookings on your calendar."})]}),e.jsxs(Le,{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 SZ(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 h$t(s=!0,t="coach"){const n=Zt(),r=st({queryKey:["google-calendar-connection",t],enabled:s,queryFn:async()=>await SZ(t,{action:"status"})}),a=()=>n.invalidateQueries({queryKey:["google-calendar-connection",t]}),i=mt({mutationFn:async()=>{const d=await SZ(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=mt({mutationFn:()=>SZ(t,{action:"disconnect"}),onSuccess:a}),o=mt({mutationFn:d=>SZ(t,{action:"settings",...d}),onSuccess:a}),c=mt({mutationFn:()=>SZ(t,{action:"refresh_calendars"}),onSuccess:a});return{status:r,connect:i,disconnect:l,updateSettings:o,refreshCalendars:c}}function m$t({scope:s="coach"}){const{status:t,connect:n,disconnect:r,updateSettings:a,refreshCalendars:i}=h$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"?(ne.success("Google Calendar connected"),t.refetch()):ne.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(je,{children:[e.jsx(St,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(gb,{className:"h-5 w-5"})," Google Calendar"]}),e.jsx(Vn,{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($e,{className:"bg-emerald-600 hover:bg-emerald-600 shrink-0",children:[e.jsx(Vr,{className:"h-3.5 w-3.5 mr-1"})," Connected"]})]})}),e.jsxs(Le,{className:"space-y-4",children:[t.isLoading&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{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(vl,{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(vl,{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:()=>ne.success("Google Calendar connected"),onError:d=>ne.error(d.message)}),disabled:n.isPending,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[n.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(gb,{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(jn,{checked:o.sync_enabled,onCheckedChange:d=>a.mutate({sync_enabled:d},{onError:u=>ne.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(jn,{checked:o.invite_guest!==!1,onCheckedChange:d=>a.mutate({invite_guest:d},{onError:u=>ne.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=>ne.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:()=>ne.success("Calendars refreshed"),onError:d=>ne.error(d.message)}),disabled:i.isPending,children:e.jsx(co,{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:()=>ne.success("Google Calendar reconnected"),onError:d=>ne.error(d.message)}),disabled:n.isPending,children:[n.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(co,{className:"h-4 w-4 mr-2"}),"Reconnect"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"text-destructive",disabled:r.isPending,onClick:async()=>{await mo({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:()=>ne.success("Google Calendar disconnected"),onError:u=>ne.error(u.message)})},children:[e.jsx(iV,{className:"h-4 w-4 mr-2"})," Disconnect"]})]})]})]})]})}function H$s(){const s=Zn(),{data:t,isLoading:n}=Wae(),r=Zt(),[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),[v,y]=j.useState([]),[b,w]=j.useState(""),[S,A]=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),y(U.specialties||[]),A(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:v,default_sessions_per_month:S}).eq("id",t.id);if(I(!1),U)return ne.error(U.message);ne.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},R=()=>{const U=b.trim();if(U){if(v.includes(U))return w("");y([...v,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(Va,{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(Ir,{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(je,{children:e.jsxs(Le,{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(jn,{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(Cvt,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Intro video"}),e.jsx(Cvt,{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:v.map(U=>e.jsxs($e,{variant:"secondary",className:"gap-1",children:[U,e.jsx("button",{onClick:()=>y(v.filter(W=>W!==U)),children:e.jsx(mr,{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(cn,{className:"h-4 w-4"})})]})]})]})}),e.jsx(je,{children:e.jsxs(Le,{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=>A(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(m$t,{}),e.jsx(V$s,{}),e.jsx(je,{children:e.jsx(Le,{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(G$s,{coachId:D.id})]})})}function G$s({coachId:s}){const[t,n]=j.useState("");Zt();const{data:r=[],refetch:a}=st({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 ne.error("Email required");const{error:d}=await q.from("coaching_invites").insert({coach_id:s,email:c});if(d)return ne.error(d.message);n(""),ne.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),ne.success("Link copied")},o=async c=>{await mo("Revoke this invite?")&&(await q.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(je,{children:e.jsxs(Le,{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(Sd,{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(cn,{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(Za,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(qn,{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 W$s="google_calendar";function K$s(){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:W$s,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(Ct,{className:"h-6 w-6 animate-spin mx-auto text-[#406E71]"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s})]})})}const Gce=[{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 Y$s(){const s=Zn(),t=Zt(),{data:n,isLoading:r}=Wae(),[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),[v,y]=j.useState(""),{data:b=[],isLoading:w}=st({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]),A=j.useMemo(()=>{const D={all:b.length};for(const O of Gce)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 ne.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 mo("Remove this person from the waitlist?"))return;const{error:O}=await q.from("coaching_waitlist").delete().eq("id",D);if(O)return ne.error(O.message);ne.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 ne.error((D==null?void 0:D.error)||(O==null?void 0:O.message)||"Could not send invite");ne.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:v}});if(O||D!=null&&D.error)return ne.error((D==null?void 0:D.error)||(O==null?void 0:O.message)||"Could not notify");ne.success(`Notified ${(D==null?void 0:D.count)||0} agents`),x(!1),y(""),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(Va,{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(Fg,{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:!A.pending,title:A.pending?"":"No pending applicants",children:[e.jsx($z,{className:"h-4 w-4 mr-2"}),"Notify all pending (",A.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 (",A.all,")"]}),Gce.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," (",A[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(je,{children:e.jsx(Le,{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=Gce.find(U=>U.value===D.status);return e.jsx(je,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(D),children:e.jsxs(Le,{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($e,{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 ",hu(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(Os,{open:!!c,onOpenChange:D=>!D&&d(null),children:e.jsx(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:c.name}),e.jsxs(Er,{children:["Joined ",hu(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(CZ,{label:"Email",value:c.email}),e.jsx(CZ,{label:"Phone",value:c.phone}),e.jsx(CZ,{label:"Brokerage",value:c.brokerage}),e.jsx(CZ,{label:"Years",value:c.years_in_business}),e.jsx(CZ,{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 ",hu(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:Gce.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(Nr,{className:"flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",className:"text-destructive",onClick:()=>I(c.id),children:[e.jsx(qn,{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(pn,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{f(""),h(!0)},children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(Os,{open:u,onOpenChange:h,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Invite to subscribe"}),e.jsxs(Er,{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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:P,children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(Os,{open:g,onOpenChange:x,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Notify all pending applicants"}),e.jsx(Er,{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:v,onChange:D=>y(D.target.value)}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:R,children:[e.jsx($z,{className:"h-4 w-4 mr-1"})," Send to ",A.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 CZ({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 Z$s(){const{data:s=[],isLoading:t}=st({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(wn,{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(Vr,{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(ei,{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(br,{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(wn,{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(Qa,{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(wn,{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(Vr,{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(Vr,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Vr,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(br,{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(Qa,{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 X$s=F2({name:yl().trim().min(1,"Name required").max(120),email:yl().trim().email("Invalid email").max(255),phone:yl().trim().max(40).optional().or(fx("")),brokerage:yl().trim().max(160).optional().or(fx("")),years_in_business:yl().max(40).optional().or(fx("")),biggest_challenge:yl().trim().max(1e3).optional().or(fx("")),preferred_package:yl().max(120).optional().or(fx("")),message:yl().trim().max(1500).optional().or(fx(""))});function Q$s({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=_s(),[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=X$s.safeParse(c);if(!m.success){ne.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){ne.error(f.message||"Could not join waitlist");return}ne.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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{children:["Join the waitlist",r?` — ${r}`:""]}),e.jsx(Er,{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(Nr,{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 J$s(){var x;const{slug:s}=Wi(),t=Zn(),{user:n}=_s(),[r,a]=j.useState(null),[i,l]=j.useState(!1),{data:o,isLoading:c}=st({queryKey:["coach-public",s],enabled:!!s,queryFn:async()=>{const v=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s||""),y=q.from("coaches").select("*"),{data:b}=v?await y.eq("id",s).maybeSingle():await y.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 v=>{if(!n){ne.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(v);const{data:y,error:b}=await q.functions.invoke("create-coaching-checkout",{body:{packageId:v}});if(a(null),b||y!=null&&y.error){ne.error((y==null?void 0:y.error)||(b==null?void 0:b.message)||"Checkout failed");return}y!=null&&y.url&&(window.location.href=y.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=(v,y)=>{const b=(v/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return y==="one_time"?b:`${b} / ${y}`};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(Va,{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(Ii,{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(wn,{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(v=>e.jsx($e,{className:"bg-white/15 text-white border-white/20",children:v},v))})]})]})]})}),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(E$s,{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(je,{children:e.jsx(Le,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):m.map(v=>{const y=v.accepting_clients===!1;return e.jsx(je,{className:`border-2 transition-colors ${y?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Le,{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:v.name}),y&&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"})]}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:v.description}),e.jsx("div",{className:"text-2xl font-bold mt-3",children:g(v.price_cents,v.billing_interval)}),y?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(Fg,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs($,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>d(v.id),disabled:r===v.id,children:[r===v.id?"Loading…":"Get Started",e.jsx(ma,{className:"h-4 w-4 ml-1"})]})]})},v.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(Fg,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(Q$s,{open:i,onOpenChange:l,coachId:f.id,coachName:h==null?void 0:h.name,packages:m.map(v=>({id:v.id,name:v.name}))})]})}const eUs=F2({full_name:yl().trim().min(2,"Please enter your full name").max(100),email:yl().trim().email("Enter a valid email").max(255),phone:yl().trim().max(40).optional().or(fx("")),brokerage:yl().trim().max(150).optional().or(fx("")),years_experience:yl().trim().max(40).optional().or(fx("")),specialties:yl().trim().max(500).optional().or(fx("")),why_coach:yl().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:yl().trim().max(2e3).optional().or(fx("")),website_url:yl().trim().max(300).optional().or(fx("")),linkedin_url:yl().trim().max(300).optional().or(fx(""))});function tUs(){const s=Zn(),[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=eUs.safeParse(i);if(!u.success){const f=(m=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:m[0];return ne.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 ne.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(Vr,{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(br,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(Va,{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(wn,{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(Yn,{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(Zl,{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(Im,{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(Vr,{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(ei,{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(e5,{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(e5,{label:"Email *",children:e.jsx(pe,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(e5,{label:"Phone",children:e.jsx(pe,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(e5,{label:"Current brokerage",children:e.jsx(pe,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(e5,{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(e5,{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(e5,{label:"Website",children:e.jsx(pe,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(e5,{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(e5,{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(e5,{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 e5({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 Ist="/assets/testimonial-avatar-1-BsCQFauB.jpg",Lst="/assets/testimonial-avatar-2-B6VPVc2t.jpg",Rst="/assets/testimonial-avatar-3-GuEFwYUE.jpg",Dst="/assets/testimonial-avatar-4-98iKMtkB.jpg",Fst="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",sUs=[Ist,Lst,Rst,Dst,Fst],nUs=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Gae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:QLe},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:JLe},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:e6e},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:t6e},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:s6e}];function rUs({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(wn,{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 aUs=F2({name:yl().trim().min(2,"Name must be at least 2 characters").max(100),email:yl().trim().email("Please enter a valid email address").max(255),phone:yl().trim().min(10,"Please enter a valid phone number").max(20).optional().or(fx("")),brokerage:yl().trim().max(200).optional().or(fx(""))}),iUs=[{icon:ef,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:yd,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:Ea,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Ah,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Qr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:dl,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],oUs=[{category:"Marketing Studio",icon:gm,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:ph,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:Sv,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:Qx,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:af,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:wi,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],lUs=[{icon:Yn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:wn,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:Rg,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ui,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Gl,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:Qp,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],cUs=[{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."}],Wce="bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]",dUs=()=>{const s=Zn(),[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=aUs.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),ne.error(x.message||"Something went wrong. Please try again.");return}if(g!=null&&g.error){ne.error(g.error);return}ne.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),ne.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(Dl,{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:$Ee,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(wn,{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(Vr,{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(Vr,{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:sUs.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(ei,{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(Tf,{className:"h-4 w-4 text-white/60"})," Cancel anytime"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Qp,{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(je,{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(Le,{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(By,{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(Ct,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(Qa,{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 ${Wce}`})}),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:nUs.map(d=>e.jsx(rUs,{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(Qa,{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(T4,{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:iUs.map((d,u)=>e.jsxs(je,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(St,{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(Et,{className:"text-xl font-sans",children:d.title})]}),e.jsx(Le,{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 ${Wce}`})}),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:oUs.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(ma,{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(wn,{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 ${Wce}`})}),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(wn,{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(je,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(St,{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(Et,{className:"text-lg font-semibold text-white",children:d.title})]}),e.jsx(Le,{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:cUs.map((d,u)=>e.jsx(je,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Le,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(h=>e.jsx(ei,{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(Tf,{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(Qp,{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(Yn,{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(je,{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 ${Wce}`})}),e.jsxs(Le,{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(Qa,{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:NG,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."})]})})})]})]})},uUs=()=>{const s=Zn();return e.jsxs(e.Fragment,{children:[e.jsx(Dl,{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:$Ee,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(je,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(Le,{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(Vr,{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(kx,{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(pn,{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(Qa,{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:NG,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},hUs="https://us06web.zoom.us/meeting/register/7Ybq3ZIkRn2_RLkkv_uY8A",Kce="ld-open-house-invite-dismissed";function f$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(`${Kce}-${s}`))return;let o=null;const c=d=>{d.clientY<=0&&!localStorage.getItem(`${Kce}-${s}`)&&a(!0)};return o=setTimeout(()=>{localStorage.getItem(`${Kce}-${s}`)||a(!0)},n),document.addEventListener("mouseleave",c),()=>{o&&clearTimeout(o),document.removeEventListener("mouseleave",c)}},[s,n]);const i=()=>{a(!1),localStorage.setItem(`${Kce}-${s}`,"1")};return e.jsx(Os,{open:r,onOpenChange:l=>!l&&i(),children:e.jsx(Fs,{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(mr,{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(fa,{className:"h-6 w-6 ld-gold-text"})}),e.jsxs(Us,{children:[e.jsx($s,{className:"text-xl font-bold leading-tight text-white",children:t}),e.jsxs(Er,{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(Ea,{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:hUs,target:"_blank",rel:"noreferrer",className:"gap-2",children:["Register for the Open House",e.jsx(Ir,{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 p$t=Date.UTC(2026,8,12,3,59,59),O7e="Friday, September 11 at 11:59 PM ET",z7e=300,Yce=39*12,mUs=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Gae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:QLe},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:JLe},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:e6e},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:t6e},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:s6e}],fUs=[{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."}],pUs="https://www.google.com/search?q=levelup+consulting+group#lrd=0x8842f50045c4bd33:0xc9b99b5330a91b3f,1,,,,",g$t=[{icon:Yn,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:s7,title:"Full CRM & Contact Hub",desc:"Contacts, tags, smart follow-ups, lead ponds and team assignments — your database finally organized.",value:600},{icon:yb,title:"Deal Pipeline",desc:"Track every transaction from offer to closing with tasks, forms and commission math built in.",value:480},{icon:jx,title:"Staging Studio",desc:"AI virtual staging with MLS-ready before/after photos — no photographer or stager needed.",value:1200},{icon:yd,title:"Marketing & Social Studio",desc:"300+ branded templates, social posts, postcards and the weekly Reels engine.",value:720},{icon:cl,title:"Lead Sites",desc:"SEO-optimized neighborhood and listing websites that rank on Google and capture leads 24/7.",value:960},{icon:af,title:"Academy Training",desc:"On-demand video training on lead gen, marketing and tech — live weekly sessions too.",value:588},{icon:l_,title:"Forms & E-Signature",desc:"Upload any PDF, map fields, send for signature — done from one place.",value:300},{icon:fa,title:"Weekly Reels & Video Tools",desc:"Personalized Instagram scripts delivered every Monday, plus screen recording and virtual backgrounds.",value:468},{icon:no,title:"Reviews Engine",desc:"Collect Google and video reviews with a single link — your reputation on autopilot.",value:240},{icon:wn,title:"ChatGPT App + 30 AI Tools",desc:"Your entire business controllable from ChatGPT — create contacts, open houses, marketing assets and more.",value:500},{icon:Ea,title:"My Calendar & Booking",desc:"Agent-first calendar with time zones, Google Calendar sync and self-serve booking links.",value:144}],Tvt=g$t.reduce((s,t)=>s+t.value,0),gUs=[{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 x$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 Mvt({dark:s=!1}){const{d:t,h:n,m:r,sec:a,expired:i}=x$t(p$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 Pvt(){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(ei,{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(wn,{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 yUs(){const{expired:s}=x$t(p$t),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),d=j.useMemo(()=>[Ist,Lst,Rst,Dst,Fst],[]),u=Yce-z7e,h=async()=>{if(!r.trim()||!r.includes("@")){ne.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 jae?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),ne.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(Dl,{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 ${O7e}.`}),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:["$",Yce]})]})]}),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:NG,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 ",O7e]})]}),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(ei,{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 ($",Yce,"/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(Mvt,{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(Qa,{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(Ct,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:["Lock in $300/yr ",e.jsx(Qa,{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(jc,{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 $",Tvt.toLocaleString(),"/year at market rates."]})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-5",children:[g$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:["$",Tvt.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:mUs.map(m=>e.jsx(xUs,{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(Pvt,{}),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:fUs.map(m=>e.jsxs("blockquote",{className:"bg-card border rounded-2xl p-5 flex flex-col gap-3",children:[e.jsx(Pvt,{}),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:pUs,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(mr,{className:"h-4 w-4 mt-0.5 shrink-0"})," $",Yce," per year"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(mr,{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(ma,{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:["$",z7e]}),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(ma,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," $",z7e," per year — save $",u," vs monthly"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Rq,{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(ma,{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(Tf,{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:gUs.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(Mvt,{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(Qa,{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(jc,{className:"h-3 w-3"})," Secure Stripe checkout · Ends ",O7e]}),e.jsxs("p",{className:"text-white/50 text-sm mt-10",children:["© ",new Date().getFullYear()," LevelUp Consulting Group"]})]})]}),e.jsx(f$t,{pageKey:"individual-labor-day-2026",headline:"Not ready to join the LevelUp family yet?"})]})}const y$t=Date.UTC(2026,8,12,3,59,59),B7e="Friday, September 11 at 11:59 PM ET",aQ=399,a3e=499,Ivt=(a3e-aQ)*12,vUs=[{key:"dashboard",label:"Agent Command Center",caption:"Every agent's day — smart queue, calendar and pipeline in one view.",src:Gae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history for every agent.",src:QLe},{key:"pipeline",label:"Deal Pipeline",caption:"Every transaction with tasks, forms and commission tracking built in.",src:JLe},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:e6e},{key:"coaching",label:"Coaching",caption:"Live coaching sessions your agents book themselves.",src:t6e},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded.",src:s6e}],bUs=[{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."}],_Us="https://www.google.com/search?q=levelup+consulting+group#lrd=0x8842f50045c4bd33:0xc9b99b5330a91b3f,1,,,,",wUs=[{icon:vb,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:s7,title:"Full CRM & Contact Hub",desc:"Contacts, tags, smart follow-ups, lead ponds and team assignments — every agent's database finally organized."},{icon:yb,title:"Deal Pipeline",desc:"Transactions from offer to closing with tasks, forms and commission math built in."},{icon:jx,title:"Staging Studio",desc:"AI virtual staging with MLS-ready before/after photos for every listing."},{icon:yd,title:"Marketing & Social Studio",desc:"300+ branded templates, social posts, postcards and the weekly Reels engine."},{icon:cl,title:"Lead Sites",desc:"SEO-optimized websites that rank on Google and capture leads 24/7."},{icon:af,title:"Academy Training",desc:"On-demand video training on lead gen, marketing and tech."},{icon:l_,title:"Forms & E-Signature",desc:"Upload any PDF, map fields, send for signature — done from one place."},{icon:fa,title:"Weekly Reels & Video Tools",desc:"Personalized Instagram scripts every Monday, plus screen recording and virtual backgrounds."}],jUs=[{icon:wi,title:"Your Own Brokerage Hub",desc:"Brand profiles, announcements and resources pushed to every agent from one place."},{icon:l_,title:"Brokerage Form Library",desc:"Publish your official forms office-wide — agents use them read-only or copy to customize."},{icon:lc,title:"Recruiting Pipeline",desc:"Customizable recruiting stages to attract and track your next agents."},{icon:gm,title:"Office-Wide Communication",desc:"Broadcasts, brokerage content and resource libraries your agents actually use."}],NUs=[{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 v$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 Lvt({dark:s=!1}){const{d:t,h:n,m:r,sec:a,expired:i}=v$t(y$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 Rvt(){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(ei,{className:"h-4 w-4 fill-accent text-accent"},t))})}function kUs({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(wn,{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 SUs(){const{expired:s}=v$t(y$t),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),d=j.useMemo(()=>[Ist,Lst,Rst,Dst,Fst],[]),u=async()=>{if(!r.trim()||!r.includes("@")){ne.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 jae?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),ne.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(Dl,{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 ${B7e}.`}),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:["$",aQ,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:["$",a3e]})]})]}),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:NG,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 ",B7e]})]}),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(ei,{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(Lvt,{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(Qa,{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(Ct,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:["Partner at $399/mo ",e.jsx(Qa,{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(jc,{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:wUs.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:jUs.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:vUs.map(h=>e.jsx(kUs,{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(Rvt,{}),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:bUs.map(h=>e.jsxs("blockquote",{className:"bg-card border rounded-2xl p-5 flex flex-col gap-3",children:[e.jsx(Rvt,{}),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:_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:"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 $",aQ,"."]})]}),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:["$",a3e]}),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(mr,{className:"h-4 w-4 mt-0.5 shrink-0"})," $",(a3e*12).toLocaleString()," per year"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(mr,{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(ma,{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 $",Ivt.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:["$",aQ]}),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(ma,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," $",(aQ*12).toLocaleString()," per year — save $",Ivt.toLocaleString()," vs standard"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Rq,{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(ma,{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(Tf,{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:NUs.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(Lvt,{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(Qa,{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(jc,{className:"h-3 w-3"})," Secure Stripe checkout · Ends ",B7e]}),e.jsxs("p",{className:"text-white/50 text-sm mt-10",children:["© ",new Date().getFullYear()," LevelUp Consulting Group"]})]})]}),e.jsx(f$t,{pageKey:"brokerage-labor-day-2026",headline:"Not ready to partner with LevelUp yet?"})]})}const CUs=["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"],AUs=["Everything in Individual, plus:","Unlimited agent seats","Brokerage admin dashboard","Team performance analytics","Agent onboarding tools","Priority support"],EUs=()=>{const{user:s,loading:t}=_s(),n=Zn(),[r]=Nc(),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 v=`/upgrade?plan=${x}`;n(`/auth?next=${encodeURIComponent(v)}`)},f=async x=>{var v;if(!(s!=null&&s.email)){m(x);return}o(!0),d(x);try{const{data:y,error:b}=await q.functions.invoke("create-checkout",{body:{tier:x,email:s.email,name:((v=s.user_metadata)==null?void 0:v.full_name)||s.email,userId:s.id,couponCode:u.trim()||void 0,skipTrial:!0}});if(b)throw b;if(y!=null&&y.url)window.location.href=y.url;else throw new Error("No checkout URL returned")}catch(y){console.error("Checkout error:",y),ne.error(y.message||"Failed to start checkout. Please try again."),o(!1),d(null)}},g=(x,v,y,b,w,S,A)=>e.jsxs(je,{className:`relative border-2 transition-colors ${A?"border-primary shadow-lg":"border-amber-500/30"} ${i===x?"ring-2 ring-primary ring-offset-2":""}`,children:[i===x&&e.jsx($e,{className:"absolute -top-3 left-1/2 -translate-x-1/2 bg-primary text-primary-foreground",children:"Recommended for you"}),e.jsxs(Le,{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 ${A?"bg-primary/10":"bg-amber-500/10"}`,children:S}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-xl",children:v}),e.jsxs("p",{className:`text-3xl font-bold mt-1 ${A?"text-primary":"text-amber-600"}`,children:[y,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(ma,{className:`h-4 w-4 mt-0.5 shrink-0 ${A?"text-primary":"text-amber-600"}`}),e.jsx("span",{children:E})]},E))}),e.jsx($,{className:"w-full",variant:A?"default":"outline",disabled:l||t,onClick:()=>f(x),children:l&&c===x?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Opening secure checkout…"]}):s?e.jsxs(e.Fragment,{children:[e.jsx(wn,{className:"h-4 w-4 mr-2"}),"Upgrade to ",v]}):e.jsxs(e.Fragment,{children:[e.jsx(GI,{className:"h-4 w-4 mr-2"}),"Sign in & upgrade to ",v]})})]})]});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:n6e,alt:"LevelUp",className:"h-10 mx-auto mb-8"}),e.jsx($e,{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",CUs,e.jsx(Yn,{className:"h-6 w-6 text-primary"}),!0),g("brokerage_over_25","Brokerage","$499","For teams and brokerages",AUs,e.jsx(wi,{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(pn,{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."})]})})},TUs=F2({viewerName:yl().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:yl().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:yl().max(20,"Phone must be less than 20 characters").optional(),message:yl().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function MUs({shareToken:s,agentName:t,hasContact:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),d=yLe({resolver:vLe(TUs),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(je,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(Le,{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(Vr,{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(je,{children:[e.jsxs(St,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ah,{className:"h-5 w-5 text-primary"}),e.jsx(Et,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(Vn,{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(Le,{children:e.jsx(jLe,{...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(_g,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Your Name *"}),e.jsx(Up,{children:e.jsx(pe,{placeholder:"John Smith",...h})}),e.jsx(m_,{})]})}),e.jsx(_g,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Email *"}),e.jsx(Up,{children:e.jsx(pe,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(m_,{})]})})]}),!n&&e.jsx(_g,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Phone (optional)"}),e.jsx(Up,{children:e.jsx(pe,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(m_,{})]})}),e.jsx(_g,{control:d.control,name:"message",render:({field:h})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Message *"}),e.jsx(Up,{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(m_,{})]})}),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(Ct,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const PUs=()=>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(ei,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(ei,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(ei,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(ei,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(ei,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(CE,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),IUs=()=>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(wn,{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(ei,{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(wn,{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(ei,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(ei,{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(CE,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),LUs=()=>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(US,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(US,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(US,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(US,{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"})]}),RUs=()=>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(Im,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(ei,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(Im,{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(ei,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(ei,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),DUs=()=>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(US,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(US,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(Cq,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),FUs=()=>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(Fz,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(Fz,{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(wn,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(wn,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),OUs=()=>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(QI,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(QI,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(QI,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(Zj,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(Zj,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(Zj,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(Zj,{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(ei,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),zUs=()=>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"})]}),BUs=()=>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(ei,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(ei,{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(ei,{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(ei,{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(wn,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(kx,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(kx,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),$Us=()=>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(ei,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(wn,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(wn,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),UUs=()=>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(pE,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(pE,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(pE,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(pE,{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"})]})]})]}),qUs=()=>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(ei,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(ei,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(Im,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(Im,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(CE,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),VUs=()=>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(Rg,{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(kx,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(dl,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),HUs=()=>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"})]}),GUs=()=>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(JN,{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(JN,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(wn,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(JN,{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"})]}),WUs=()=>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(__,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(__,{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(wn,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(kx,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),KUs=()=>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(kx,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(kx,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(__,{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(wn,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(wn,{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"})]}),YUs=()=>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(__,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(__,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(__,{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(kx,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(wn,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(ei,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),ZUs=()=>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(__,{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(wn,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(WN,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),Dvt=()=>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"})]}),XUs=()=>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"})]}),QUs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(WN,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(wn,{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"})]}),JUs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(E4,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx($q,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(E4,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),AZ=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(wn,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(kx,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(wn,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),Fvt=()=>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(wn,{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"})]}),TGe=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(wn,{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(XUs,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(hJ,{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(AZ,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(E4,{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(JUs,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(Gl,{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(Yn,{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(AZ,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(Im,{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(Dvt,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(ui,{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(Fvt,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx($q,{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(AZ,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(Rg,{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(VUs,{})},{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(HUs,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(JN,{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(GUs,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(ei,{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(BUs,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(Cq,{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(DUs,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(US,{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(LUs,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(Im,{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(RUs,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(CE,{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(PUs,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(sh,{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(IUs,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(Im,{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(qUs,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(Fz,{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(FUs,{})},{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(zUs,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(QI,{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(OUs,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(wn,{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($Us,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(pE,{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(UUs,{})},{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(WUs,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(kx,{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(KUs,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(Ea,{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(Fvt,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(su,{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(AZ,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(tC,{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(WN,{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(QUs,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(__,{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(YUs,{})},{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(ZUs,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx($y,{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(AZ,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(Im,{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(Dvt,{})}],eqs=[{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 tqs(s){return TGe.filter(t=>t.category===s)}function vV(s){return TGe.find(t=>t.id===s)||TGe[0]}function Ovt(){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),v=j.useRef(0),y=(()=>{const U=new URLSearchParams(window.location.search);return t||U.get("rt")||null})(),b=j.useCallback((U,W=!1)=>{if(!y||U<=0)return;const V=Math.max(1,Math.round(U));if(V<=v.current)return;const Z=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(y)}&e=watch&ws=${V}`;W&&navigator.sendBeacon?navigator.sendBeacon(Z):fetch(Z,{method:"GET",keepalive:W}).catch(()=>{}),v.current=Math.max(v.current,V)},[y]);j.useEffect(()=>{var ae;if(!m||!(n!=null&&n.playback_url)||!y)return;let U=!1;const W=()=>{x.current>0&&b(x.current,!0)},V=()=>{document.visibilityState==="hidden"&&W()},G=()=>{W()},Z=()=>{var re;if(U||!g.current||!((re=window.playerjs)!=null&&re.Player))return;const le=new window.playerjs.Player(g.current);le.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))}),le.on("pause",()=>{x.current>0&&b(x.current)}),le.on("ended",()=>{x.current>0&&b(x.current,!0)})},X=document.querySelector('script[data-bunny-playerjs="true"]');if((ae=window.playerjs)!=null&&ae.Player)Z();else if(X)X.addEventListener("load",Z,{once:!0});else{const le=document.createElement("script");le.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",le.async=!0,le.defer=!0,le.dataset.bunnyPlayerjs="true",le.onload=Z,document.body.appendChild(le)}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,y,b]),j.useEffect(()=>{x.current=0,v.current=0},[y,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(Z=>{document.querySelectorAll(Z).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:Z}=await q.storage.from("avatars").list(`${W.owner_user_id}`);if(Z&&Z.length>0){const{data:X}=q.storage.from("avatars").getPublicUrl(`${W.owner_user_id}/${Z[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,A=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=vV((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(Ct,{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(je,{className:"max-w-md w-full",children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(fa,{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(Dl,{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(Ii,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(za,{className:"bg-primary/10 text-primary font-semibold",children:A(a.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children: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(pn,{className:"h-4 w-4"})})})]})]}),e.jsx(je,{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(fa,{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(Ou,{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(Ou,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(MUs,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function sqs(){return j.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(bet,{})}function nqs(){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(Ct,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const rqs=[{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:wi,points:["Pitch Mode to win the assignment","Institutional-grade microsite","Gated OM & investor tracking"],featured:!0}];function aqs(){const s=Zn(),{search:t}=qu();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(Va,{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:rqs.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(wn,{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(Qa,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]},n.key)})})]})})}const b$t=()=>st({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}}),_$t=s=>{const{user:t,brokerageId:n}=_s();return st({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=>zst(Ost(o)))}})};function Ost(s){return s&&Array.isArray(s.commercial)&&(s.commercial=s.commercial[0]??null),s}function zst(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 Bst=()=>{const{user:s}=_s();return st({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t.map(r=>zst(Ost(r)))},enabled:!!s})},Kae=s=>{const{user:t}=_s();return st({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}),zst(Ost(n))},enabled:!!s})},w$t=()=>{const s=Zt(),{user:t}=_s();return mt({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"]})}})},iqs=()=>{const s=Zt();return mt({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"]})}})},j$t=()=>{const s=Zt();return mt({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]})}})},N$t=()=>{const s=Zt();return mt({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"]})}})},k$t=()=>{const s=Zt();return mt({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"]})}})},S$t=()=>{const s=Zt();return mt({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"]})}})},C$t=()=>{const s=Zt();return mt({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"]})}})},A$t=()=>{const s=Zt();return mt({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"]})}})},oqs=()=>{const{user:s}=_s();return st({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})},E$t=()=>{const s=Zt(),{user:t}=_s();return mt({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"]})}})},T$t=s=>{const{user:t}=_s();return st({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=Zt(),{user:t}=_s();return mt({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"]})}})},cqs=s=>{const{user:t}=_s();return st({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}=_s();return mt({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}})},uqs=()=>{const{user:s}=_s();return st({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})},hqs=()=>{const s=Zt(),{user:t}=_s();return mt({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"]})}})},mqs=()=>st({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}}}),fqs=()=>{const{user:s,brokerageId:t}=_s();return st({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})},$7e=q,pp=s=>s===""||s==null?null:Number(String(s).replace(/[^0-9.\-]/g,"")),pqs={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 zvt({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(mr,{className:"h-4 w-4"})})]},i)),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>r([...n,""]),children:[e.jsx(cn,{className:"mr-1.5 h-3.5 w-3.5"})," Add"]})]})}function U7e({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(mr,{className:"h-4 w-4"})})]},l)),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>a([...r,{}]),children:[e.jsx(cn,{className:"mr-1.5 h-3.5 w-3.5"})," Add row"]})]})}const gqs=[{key:"radius_1",label:"1 mile"},{key:"radius_3",label:"3 miles"},{key:"radius_5",label:"5 miles"}],xqs=[{key:"population",label:"Population"},{key:"households",label:"Households"},{key:"avg_income",label:"Avg income"},{key:"daytime_pop",label:"Daytime pop."}];function Bvt(){const{listingId:s}=Wi(),t=Zn(),{user:n,loading:r}=_s(),a=!!s,{data:i,isLoading:l}=Kae(s||""),{data:o}=k7t(s);w$t();const c=j$t(),d=S7t(),u=C7t(),[h,m]=j.useState(null),[f,g]=j.useState(pqs),[x,v]=j.useState([""]),[y,b]=j.useState([]),[w,S]=j.useState([]),[A,E]=j.useState([]),[I,P]=j.useState([]),[R,D]=j.useState({}),[O,U]=j.useState(!1),[W,V]=j.useState([]),[G,Z]=j.useState([]),X=!a||!!(n!=null&&n.id)&&(i==null?void 0:i.agent_id)===n.id;j.useEffect(()=>{!a||r||l||!i||X||(ne.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 be=Array.from(ue);V(Ee=>[...Ee,...be]),Z(Ee=>[...Ee,...be.map(ke=>URL.createObjectURL(ke))])},le=ue=>{URL.revokeObjectURL(G[ue]),V(be=>be.filter((Ee,ke)=>ke!==ue)),Z(be=>be.filter((Ee,ke)=>ke!==ue))},re=async ue=>{if(!W.length)return;const{count:be}=await $7e.from("listing_photos").select("id",{count:"exact",head:!0}).eq("listing_id",ue),Ee=be??0;for(let ke=0;keg(Ee=>({...Ee,[ue]:be}));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(be=>({...be,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})),v((ue=o.investment_highlights)!=null&&ue.length?o.investment_highlights:[""]),b(o.property_highlights??[]),S((o.spaces??[]).map(be=>({...be,sf:(be==null?void 0:be.sf)!=null?String(be.sf):""}))),E((o.tenants??[]).map(be=>({...be,sf:(be==null?void 0:be.sf)!=null?String(be.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",ve=j.useMemo(()=>({deal_type:f.deal_type,commercial_type:f.commercial_type,opportunity_title:f.opportunity_title||null,submarket:f.submarket||null,asking_price:pp(f.asking_price),lease_rate:pp(f.lease_rate),lease_rate_unit:f.lease_rate_unit,lease_type:f.lease_type||null,building_sf:pp(f.building_sf),available_sf:pp(f.available_sf),lot_acres:pp(f.lot_acres),units:pp(f.units),floors:pp(f.floors),parking_spaces:pp(f.parking_spaces),zoning:f.zoning||null,occupancy_pct:pp(f.occupancy_pct),tenancy:f.tenancy||null,noi:pp(f.noi),cap_rate:pp(f.cap_rate),gross_income:pp(f.gross_income),operating_expenses:pp(f.operating_expenses),broker_coop_pct:pp(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(be=>String(be??"").trim())),tenants:A.filter(ue=>Object.values(ue).some(be=>String(be??"").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(be=>String(be??"").trim()))),property_highlights:y.map(ue=>ue.trim()).filter(Boolean),price_per_sf:pp(f.asking_price)&&pp(f.building_sf)?Math.round(pp(f.asking_price)/pp(f.building_sf)*100)/100:null,price_per_unit:pp(f.asking_price)&&pp(f.units)?Math.round(pp(f.asking_price)/pp(f.units)):null}),[f,x,y,w,A,I,R]),fe=async()=>{if(a&&!X){ne.error("Only the listing agent can edit this commercial listing");return}if(!f.city||!f.state){ne.error("City and state are required");return}if(!a&&!h){ne.error("Choose whether you already have the assignment");return}U(!0);try{let ue=s;const be={property_address:f.property_address||null,city:f.city,state:f.state,neighborhood:f.submarket||null,price:pp(f.asking_price)??0,property_type:"commercial",description:f.description||null,year_built:pp(f.year_built),square_footage:pp(f.building_sf)},Ee=h==="pitch",ke=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},Ie=!Ee&&(ke.is_public||ke.show_on_lead_site||ke.allow_sharing)?"active":"coming_soon";if(a&&ue)await c.mutateAsync({id:ue,...be,...ke,...Ie==="active"?{status:"active"}:{}});else{const Fe=await $7e.from("listings").insert({...be,...ke,agent_id:n.id,listing_class:"commercial",lifecycle_stage:Ee?"pitch":"won",status:Ie}).select().single();if(Fe.error)throw Fe.error;ue=Fe.data.id,Ee&&await u.mutateAsync({listingId:ue,values:{launch_plan:N7t}})}await d.mutateAsync({listingId:ue,values:ve}),await re(ue),ne.success(a?"Commercial listing updated":"Commercial listing created"),t(`/mission-control/listings/${ue}/commercial`)}catch(ue){console.error(ue),ne.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(Ct,{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(Va,{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(ph,{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(Va,{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(wi,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"The opportunity"}),e.jsx(Vn,{children:"How this deal is positioned to the market."})]}),e.jsxs(Le,{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(SL).map(([ue,be])=>e.jsx(Ge,{value:ue,children:be},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(r6).map(([ue,be])=>e.jsx(Ge,{value:ue,children:be},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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Location"})}),e.jsxs(Le,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Pricing"})}),e.jsxs(Le,{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"}),JRs.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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Building & site"})}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Investment metrics"}),e.jsx(Vn,{children:"Only what you enter is shown on the microsite."})]}),e.jsxs(Le,{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(jn,{checked:f.opportunity_zone,onCheckedChange:ue=>te("opportunity_zone",ue)})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Highlights"}),e.jsx(Vn,{children:"3–6 reasons this opportunity matters. These headline the microsite."})]}),e.jsxs(Le,{className:"space-y-6",children:[e.jsx(zvt,{label:"Investment highlights",placeholder:"e.g. 12-year NNN lease to investment-grade tenant",items:x,onChange:v}),e.jsx(zvt,{label:"Property highlights",placeholder:"e.g. 32' clear height, 14 dock doors",items:y,onChange:b})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Spaces, tenants & market data"}),e.jsx(Vn,{children:"Everything here is optional — the microsite only renders the sections you fill in."})]}),e.jsxs(Le,{className:"space-y-8",children:[e.jsx(U7e,{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(U7e,{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:A,onChange:E}),e.jsx(U7e,{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."})]}),gqs.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}),xqs.map(be=>{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:be.label}),e.jsx(pe,{value:((Ee=R[ue.key])==null?void 0:Ee[be.key])??"",onChange:ke=>D({...R,[ue.key]:{...R[ue.key]??{},[be.key]:ke.target.value}})})]},be.key)})]},ue.key))]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Photography"}),e.jsx(Vn,{children:"Cinematic exterior, aerial and interior imagery drives the microsite hero and gallery."})]}),e.jsxs(Le,{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(cn,{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,be)=>e.jsxs("div",{className:"group relative aspect-[4/3] overflow-hidden rounded-md border",children:[e.jsx("img",{src:ue,alt:`Commercial photo ${be+1}`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>le(be),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(mr,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Distribution & sharing"}),e.jsx(Vn,{children:"Choose where this opportunity appears. You control the Listing Exchange, your own website, and the public commercial marketplace independently."})]}),e.jsxs(Le,{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(jn,{checked:f.site_only,onCheckedChange:ue=>g(be=>({...be,site_only:ue,is_public:ue?!1:be.is_public,show_on_lead_site:ue?!0:be.show_on_lead_site,share_with_brokerage:ue?!1:be.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(jn,{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(jn,{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(jn,{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(jn,{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(jn,{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(jn,{checked:f.open_to_social_promotion,disabled:f.site_only,onCheckedChange:ue=>te("open_to_social_promotion",ue)})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Confidentiality & document gating"})}),e.jsxs(Le,{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(jn,{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(jn,{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:fe,disabled:O,children:[O&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),a?"Save changes":"Create & continue"]})]})})]})}function r6e(s){return st({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 M$t(){const{user:s}=_s(),t=Zt();return mt({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 P$t(){const s=Zt();return mt({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 yqs(){const s=Zt();return mt({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 vqs(){const s=Zt();return mt({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 $st(s){const{data:t,error:n}=await q.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}function bqs(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const a6e=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function aK(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function Ust(s){return"nodeType"in s}function $w(s){var t,n;return s?aK(s)?s:Ust(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function qst(s){const{Document:t}=$w(s);return s instanceof t}function Yae(s){return aK(s)?!1:s instanceof $w(s).HTMLElement}function I$t(s){return s instanceof $w(s).SVGElement}function iK(s){return s?aK(s)?s.document:Ust(s)?qst(s)?s:Yae(s)||I$t(s)?s.ownerDocument:document:document:document}const K4=a6e?j.useLayoutEffect:j.useEffect;function Vst(s){const t=j.useRef(s);return K4(()=>{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 sse(s,t){t===void 0&&(t=[s]);const n=j.useRef(s);return K4(()=>{n.current!==s&&(n.current=s)},t),n}function Zae(s,t){const n=j.useRef();return j.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function UEe(s){const t=Vst(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 MGe(s){const t=j.useRef();return j.useEffect(()=>{t.current=s},[s]),t.current}let q7e={};function Xae(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 L$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 bV=L$t(1),nse=L$t(-1);function wqs(s){return"clientX"in s&&"clientY"in s}function Hst(s){if(!s)return!1;const{KeyboardEvent:t}=$w(s.target);return t&&s instanceof t}function jqs(s){if(!s)return!1;const{TouchEvent:t}=$w(s.target);return t&&s instanceof t}function PGe(s){if(jqs(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 wqs(s)?{x:s.clientX,y:s.clientY}:null}const TL=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[TL.Translate.toString(s),TL.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),$vt="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Nqs(s){return s.matches($vt)?s:s.querySelector($vt)}const kqs={display:"none"};function Sqs(s){let{id:t,value:n}=s;return Kt.createElement("div",{id:t,style:kqs},n)}function Cqs(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 Kt.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function Aqs(){const[s,t]=j.useState("");return{announce:j.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const R$t=j.createContext(null);function Eqs(s){const t=j.useContext(R$t);j.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function Tqs(){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 Mqs={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. `},Pqs={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 Iqs(s){let{announcements:t=Pqs,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=Mqs}=s;const{announce:i,announcement:l}=Aqs(),o=Xae("DndLiveRegion"),[c,d]=j.useState(!1);if(j.useEffect(()=>{d(!0)},[]),Eqs(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=Kt.createElement(Kt.Fragment,null,Kt.createElement(Sqs,{id:r,value:a.draggable}),Kt.createElement(Cqs,{id:o,announcement:l}));return n?yv.createPortal(u,n):u}var p0;(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"})(p0||(p0={}));function qEe(){}function CG(s,t){return j.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function i6e(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const mC=Object.freeze({x:0,y:0});function D$t(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function F$t(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function Lqs(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function Uvt(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 O$t(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function qvt(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 o6e=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=qvt(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=D$t(qvt(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(F$t)},Rqs=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=Uvt(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=Uvt(c),u=a.reduce((m,f,g)=>m+D$t(d[g],f),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(F$t)};function Dqs(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=Dqs(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(Lqs)};function Oqs(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function z$t(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:mC}function zqs(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 Bqs=zqs(1);function $qs(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 Uqs(s,t,n){const r=$qs(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 qqs={ignoreTransform:!1};function oK(s,t){t===void 0&&(t=qqs);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=$w(s).getComputedStyle(s);d&&(n=Uqs(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 Vvt(s){return oK(s,{ignoreTransform:!0})}function Vqs(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function Hqs(s,t){return t===void 0&&(t=$w(s).getComputedStyle(s)),t.position==="fixed"}function Gqs(s,t){t===void 0&&(t=$w(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 l6e(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(qst(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!Yae(a)||I$t(a)||n.includes(a))return n;const i=$w(s).getComputedStyle(a);return a!==s&&Gqs(a,i)&&n.push(a),Hqs(a,i)?n:r(a.parentNode)}return s?r(s):n}function B$t(s){const[t]=l6e(s,1);return t??null}function V7e(s){return!a6e||!s?null:aK(s)?s:Ust(s)?qst(s)||s===iK(s).scrollingElement?window:Yae(s)?s:null:null}function $$t(s){return aK(s)?s.scrollX:s.scrollLeft}function U$t(s){return aK(s)?s.scrollY:s.scrollTop}function IGe(s){return{x:$$t(s),y:U$t(s)}}var dv;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(dv||(dv={}));function q$t(s){return!a6e||!s?!1:s===document.scrollingElement}function V$t(s){const t={x:0,y:0},n=q$t(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 Wqs={x:.2,y:.2};function Kqs(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=Wqs);const{isTop:d,isBottom:u,isLeft:h,isRight:m}=V$t(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=dv.Backward,g.y=r*Math.abs((t.top+x.height-i)/x.height)):!u&&c>=t.bottom-x.height&&(f.y=dv.Forward,g.y=r*Math.abs((t.bottom-x.height-c)/x.height)),!m&&o>=t.right-x.width?(f.x=dv.Forward,g.x=r*Math.abs((t.right-x.width-o)/x.width)):!h&&l<=t.left+x.width&&(f.x=dv.Backward,g.x=r*Math.abs((t.left+x.width-l)/x.width)),{direction:f,speed:g}}function Yqs(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 H$t(s){return s.reduce((t,n)=>bV(t,IGe(n)),mC)}function Zqs(s){return s.reduce((t,n)=>t+$$t(n),0)}function Xqs(s){return s.reduce((t,n)=>t+U$t(n),0)}function Qqs(s,t){if(t===void 0&&(t=oK),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);B$t(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const Jqs=[["x",["left","right"],Zqs],["y",["top","bottom"],Xqs]];let Gst=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=l6e(n),a=H$t(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of Jqs)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 yee{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 eVs(s){const{EventTarget:t}=$w(s);return s instanceof t?s:iK(s)}function H7e(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 _N;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(_N||(_N={}));function Hvt(s){s.preventDefault()}function tVs(s){s.stopPropagation()}var Xu;(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"})(Xu||(Xu={}));const G$t={start:[Xu.Space,Xu.Enter],cancel:[Xu.Esc],end:[Xu.Space,Xu.Enter,Xu.Tab]},sVs=(s,t)=>{let{currentCoordinates:n}=t;switch(s.code){case Xu.Right:return{...n,x:n.x+25};case Xu.Left:return{...n,x:n.x-25};case Xu.Down:return{...n,y:n.y+25};case Xu.Up:return{...n,y:n.y-25}}};class c6e{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 yee(iK(n)),this.windowListeners=new yee($w(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(_N.Resize,this.handleCancel),this.windowListeners.add(_N.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(_N.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&Qqs(r),n(mC)}handleKeyDown(t){if(Hst(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=G$t,coordinateGetter:l=sVs,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}:mC;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const m=nse(h,u),f={x:0,y:0},{scrollableAncestors:g}=r.current;for(const x of g){const v=t.code,{isTop:y,isRight:b,isLeft:w,isBottom:S,maxScroll:A,minScroll:E}=V$t(x),I=Yqs(x),P={x:Math.min(v===Xu.Right?I.right-I.width/2:I.right,Math.max(v===Xu.Right?I.left:I.left+I.width/2,h.x)),y:Math.min(v===Xu.Down?I.bottom-I.height/2:I.bottom,Math.max(v===Xu.Down?I.top:I.top+I.height/2,h.y))},R=v===Xu.Right&&!b||v===Xu.Left&&!w,D=v===Xu.Down&&!S||v===Xu.Up&&!y;if(R&&P.x!==h.x){const O=x.scrollLeft+m.x,U=v===Xu.Right&&O<=A.x||v===Xu.Left&&O>=E.x;if(U&&!m.y){x.scrollTo({left:O,behavior:o});return}U?f.x=x.scrollLeft-O:f.x=v===Xu.Right?x.scrollLeft-A.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=v===Xu.Down&&O<=A.y||v===Xu.Up&&O>=E.y;if(U&&!m.x){x.scrollTo({top:O,behavior:o});return}U?f.y=x.scrollTop-O:f.y=v===Xu.Down?x.scrollTop-A.y:x.scrollTop-E.y,f.y&&x.scrollBy({top:-f.y,behavior:o});break}}this.handleMove(t,bV(nse(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()}}c6e.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=G$t,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 Gvt(s){return!!(s&&"distance"in s)}function Wvt(s){return!!(s&&"delay"in s)}class Wst{constructor(t,n,r){var a;r===void 0&&(r=eVs(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=iK(l),this.documentListeners=new yee(this.document),this.listeners=new yee(r),this.windowListeners=new yee($w(l)),this.initialCoordinates=(a=PGe(i))!=null?a:mC,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(_N.Resize,this.handleCancel),this.windowListeners.add(_N.DragStart,Hvt),this.windowListeners.add(_N.VisibilityChange,this.handleCancel),this.windowListeners.add(_N.ContextMenu,Hvt),this.documentListeners.add(_N.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Wvt(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Gvt(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(_N.Click,tVs,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(_N.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=PGe(t))!=null?n:mC,d=nse(a,c);if(!r&&o){if(Gvt(o)){if(o.tolerance!=null&&H7e(d,o.tolerance))return this.handleCancel();if(H7e(d,o.distance))return this.handleStart()}if(Wvt(o)&&H7e(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===Xu.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const nVs={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class lK extends Wst{constructor(t){const{event:n}=t,r=iK(n.target);super(t,nVs,r)}}lK.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 rVs={move:{name:"mousemove"},end:{name:"mouseup"}};var LGe;(function(s){s[s.RightClick=2]="RightClick"})(LGe||(LGe={}));class aVs extends Wst{constructor(t){super(t,rVs,iK(t.event.target))}}aVs.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===LGe.RightClick?!1:(r==null||r({event:n}),!0)}}];const G7e={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class iVs extends Wst{constructor(t){super(t,G7e)}static setup(){return window.addEventListener(G7e.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(G7e.move.name,t)};function t(){}}}iVs.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 vee;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(vee||(vee={}));var VEe;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(VEe||(VEe={}));function oVs(s){let{acceleration:t,activator:n=vee.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=VEe.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:m}=s;const f=cVs({delta:h,disabled:!i}),[g,x]=_qs(),v=j.useRef({x:0,y:0}),y=j.useRef({x:0,y:0}),b=j.useMemo(()=>{switch(n){case vee.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case vee.DraggableRect:return a}},[n,a,c]),w=j.useRef(null),S=j.useCallback(()=>{const E=w.current;if(!E)return;const I=v.current.x*y.current.x,P=v.current.y*y.current.y;E.scrollBy(I,P)},[]),A=j.useMemo(()=>o===VEe.TreeOrder?[...d].reverse():d,[o,d]);j.useEffect(()=>{if(!i||!d.length||!b){x();return}for(const E of A){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}=Kqs(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),v.current=D,y.current=R;return}}v.current={x:0,y:0},y.current={x:0,y:0},x()},[t,S,r,x,i,l,JSON.stringify(b),JSON.stringify(f),g,d,A,u,JSON.stringify(m)])}const lVs={x:{[dv.Backward]:!1,[dv.Forward]:!1},y:{[dv.Backward]:!1,[dv.Forward]:!1}};function cVs(s){let{delta:t,disabled:n}=s;const r=MGe(t);return Zae(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:{[dv.Backward]:a.x[dv.Backward]||i.x===-1,[dv.Forward]:a.x[dv.Forward]||i.x===1},y:{[dv.Backward]:a.y[dv.Backward]||i.y===-1,[dv.Forward]:a.y[dv.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 Zae(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function uVs(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 rse;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(rse||(rse={}));var RGe;(function(s){s.Optimized="optimized"})(RGe||(RGe={}));const Kvt=new Map;function hVs(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=v(),m=sse(h),f=j.useCallback(function(y){y===void 0&&(y=[]),!m.current&&l(b=>b===null?y:b.concat(y.filter(w=>!b.includes(w))))},[m]),g=j.useRef(null),x=Zae(y=>{if(h&&!n)return Kvt;if(!y||y===Kvt||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,A=S?new Gst(c(S),S):null;w.rect.current=A,A&&b.set(w.id,A)}return b}return y},[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 v(){switch(d){case rse.Always:return!1;case rse.BeforeDragging:return n;default:return!n}}}function W$t(s,t){return Zae(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function mVs(s,t){return W$t(s,t)}function fVs(s){let{callback:t,disabled:n}=s;const r=Vst(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 d6e(s){let{callback:t,disabled:n}=s;const r=Vst(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 pVs(s){return new Gst(oK(s),s)}function Yvt(s,t,n){t===void 0&&(t=pVs);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=fVs({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=d6e({callback:i});return K4(()=>{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 gVs(s){const t=W$t(s);return z$t(s,t)}const Zvt=[];function xVs(s){const t=j.useRef(s),n=Zae(r=>s?r&&r!==Zvt&&s&&t.current&&s.parentNode===t.current.parentNode?r:l6e(s):Zvt,[s]);return j.useEffect(()=>{t.current=s},[s]),n}function yVs(s){const[t,n]=j.useState(null),r=j.useRef(s),a=j.useCallback(i=>{const l=V7e(i.target);l&&n(o=>o?(o.set(l,IGe(l)),new Map(o)):null)},[]);return j.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=V7e(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,IGe(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=V7e(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),j.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>bV(i,l),mC):H$t(s):mC,[s,t])}function Xvt(s,t){t===void 0&&(t=[]);const n=j.useRef(null);return j.useEffect(()=>{n.current=null},t),j.useEffect(()=>{const r=s!==mC;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?nse(s,n.current):mC}function vVs(s){j.useEffect(()=>{if(!a6e)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 bVs(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 K$t(s){return j.useMemo(()=>s?Vqs(s):null,[s])}const Qvt=[];function _Vs(s,t){t===void 0&&(t=oK);const[n]=s,r=K$t(n?$w(n):null),[a,i]=j.useState(Qvt);function l(){i(()=>s.length?s.map(c=>q$t(c)?r:new Gst(t(c),c)):Qvt)}const o=d6e({callback:l});return K4(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function wVs(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return Yae(t)?t:s}function jVs(s){let{measure:t}=s;const[n,r]=j.useState(null),a=j.useCallback(d=>{for(const{target:u}of d)if(Yae(u)){r(h=>{const m=t(u);return h?{...h,width:m.width,height:m.height}:m});break}},[t]),i=d6e({callback:a}),l=j.useCallback(d=>{const u=wVs(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=UEe(l);return j.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const NVs=[{sensor:lK,options:{}},{sensor:c6e,options:{}}],kVs={current:{}},i3e={draggable:{measure:Vvt},droppable:{measure:Vvt,strategy:rse.WhileDragging,frequency:RGe.Optimized},dragOverlay:{measure:oK}};class bee 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 SVs={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new bee,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:qEe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:i3e,measureDroppableContainers:qEe,windowRect:null,measuringScheduled:!1},CVs={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:qEe,draggableNodes:new Map,over:null,measureDroppableContainers:qEe},u6e=j.createContext(CVs),Y$t=j.createContext(SVs);function AVs(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new bee}}}function EVs(s,t){switch(t.type){case p0.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case p0.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 p0.DragEnd:case p0.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case p0.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new bee(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case p0.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 bee(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case p0.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new bee(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function TVs(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=j.useContext(u6e),i=MGe(r),l=MGe(n==null?void 0:n.id);return j.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!Hst(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=Nqs(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function MVs(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function PVs(s){return j.useMemo(()=>({draggable:{...i3e.draggable,...s==null?void 0:s.draggable},droppable:{...i3e.droppable,...s==null?void 0:s.droppable},dragOverlay:{...i3e.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 IVs(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;K4(()=>{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=z$t(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=B$t(d);m&&m.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const Z$t=j.createContext({...mC,scaleX:1,scaleY:1});var lP;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(lP||(lP={}));const h6e=j.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=NVs,collisionDetection:h=Fqs,measuring:m,modifiers:f,...g}=t;const x=j.useReducer(EVs,void 0,AVs),[v,y]=x,[b,w]=Tqs(),[S,A]=j.useState(lP.Uninitialized),E=S===lP.Initialized,{draggable:{active:I,nodes:P,translate:R},droppable:{containers:D}}=v,O=I!=null?P.get(I):null,U=j.useRef({initial:null,translated:null}),W=j.useMemo(()=>{var zt;return I!=null?{id:I,data:(zt=O==null?void 0:O.data)!=null?zt:kVs,rect:U}:null},[I,O]),V=j.useRef(null),[G,Z]=j.useState(null),[X,ae]=j.useState(null),le=sse(g,Object.values(g)),re=Xae("DndDescribedBy",l),te=j.useMemo(()=>D.getEnabled(),[D]),J=PVs(m),{droppableRects:ce,measureDroppableContainers:ve,measuringScheduled:fe}=hVs(te,{dragging:E,dependencies:[R.x,R.y],config:J.droppable}),ue=dVs(P,I),be=j.useMemo(()=>X?PGe(X):null,[X]),Ee=Bt(),ke=mVs(ue,J.draggable.measure);IVs({activeNode:I!=null?P.get(I):null,config:Ee.layoutShiftCompensation,initialRect:ke,measure:J.draggable.measure});const Ie=Yvt(ue,J.draggable.measure,ke),Fe=Yvt(ue?ue.parentElement:null),Ne=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}),Be=D.getNodeFor((n=Ne.current.over)==null?void 0:n.id),Se=jVs({measure:J.dragOverlay.measure}),Ae=(r=Se.nodeRef.current)!=null?r:ue,Ce=E?(a=Se.rect)!=null?a:Ie:null,qe=!!(Se.nodeRef.current&&Se.rect),ze=gVs(qe?null:Ie),Ve=K$t(Ae?$w(Ae):null),ht=xVs(E?Be??ue:null),Qe=_Vs(ht),at=MVs(f,{transform:{x:R.x-ze.x,y:R.y-ze.y,scaleX:1,scaleY:1},activatorEvent:X,active:W,activeNodeRect:Ie,containerNodeRect:Fe,draggingNodeRect:Ce,over:Ne.current.over,overlayNodeRect:Se.rect,scrollableAncestors:ht,scrollableAncestorRects:Qe,windowRect:Ve}),rt=be?bV(be,R):null,Ke=yVs(ht),Je=Xvt(Ke),ft=Xvt(Ke,[Ie]),gt=bV(at,Je),es=Ce?Bqs(Ce,at):null,Ht=W&&es?h({active:W,collisionRect:es,droppableRects:ce,droppableContainers:te,pointerCoordinates:rt}):null,as=O$t(Ht,"id"),[bs,Ut]=j.useState(null),Ft=qe?at:bV(at,ft),is=Oqs(Ft,(i=bs==null?void 0:bs.rect)!=null?i:null,Ie),jt=j.useRef(null),zs=j.useCallback((zt,vs)=>{let{sensor:dn,options:Ks}=vs;if(V.current==null)return;const Cn=P.get(V.current);if(!Cn)return;const Rr=zt.nativeEvent,ia=new dn({active:V.current,activeNode:Cn,event:Rr,options:Ks,context:Ne,onAbort(Br){if(!P.get(Br))return;const{onDragAbort:Wn}=le.current,Sn={id:Br};Wn==null||Wn(Sn),b({type:"onDragAbort",event:Sn})},onPending(Br,Ur,Wn,Sn){if(!P.get(Br))return;const{onDragPending:bn}=le.current,xs={id:Br,constraint:Ur,initialCoordinates:Wn,offset:Sn};bn==null||bn(xs),b({type:"onDragPending",event:xs})},onStart(Br){const Ur=V.current;if(Ur==null)return;const Wn=P.get(Ur);if(!Wn)return;const{onDragStart:Sn}=le.current,Fn={activatorEvent:Rr,active:{id:Ur,data:Wn.data,rect:U}};yv.unstable_batchedUpdates(()=>{Sn==null||Sn(Fn),A(lP.Initializing),y({type:p0.DragStart,initialCoordinates:Br,active:Ur}),b({type:"onDragStart",event:Fn}),Z(jt.current),ae(Rr)})},onMove(Br){y({type:p0.DragMove,coordinates:Br})},onEnd:Hs(p0.DragEnd),onCancel:Hs(p0.DragCancel)});jt.current=ia;function Hs(Br){return async function(){const{active:Wn,collisions:Sn,over:Fn,scrollAdjustedTranslate:bn}=Ne.current;let xs=null;if(Wn&&bn){const{cancelDrop:Tr}=le.current;xs={activatorEvent:Rr,active:Wn,collisions:Sn,delta:bn,over:Fn},Br===p0.DragEnd&&typeof Tr=="function"&&await Promise.resolve(Tr(xs))&&(Br=p0.DragCancel)}V.current=null,yv.unstable_batchedUpdates(()=>{y({type:Br}),A(lP.Uninitialized),Ut(null),Z(null),ae(null),jt.current=null;const Tr=Br===p0.DragEnd?"onDragEnd":"onDragCancel";if(xs){const Lr=le.current[Tr];Lr==null||Lr(xs),b({type:Tr,event:xs})}})}}},[P]),yt=j.useCallback((zt,vs)=>(dn,Ks)=>{const Cn=dn.nativeEvent,Rr=P.get(Ks);if(V.current!==null||!Rr||Cn.dndKit||Cn.defaultPrevented)return;const ia={active:Rr};zt(dn,vs.options,ia)===!0&&(Cn.dndKit={capturedBy:vs.sensor},V.current=Ks,zs(dn,vs))},[P,zs]),gs=uVs(u,yt);vVs(u),K4(()=>{Ie&&S===lP.Initializing&&A(lP.Initialized)},[Ie,S]),j.useEffect(()=>{const{onDragMove:zt}=le.current,{active:vs,activatorEvent:dn,collisions:Ks,over:Cn}=Ne.current;if(!vs||!dn)return;const Rr={active:vs,activatorEvent:dn,collisions:Ks,delta:{x:gt.x,y:gt.y},over:Cn};yv.unstable_batchedUpdates(()=>{zt==null||zt(Rr),b({type:"onDragMove",event:Rr})})},[gt.x,gt.y]),j.useEffect(()=>{const{active:zt,activatorEvent:vs,collisions:dn,droppableContainers:Ks,scrollAdjustedTranslate:Cn}=Ne.current;if(!zt||V.current==null||!vs||!Cn)return;const{onDragOver:Rr}=le.current,ia=Ks.get(as),Hs=ia&&ia.rect.current?{id:ia.id,rect:ia.rect.current,data:ia.data,disabled:ia.disabled}:null,Br={active:zt,activatorEvent:vs,collisions:dn,delta:{x:Cn.x,y:Cn.y},over:Hs};yv.unstable_batchedUpdates(()=>{Ut(Hs),Rr==null||Rr(Br),b({type:"onDragOver",event:Br})})},[as]),K4(()=>{Ne.current={activatorEvent:X,active:W,activeNode:ue,collisionRect:es,collisions:Ht,droppableRects:ce,draggableNodes:P,draggingNode:Ae,draggingNodeRect:Ce,droppableContainers:D,over:bs,scrollableAncestors:ht,scrollAdjustedTranslate:gt},U.current={initial:Ce,translated:es}},[W,ue,Ht,es,P,Ae,Ce,ce,D,bs,ht,gt]),oVs({...Ee,delta:R,draggingRect:es,pointerCoordinates:rt,scrollableAncestors:ht,scrollableAncestorRects:Qe});const Ss=j.useMemo(()=>({active:W,activeNode:ue,activeNodeRect:Ie,activatorEvent:X,collisions:Ht,containerNodeRect:Fe,dragOverlay:Se,draggableNodes:P,droppableContainers:D,droppableRects:ce,over:bs,measureDroppableContainers:ve,scrollableAncestors:ht,scrollableAncestorRects:Qe,measuringConfiguration:J,measuringScheduled:fe,windowRect:Ve}),[W,ue,Ie,X,Ht,Fe,Se,P,D,ce,bs,ve,ht,Qe,J,fe,Ve]),Ds=j.useMemo(()=>({activatorEvent:X,activators:gs,active:W,activeNodeRect:Ie,ariaDescribedById:{draggable:re},dispatch:y,draggableNodes:P,over:bs,measureDroppableContainers:ve}),[X,gs,W,Ie,y,re,P,bs,ve]);return Kt.createElement(R$t.Provider,{value:w},Kt.createElement(u6e.Provider,{value:Ds},Kt.createElement(Y$t.Provider,{value:Ss},Kt.createElement(Z$t.Provider,{value:is},d)),Kt.createElement(TVs,{disabled:(o==null?void 0:o.restoreFocus)===!1})),Kt.createElement(Iqs,{...o,hiddenTextDescribedById:re}));function Bt(){const zt=(G==null?void 0:G.autoScrollEnabled)===!1,vs=typeof c=="object"?c.enabled===!1:c===!1,dn=E&&!zt&&!vs;return typeof c=="object"?{...c,enabled:dn}:{enabled:dn}}}),LVs=j.createContext(null),Jvt="button",RVs="Draggable";function DVs(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=Xae(RVs),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:m}=j.useContext(u6e),{role:f=Jvt,roleDescription:g="draggable",tabIndex:x=0}=a??{},v=(c==null?void 0:c.id)===t,y=j.useContext(v?Z$t:LVs),[b,w]=UEe(),[S,A]=UEe(),E=bVs(l,t),I=sse(n);K4(()=>(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":v&&f===Jvt?!0:void 0,"aria-roledescription":g,"aria-describedby":u.draggable}),[r,f,x,v,g,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:P,isDragging:v,listeners:r?void 0:E,node:b,over:m,setNodeRef:w,setActivatorNodeRef:A,transform:y}}function FVs(){return j.useContext(Y$t)}const OVs="Droppable",zVs={timeout:25};function BVs(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=Xae(OVs),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=j.useContext(u6e),u=j.useRef({disabled:n}),h=j.useRef(!1),m=j.useRef(null),f=j.useRef(null),{disabled:g,updateMeasurementsFor:x,timeout:v}={...zVs,...a},y=sse(x??r),b=j.useCallback(()=>{if(!h.current){h.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(y.current)?y.current:[y.current]),f.current=null},v)},[v]),w=d6e({callback:b,disabled:g||!l}),S=j.useCallback((P,R)=>{w&&(R&&(w.unobserve(R),h.current=!1),P&&w.observe(P))},[w]),[A,E]=UEe(S),I=sse(t);return j.useEffect(()=>{!w||!A.current||(w.disconnect(),h.current=!1,w.observe(A.current))},[A,w]),j.useEffect(()=>(o({type:p0.RegisterDroppable,element:{id:r,key:i,disabled:n,node:A,rect:m,data:I}}),()=>o({type:p0.UnregisterDroppable,key:i,id:r})),[r]),j.useEffect(()=>{n!==u.current.disabled&&(o({type:p0.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:A,over:c,setNodeRef:E}}function m6e(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function $Vs(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function Zce(s){return s!==null&&s>=0}function UVs(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=VVs(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...Xce}:l=i?{x:o.width+c,y:0,...Xce}:{x:0,y:0,...Xce}};function VVs(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=m6e(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}},Qce={scaleX:1,scaleY:1},HVs=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,...Qce}:a=l?{x:0,y:o.height+c,...Qce}:{x:0,y:0,...Qce}};function GVs(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,v=d?f.indexOf(d.id):-1,y=j.useRef(f),b=!UVs(f,y.current),w=v!==-1&&x===-1||b,S=qVs(i);K4(()=>{b&&g&&u(f)},[b,f,g,u]),j.useEffect(()=>{y.current=f},[f]);const A=j.useMemo(()=>({activeIndex:x,containerId:h,disabled:S,disableTransforms:w,items:f,overIndex:v,useDragOverlay:m,sortedRects:$Vs(f,c),strategy:a}),[x,h,S.draggable,S.droppable,w,f,v,c,m,a]);return Kt.createElement(Q$t.Provider,{value:A},t)}const WVs=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return m6e(n,r,a).indexOf(t)},KVs=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},YVs={duration:200,easing:"ease"},J$t="transform",ZVs=TL.Transition.toString({property:J$t,duration:0,easing:"linear"}),XVs={roleDescription:"sortable"};function QVs(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=j.useState(null),o=j.useRef(n);return K4(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=oK(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 p6e(s){let{animateLayoutChanges:t=KVs,attributes:n,disabled:r,data:a,getNewIndex:i=WVs,id:l,strategy:o,resizeObserverConfig:c,transition:d=YVs}=s;const{items:u,containerId:h,activeIndex:m,disabled:f,disableTransforms:g,sortedRects:x,overIndex:v,useDragOverlay:y,strategy:b}=j.useContext(Q$t),w=JVs(r,f),S=u.indexOf(l),A=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}=BVs({id:l,data:A,disabled:w.droppable,resizeObserverConfig:{updateMeasurementsFor:E,...c}}),{active:O,activatorEvent:U,activeNodeRect:W,attributes:V,setNodeRef:G,listeners:Z,isDragging:X,over:ae,setActivatorNodeRef:le,transform:re}=DVs({id:l,data:A,attributes:{...XVs,...n},disabled:w.draggable}),te=bqs(D,G),J=!!O,ce=J&&!g&&Zce(m)&&Zce(v),ve=!y&&X,fe=ve&&ce?re:null,be=ce?fe??(o??b)({rects:x,activeNodeRect:W,activeIndex:m,overIndex:v,index:S}):null,Ee=Zce(m)&&Zce(v)?i({id:l,items:u,activeIndex:m,overIndex:v}):S,ke=O==null?void 0:O.id,Ie=j.useRef({activeId:ke,items:u,newIndex:Ee,containerId:h}),Fe=u!==Ie.current.items,Ne=t({active:O,containerId:h,isDragging:X,isSorting:J,id:l,index:S,items:u,newIndex:Ie.current.newIndex,previousItems:Ie.current.items,previousContainerId:Ie.current.containerId,transition:d,wasDragging:Ie.current.activeId!=null}),Be=QVs({disabled:!Ne,index:S,node:P,rect:I});return j.useEffect(()=>{J&&Ie.current.newIndex!==Ee&&(Ie.current.newIndex=Ee),h!==Ie.current.containerId&&(Ie.current.containerId=h),u!==Ie.current.items&&(Ie.current.items=u)},[J,Ee,h,u]),j.useEffect(()=>{if(ke===Ie.current.activeId)return;if(ke!=null&&Ie.current.activeId==null){Ie.current.activeId=ke;return}const Ae=setTimeout(()=>{Ie.current.activeId=ke},50);return()=>clearTimeout(Ae)},[ke]),{active:O,activeIndex:m,attributes:V,data:A,rect:I,index:S,newIndex:Ee,items:u,isOver:R,isSorting:J,isDragging:X,listeners:Z,node:P,overIndex:v,over:ae,setNodeRef:te,setActivatorNodeRef:le,setDroppableNodeRef:D,setDraggableNodeRef:G,transform:Be??be,transition:Se()};function Se(){if(Be||Fe&&Ie.current.newIndex===S)return ZVs;if(!(ve&&!Hst(U)||!d)&&(J||Ne))return TL.Transition.toString({...d,property:J$t})}}function JVs(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 HEe(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 eHs=[Xu.Down,Xu.Right,Xu.Up,Xu.Left],eUt=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(eHs.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 Xu.Down:r.topm.top&&c.push(h);break;case Xu.Left:r.left>m.left&&c.push(h);break;case Xu.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 v=l6e(g).some((E,I)=>o[I]!==E),y=tUt(h,m),b=tHs(h,m),w=v||!y?{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:nse(S,w)}}}};function tUt(s,t){return!HEe(s)||!HEe(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function tHs(s,t){return!HEe(s)||!HEe(t)||!tUt(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(mr,{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(ei,{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 sUt({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){var h,m;const l=i6e(CG(lK,{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 v=o.findIndex(I=>I.id===g.id),y=o.findIndex(I=>I.id===x.id),b=[...o],[w]=b.splice(v,1);b.splice(y,0,w);const S=c??((E=b[0])==null?void 0:E.id),A=b.map((I,P)=>({...I,sort_order:P,is_primary:I.id===S}));a(A)};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(h6e,{sensors:l,collisionDetection:o6e,onDragEnd:u,children:e.jsx(f6e,{items:o.map(f=>f.id),strategy:Qae,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(f=>e.jsx(sHs,{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(Ct,{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 g6e({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a,isCommercial:i=!1}){const{user:l}=_s(),[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:y,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(y&&y.share_token)c(y);else if(y&&!y.share_token){const{data:w,error:S}=await q.from("listing_shares").update({share_type:"referral_link"}).eq("id",y.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(y){console.error("Error creating share link:",y),ne.error("Failed to generate share link")}finally{u(!1)}}})()},[s,l,n]);const f=o!=null&&o.share_token?`${i?sDs:"https://listings.relevelup.com"}/${r||n}?ref=${o.share_token}`:"",g=async()=>{try{await navigator.clipboard.writeText(f),m(!0),ne.success("Link copied to clipboard!"),setTimeout(()=>m(!1),2e3)}catch{ne.error("Failed to copy link")}},x=v=>{const y=encodeURIComponent(f),b=encodeURIComponent(`Check out this listing: ${a}`);switch(v){case"email":window.open(`mailto:?subject=${b}&body=${y}`);break;case"text":window.open(`sms:?body=${b}%20${y}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${y}`,"_blank");break}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(Er,{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(ma,{className:"h-4 w-4"}):e.jsx(Za,{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(pn,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>x("text"),disabled:d,children:[e.jsx(no,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>x("facebook"),disabled:d,children:[e.jsx(Zp,{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(Ta,{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(Yn,{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 nHs=Object.defineProperty,GEe=Object.getOwnPropertySymbols,nUt=Object.prototype.hasOwnProperty,rUt=Object.prototype.propertyIsEnumerable,ebt=(s,t,n)=>t in s?nHs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,DGe=(s,t)=>{for(var n in t||(t={}))nUt.call(t,n)&&ebt(s,n,t[n]);if(GEe)for(var n of GEe(t))rUt.call(t,n)&&ebt(s,n,t[n]);return s},FGe=(s,t)=>{var n={};for(var r in s)nUt.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&GEe)for(var r of GEe(s))t.indexOf(r)<0&&rUt.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var U7;(s=>{const t=class bu{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cbu.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=bu.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[bu.Ecc.MEDIUM,bu.Ecc.QUARTILE,bu.Ecc.HIGH])f&&x<=bu.getNumDataCodewords(g,w)*8&&(d=w);let v=[];for(const w of c){n(w.mode.modeBits,4,v),n(w.numChars,w.mode.numCharCountBits(g),v);for(const S of w.getData())v.push(S)}a(v.length==x);const y=bu.getNumDataCodewords(g,d)*8;a(v.length<=y),n(0,Math.min(4,y-v.length),v),n(0,(8-v.length%8)%8,v),a(v.length%8==0);for(let w=236;v.lengthb[S>>>3]|=w<<7-(S&7)),new bu(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||A>=g)&&b.push(S[w])});return a(b.length==f),b}drawCodewords(c){if(c.length!=Math.floor(bu.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)*bu.PENALTY_N3),f=this.modules[m][v],g=1);c+=this.finderPenaltyTerminateAndCount(f,g,x)*bu.PENALTY_N3}for(let m=0;m5&&c++):(this.finderPenaltyAddHistory(g,x),f||(c+=this.finderPenaltyCountPatterns(x)*bu.PENALTY_N3),f=this.modules[v][m],g=1);c+=this.finderPenaltyTerminateAndCount(f,g,x)*bu.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*bu.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.lengthbu.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(bu.getNumRawDataModules(c)/8)-bu.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*bu.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]^=bu.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 ix{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 ix(ix.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!ix.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={}))})(U7||(U7={}));(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={}))})(U7||(U7={}));var KU=U7;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var rHs={L:KU.QrCode.Ecc.LOW,M:KU.QrCode.Ecc.MEDIUM,Q:KU.QrCode.Ecc.QUARTILE,H:KU.QrCode.Ecc.HIGH},aUt=128,iUt="L",oUt="#FFFFFF",lUt="#000000",cUt=!1,dUt=1,aHs=4,iHs=0,oHs=.1;function uUt(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 hUt(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*oHs),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),v=Math.ceil(o+d-g),y=Math.ceil(c+u-x);m={x:g,y:x,w:v,h:y}}const f=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:m,opacity:h,crossOrigin:f}}function cHs(s,t){return t!=null?Math.max(Math.floor(t),0):s?aHs:iHs}function mUt({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=Kt.useMemo(()=>{const g=(Array.isArray(s)?s:[s]).reduce((x,v)=>(x.push(...KU.QrSegment.makeSegments(v)),x),[]);return KU.QrCode.encodeSegments(g,rHs[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:m}=Kt.useMemo(()=>{let f=c.getModules();const g=cHs(r,a),x=f.length+g*2,v=lHs(f,l,g,i);return{cells:f,margin:g,numCells:x,calculatedImageSettings:v}},[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}(),fUt=Kt.forwardRef(function(t,n){const r=t,{value:a,size:i=aUt,level:l=iUt,bgColor:o=oUt,fgColor:c=lUt,includeMargin:d=cUt,minVersion:u=dUt,boostLevel:h,marginSize:m,imageSettings:f}=r,x=FGe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:v}=x,y=FGe(x,["style"]),b=f==null?void 0:f.src,w=Kt.useRef(null),S=Kt.useRef(null),A=Kt.useCallback(V=>{w.current=V,typeof n=="function"?n(V):n&&(n.current=V)},[n]),[E,I]=Kt.useState(!1),{margin:P,cells:R,numCells:D,calculatedImageSettings:O}=mUt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:m,imageSettings:f,size:i});Kt.useEffect(()=>{if(w.current!=null){const V=w.current,G=V.getContext("2d");if(!G)return;let Z=R;const X=S.current,ae=O!=null&&X!==null&&X.complete&&X.naturalHeight!==0&&X.naturalWidth!==0;ae&&O.excavation!=null&&(Z=hUt(R,O.excavation));const le=window.devicePixelRatio||1;V.height=V.width=i*le;const re=i/D*le;G.scale(re,re),G.fillStyle=o,G.fillRect(0,0,D,D),G.fillStyle=c,dHs?G.fill(new Path2D(uUt(Z,P))):R.forEach(function(te,J){te.forEach(function(ce,ve){ce&&G.fillRect(ve+P,J+P,1,1)})}),O&&(G.globalAlpha=O.opacity),ae&&G.drawImage(X,O.x+P,O.y+P,O.w,O.h)}}),Kt.useEffect(()=>{I(!1)},[b]);const U=DGe({height:i,width:i},v);let W=null;return b!=null&&(W=Kt.createElement("img",{src:b,key:b,style:{display:"none"},onLoad:()=>{I(!0)},ref:S,crossOrigin:O==null?void 0:O.crossOrigin})),Kt.createElement(Kt.Fragment,null,Kt.createElement("canvas",DGe({style:U,height:i,width:i,ref:A,role:"img"},y)),W)});fUt.displayName="QRCodeCanvas";var dk=Kt.forwardRef(function(t,n){const r=t,{value:a,size:i=aUt,level:l=iUt,bgColor:o=oUt,fgColor:c=lUt,includeMargin:d=cUt,minVersion:u=dUt,boostLevel:h,title:m,marginSize:f,imageSettings:g}=r,x=FGe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:v,cells:y,numCells:b,calculatedImageSettings:w}=mUt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:f,imageSettings:g,size:i});let S=y,A=null;g!=null&&w!=null&&(w.excavation!=null&&(S=hUt(y,w.excavation)),A=Kt.createElement("image",{href:g.src,height:w.h,width:w.w,x:w.x+v,y:w.y+v,preserveAspectRatio:"none",opacity:w.opacity,crossOrigin:w.crossOrigin}));const E=uUt(S,v);return Kt.createElement("svg",DGe({height:i,width:i,viewBox:`0 0 ${b} ${b}`,ref:n,role:"img"},x),!!m&&Kt.createElement("title",null,m),Kt.createElement("path",{fill:o,d:`M0,0 h${b}v${b}H0z`,shapeRendering:"crispEdges"}),Kt.createElement("path",{fill:c,d:E,shapeRendering:"crispEdges"}),A)});dk.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 v=document.createElement("canvas");v.width=h,v.height=h;const y=v.getContext("2d");y&&(y.fillStyle="#ffffff",y.fillRect(0,0,h,h),y.drawImage(f,0,0,h,h),URL.revokeObjectURL(x),v.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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Listing QR Code"}),e.jsx(Er,{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(dk,{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(ji,{className:"h-4 w-4"}),"PNG"]}),e.jsxs($,{variant:"outline",onClick:d,className:"gap-2",children:[e.jsx(ji,{className:"h-4 w-4"}),"SVG"]}),e.jsxs($,{variant:"outline",onClick:async()=>{await navigator.clipboard.writeText(n),ne.success("Link copied")},className:"gap-2",children:[e.jsx(Za,{className:"h-4 w-4"}),"Copy link"]})]})]})})}var uHs=Object.defineProperty,gUt=(s,t)=>uHs(s,"name",{value:t,configurable:!0}),tbt="horizontal",hHs=["horizontal","vertical"],mHs=j.forwardRef(gUt(function(t,n){const{decorative:r,orientation:a=tbt,...i}=t,l=xUt(a)?a:tbt,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 xUt(s){return hHs.includes(s)}gUt(xUt,"isValidOrientation");var yUt=mHs;const Vc=j.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(yUt,{ref:a,decorative:n,orientation:t,className:Pt("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));Vc.displayName=yUt.displayName;const Uw=()=>st({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}}),vUt=()=>{const s=Sa(),t=1e3;return st({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 v=0;v{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})},fHs=s=>st({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}),bUt=()=>{const s=Sa();return st({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})},x6e=()=>{const s=Zt(),t=Sa();return mt({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"})}})},Kst=()=>{const s=Zt();return mt({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"})}})},_Ut=()=>{const s=Zt();return mt({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"})}})},wUt=()=>{const s=Zt();return mt({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"})}})},pHs=()=>{const s=Zt();return mt({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"]})}})},Jae=()=>st({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}}),gHs=s=>st({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}}),xHs=()=>st({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}}),yHs=()=>{const s=Zt(),t=Sa();return mt({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"})}})},vHs=()=>{const s=Zt(),t=Sa();return mt({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"})}})},bHs=()=>{const s=Zt();return mt({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"})}})},_Hs=()=>{const s=Zt();return mt({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"})}})},wHs=()=>{const s=Zt();return mt({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"})}})},jHs=()=>{const s=Zt();return mt({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"})}})},NHs=()=>{const s=Sa();return st({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})},kHs=()=>{const s=Zt(),t=Sa();return mt({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"})}})},cK=(s=7)=>{const t=Sa();return st({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})},jUt=()=>{const s=Sa();return st({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})},SHs=(s=90)=>{const{data:t}=L_(),{data:n}=jUt();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=Zt(),t=Sa();return mt({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{}}})},NUt="agentos_weekly_touch_goal",sbt=20,kUt=()=>{if(typeof window>"u")return sbt;const s=localStorage.getItem(NUt);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return sbt},CHs=s=>{localStorage.setItem(NUt,s.toString())},v6e=()=>{const{data:s}=cK(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=kUt();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},AHs=()=>{const s=Sa();return st({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})},EHs=()=>{const s=Zt();return Sa(),mt({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`})}})},Yst=()=>{const s=Sa(),{data:t}=AHs(),{data:n}=cK(30);return st({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 v=new Date(x.cycle_start_date),b=Math.floor((i.getTime()-v.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:A}=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:(A==null?void 0:A.name)||"",monthNumber:b})}}}const d=5,u=i.getDate(),h=l.sort((x,v)=>x.contact.first_name.localeCompare(v.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 THs(){const{user:s}=_s(),{limitFor:t,isRestricted:n}=bC(),r=n?t("mass_email"):null,{data:a=0,refetch:i}=st({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 MHs({onSelect:s}){const{user:t}=_s(),[n,r]=j.useState("root"),[a,i]=j.useState(null),{data:l=[],isLoading:o}=st({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:y,error:b}=await q.from("email_template_categories").select("*").order("sort_order");if(b)throw b;return y}}),{data:c=[],isLoading:d}=st({queryKey:["agent-email-templates",a],enabled:n==="category"&&!!a,queryFn:async()=>{const{data:y,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 y}}),{data:u=[],isLoading:h}=st({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:y,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 y}}),m=u.filter(y=>y.user_id===(t==null?void 0:t.id)&&!y.is_shared),f=u.filter(y=>y.is_shared),g=l.find(y=>y.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const x=y=>{s({title:y.name,subject:y.subject,body:y.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(cl,{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(y=>e.jsxs("button",{onClick:()=>{i(y.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:y.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:y.name}),y.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:y.description})]})]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},y.id))})]})]});const v=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(kd,{className:"h-3.5 w-3.5"}),"Back"]});return n==="my"?e.jsxs("div",{className:"space-y-2",children:[v,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(Ct,{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(wn,{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(go,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:m.map(y=>e.jsxs("button",{onClick:()=>x(y),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:y.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:y.subject||"(no subject)"})]},y.id))})})]}):n==="shared"?e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(cl,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Ct,{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(go,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:f.map(y=>e.jsxs("button",{onClick:()=>x(y),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:y.name}),e.jsx($e,{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:y.subject||"(no subject)"})]},y.id))})})]}):e.jsxs("div",{className:"space-y-2",children:[v,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(Ct,{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(go,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:c.map(y=>e.jsxs("button",{onClick:()=>s(y),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:y.title}),y.tone&&e.jsx($e,{variant:"secondary",className:"text-[10px] shrink-0",children:y.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:y.subject})]},y.id))})})]})}function FB(){var a;const{user:s}=_s(),{data:t,isLoading:n}=st({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 eie(){const{user:s}=_s();return st({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 b6e({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=Zn();return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{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(vl,{className:"h-5 w-5"})}),e.jsx($s,{children:"Verify your sending email first"})]}),e.jsx(Er,{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(ca,{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(pn,{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(Nr,{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(Ir,{className:"h-4 w-4 mr-1"}),n?"Manage senders":"Verify my email"]})]})]})})}function _6e(){const{user:s}=_s(),t=Zt(),{data:n,isLoading:r}=st({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=mt({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"]}),ne.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?ne.error("That slug is already taken. Try another."):ne.error("Failed to create page")}}),i=mt({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"]}),ne.success("Page updated!")},onError:()=>ne.error("Failed to update page")}),{data:l=[],isLoading:o}=st({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=mt({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 SUt({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=v=>{m.current&&!m.current.contains(v.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 v=`%${x}%`,y=q,{data:b,error:w}=await y.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",n).not("email","is",null).or(`first_name.ilike.${v},last_name.ilike.${v},email.ilike.${v}`).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(v=>Math.min(v+1,l.length-1))):x.key==="ArrowUp"?(x.preventDefault(),h(v=>Math.max(v-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(Ct,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((x,v)=>{const y=[x.first_name,x.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>h(v),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 ${v===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:y}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:x.email})]})]},x.id)})})]})}function PHs(){const{user:s}=_s(),{data:t,isLoading:n}=st({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 IHs(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 LHs(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 W7e=25*1024*1024,nbt=Math.floor(6.5*1024*1024),RHs=750*1024,Q2=50,DHs=["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 Jce(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function FHs(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 OHs(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function uj(s,t){const n=OHs(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 Nk({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=_s(),h=Zt(),{isReady:m,settings:f}=FB(),{data:g}=eie(),[x,v]=j.useState(!1),{intakePage:y}=_6e(),b=y?`https://contacts.relevelup.com/${y.slug}`:null,w=!!r&&r.length>0,S=THs(),A=m,E=w?r:n?[n]:[],I=E[0],P=w?Math.ceil(E.length/Q2):1,R=w&&E.length>Q2,[D,O]=j.useState((I==null?void 0:I.email)||""),[U,W]=j.useState(a),[V,G]=j.useState(i),[Z,X]=j.useState(!1),[ae,le]=j.useState(!1),[re,te]=j.useState([]),J=j.useRef(new Map),[ce,ve]=j.useState(a),[fe,ue]=j.useState(i),[be,Ee]=j.useState(!1),[ke,Ie]=j.useState("composing"),[Fe,Ne]=j.useState(0),[Be,Se]=j.useState(0),[Ae,Ce]=j.useState(0),[qe,ze]=j.useState(0),Ve=j.useRef(!1),ht=j.useRef(0),[Qe,at]=j.useState(!0),{signatureHtml:rt,hasSignature:Ke}=PHs(),[Je,ft]=j.useState(!0),[gt,es]=j.useState(null),Ht=Xn=>{let wr=5381;for(let Bn=0;Bn>>0;return wr.toString(36)},as=w?`bulk-${E.length}-${Ht(E.map(Xn=>Xn.id||Xn.email||"").join("|"))}`:(I==null?void 0:I.id)||"adhoc",bs=Ht(`${a||""}::${(i||"").slice(0,400)}`),Ut=`levelup:email-draft:${as}:${bs}`,[Ft,is]=j.useState(!1),jt=j.useRef(!1),zs=()=>{try{localStorage.removeItem(Ut)}catch{}is(!1)};j.useEffect(()=>{s&&ft(Ke)},[s,Ke]),j.useEffect(()=>{if(s){const Xn=/<[a-z][\s\S]*>/i.test(i),wr=Xn?LHs(i):i;Bt.current=Xn?{plain:wr,html:i}:null,O((I==null?void 0:I.email)||""),ve(a),ue(wr),W(uj(a,I||{first_name:""})),G(uj(wr,I||{first_name:""})),le(!a&&!i),Ee(!1),Ks(Bn=>Bn+1),te([]),J.current=new Map,Ie("composing"),Ne(0),Se(0),Ce(0),ze(0),Ve.current=!1,ht.current=0,es(null);try{const Bn=localStorage.getItem(Ut);if(Bn){const cr=JSON.parse(Bn),Pa=(cr==null?void 0:cr.savedAt)&&Date.now()-cr.savedAt<14*24*60*60*1e3,ii=(cr==null?void 0:cr.rawSubject)||(cr==null?void 0:cr.rawBody)||(cr==null?void 0:cr.html);Pa&&ii&&(cr.to&&O(cr.to),ve(cr.rawSubject||""),ue(cr.rawBody||""),W(uj(cr.rawSubject||"",I||{first_name:""})),G(uj(cr.rawBody||"",I||{first_name:""})),cr.html&&(Bt.current={plain:cr.rawBody||"",html:cr.html}),le(!1),Ks($i=>$i+1),is(!0))}}catch{}jt.current=!0}else jt.current=!1},[s,I,a,i]),j.useEffect(()=>{if(!s||!jt.current||ke!=="composing")return;const Xn=Bt.current,wr={to:D,rawSubject:ce,rawBody:fe,html:Xn&&fe===Xn.plain?Xn.html:null,savedAt:Date.now()},Bn=()=>{try{if(!ce&&!fe)return;localStorage.setItem(Ut,JSON.stringify({...wr,savedAt:Date.now(),html:Bt.current&&fe===Bt.current.plain?Bt.current.html:null}))}catch{}},cr=setTimeout(Bn,600);return window.addEventListener("blur",Bn),document.addEventListener("visibilitychange",Bn),()=>{clearTimeout(cr),window.removeEventListener("blur",Bn),document.removeEventListener("visibilitychange",Bn)}},[s,D,ce,fe,ke,Ut]);const yt=async Xn=>{const wr=Xn.target.files;if(!wr)return;const Bn=re.reduce((ii,$i)=>ii+$i.size,0),cr=[];let Pa=Bn;for(const ii of Array.from(wr)){if(!DHs.includes(ii.type)){ne.error(`${ii.name}: Unsupported file type`);continue}if(Pa+ii.size>W7e){ne.error(`Total attachments exceed ${Jce(W7e)} limit`);break}try{const $i=await FHs(ii);cr.push({name:ii.name,type:ii.type,size:ii.size,data:$i}),Pa+=ii.size}catch{ne.error(`Failed to read ${ii.name}`)}}te(ii=>[...ii,...cr]),Xn.target.value=""},gs=Xn=>{const wr=re[Xn];wr&&J.current.delete(`${wr.name}::${wr.size}`),te(Bn=>Bn.filter((cr,Pa)=>Pa!==Xn))},Ss=async()=>{if(re.length===0||!u)return{inline:[],paths:[]};const Xn=[],wr=[];for(const Bn of re){const cr=`${Bn.name}::${Bn.size}`,Pa=J.current.get(cr);if(Pa){wr.push(Pa);continue}if(Bn.size<=RHs){Xn.push(Bn);continue}const ii=Bn.name.replace(/[^a-zA-Z0-9._-]/g,"_"),$i=`${u.id}/${Date.now()}-${ii}`,Ln=atob(Bn.data),xa=new Uint8Array(Ln.length);for(let uo=0;uo{if(!/<[a-z][\s\S]*>/i.test(Xn)||typeof window>"u")return Xn;const wr=Xn.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,""),Bn=document.createElement("div");return Bn.innerHTML=wr,(Bn.textContent||Bn.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},Bt=j.useRef(null),zt=Bt.current&&fe===Bt.current.plain?Bt.current.html:null,vs=j.useRef(null),[dn,Ks]=j.useState(0),Cn=()=>{const Xn=vs.current,wr=Bt.current;!Xn||!wr||(Bt.current={plain:wr.plain,html:Xn.innerHTML})},Rr=Xn=>{const wr=/<[a-z][\s\S]*>/i.test(Xn.body),Bn=wr?Ds(Xn.body):Xn.body;Bt.current=wr?{plain:Bn,html:Xn.body}:null,ve(Xn.subject),ue(Bn),W(uj(Xn.subject,I||{first_name:""})),G(uj(Bn,I||{first_name:""})),le(!1),Ks(cr=>cr+1)},ia=Xn=>{let wr=Xn.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+|mailto:[^\s)]+)\)/g,(Bn,cr,Pa)=>`${cr}`);return wr=wr.replace(/(^|[\s(])((?:https?:\/\/|www\.)[^\s<)]+)/g,(Bn,cr,Pa)=>{const ii=Pa.startsWith("http")?Pa:`https://${Pa}`;return`${cr}${Pa}`}),wr},Hs=Xn=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(Xn)?Xn:Xn.split(/\n\n+/).map(wr=>`

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

`).join(""),Br=(Xn,wr)=>{const Bn="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let cr=Xn.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(ii,$i,Ln,xa,Ka)=>{if(!xa||/^(mailto:|tel:|#)/i.test(xa)||xa.includes("/bulk-email-track")||xa.includes("/ses-campaign-track"))return ii;const uo=`${Bn}?s=${wr}&t=click&u=${encodeURIComponent(xa)}`;return``});const Pa=``;return/<\/body>/i.test(cr)?cr=cr.replace(/<\/body>/i,`${Pa}`):cr=`${cr}${Pa}`,cr},Ur=async Xn=>{if(!(Xn!=null&&Xn.email))return ne.error("Please enter a recipient email"),!1;const wr=Xn||{first_name:""},Bn=uj(ce,wr),cr=Bt.current,Pa=cr&&fe===cr.plain,ii=uj(Pa?cr.html:fe,wr);let $i=Pa?ii:Hs(ii);Je&&rt&&($i=IHs($i,uj(rt,wr)));const Ln=u&&Xn.id?crypto.randomUUID():null;Ln&&($i=Br($i,Ln));try{if(u&&Xn.email){const uo=new Date(Date.now()-6e5).toISOString(),{data:Tc}=await q.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",Xn.email).eq("subject",Bn).gte("sent_at",uo).limit(1);if(Tc&&Tc.length>0)return console.log(`Skipping duplicate send to ${Xn.email} (same subject within 10 min)`),ne.info(`Skipped ${Xn.first_name||Xn.email} — already sent this in the last 10 min`),!0}const{inline:xa,paths:Ka}=await Ss();if(A){const uo=(f==null?void 0:f.display_name)||"ReLevelUp",Tc=`${uo.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Fd=`${uo} <${Tc}>`;let Nl=Ka[0];if(!Nl&&xa.length>0&&u){const Yr=xa[0],Eo=Yr.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Th=`${u.id}/${Date.now()}-${Eo}`,rh=atob(Yr.data),ro=new Uint8Array(rh.length);for(let pc=0;pc({name:Fd,type:Nl,data:Ho})),attachment_paths:Ka,skip_signature:!0}});if(Tc)throw Tc;if(!(uo!=null&&uo.success))throw new Error((uo==null?void 0:uo.error)||"Failed to send")}if(u&&Xn.id&&Ln&&(await q.from("bulk_email_sends").insert({id:Ln,user_id:u.id,contact_id:Xn.id,contact_email:Xn.email,subject:Bn,source:c||(A?"ses_bulk":"sphere_gaps")}),d))try{await q.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:Xn.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${Bn}`,completed_at:new Date().toISOString()})}catch(uo){console.warn("touch log insert failed",uo)}return!0}catch(xa){return console.error("Send error:",xa),ne.error("Failed to send to "+Xn.first_name+": "+(xa instanceof Error?xa.message:"Unknown error")),!1}},Wn=()=>{const Xn=Fe*Q2;return E.slice(Xn,Xn+Q2)},Sn=async(Xn=0,wr=Qe)=>{if(!U||!V){ne.error("Please fill in subject and message");return}X(!0),Ie("sending");let Bn=Math.max(0,Math.min(Xn,E.length)),cr=!1;for(;BnKa+1):Ce(Ka=>Ka+1),Ln<$i-1&&await new Promise(Ka=>setTimeout(Ka,150))}if(h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),cr||Ve.current||Bn>=E.length)break;if(!wr){X(!1),Ie("batch_complete");return}if(ze(0),await new Promise(Ln=>setTimeout(Ln,1500)),Ve.current){cr=!0;break}}X(!1),!cr&&!Ve.current&&zs(),Ie(cr||Ve.current?"batch_complete":"all_done")},Fn=async()=>{var wr;if(!U||!V){ne.error("Please fill in subject and message");return}const Xn=w?(r==null?void 0:r.length)||0:1;if(S.wouldExceed(Xn)){ne.error(`Your package includes ${(wr=S.limit)==null?void 0:wr.toLocaleString()} emails per month. You have ${S.remaining.toLocaleString()} left — request an upgrade for unlimited sending.`);return}if(A&&g&&!g.hasVerifiedSes&&!g.hasGmail){v(!0);return}if(!w){const Bn=I||{id:"",first_name:"",last_name:"",email:D.trim()};if(!Bn.email){ne.error("Please enter a recipient email");return}X(!0);try{await Ur(Bn)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),zs(),ne.success("Email sent successfully!"),t(!1),o==null||o())}finally{X(!1)}return}Ve.current=!1,ht.current=0,await Sn(0)},bn=async()=>{Ve.current=!1,ze(0),await Sn(ht.current,!1)},xs=async()=>{Ve.current=!1,at(!0),ze(0),await Sn(ht.current,!0)},Tr=()=>{if(Z){Ve.current=!0;return}t(!1),o==null||o()},Lr=Fe*Q2;Math.min(Lr+Q2,E.length);const la=w&&E.length>0?Math.round((Be+Ae)/E.length*100):0;return e.jsxs(Os,{open:s,onOpenChange:Tr,children:[e.jsxs(Fs,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",onPointerDownOutside:Xn=>{(ce||fe)&&Xn.preventDefault()},onInteractOutside:Xn=>{(ce||fe)&&Xn.preventDefault()},onEscapeKeyDown:Xn=>{(ce||fe)&&Xn.preventDefault()},children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:`h-5 w-5 ${A?"text-orange-500":"text-red-500"}`}),w?`Send to ${E.length} Contacts`:"Compose Email"]}),A?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&&ke==="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&&ke==="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:()=>{zs(),ve(""),ue(""),W(""),G(""),Bt.current=null,Ks(Xn=>Xn+1)},children:"Start fresh"})]}),ke==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Ct,{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 ",Wn().length," in this batch"]}),Qe&&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(Wn().length,1)*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Be+Ae," / ",E.length]}),e.jsxs("span",{children:[Be," sent • ",Ae," failed"]})]}),e.jsx($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Ve.current=!0},children:"Stop Sending"})]}),ke==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Vr,{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:[Be," sent, ",Ae," failed so far"]})]}),e.jsx(Yi,{value:la,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[E.length-Be-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:Tr,children:"Done for Now"}),e.jsxs($,{className:"flex-1 gap-2",onClick:xs,children:[e.jsx(Zr,{className:"h-4 w-4"}),"Resume Sending"]})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full",onClick:bn,children:["Send just the next ",Math.min(Q2,Math.max(E.length-(Be+Ae),0))," contacts"]})]}),ke==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Vr,{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:[Be," emails sent successfully",Ae>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",Ae," failed"]})]})]}),e.jsx($,{className:"w-full",onClick:Tr,children:"Close"})]}),ke==="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(Qr,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>le(!1),className:"h-7 px-2 text-xs",children:[e.jsx(mr,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(MHs,{onSelect:Rr})]}):e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>le(!0),children:[e.jsx(Qr,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(Vc,{}),!w&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"gmail-to",children:"To"}),e.jsx(SUt,{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:Xn=>{W(Xn.target.value),ve(Xn.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($e,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{G(Xn=>Xn+"{{first_name}}"),ue(Xn=>Xn+"{{first_name}}")},children:"{{first_name}}"}),e.jsx($e,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{G(Xn=>Xn+"{{last_name}}"),ue(Xn=>Xn+"{{last_name}}")},children:"{{last_name}}"}),b&&e.jsx($e,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const Xn=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${b} `;G(wr=>wr+Xn),ue(wr=>wr+Xn)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),zt&&!be?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:Xn=>Xn.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:Xn=>Xn.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:Xn=>Xn.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:Xn=>Xn.preventDefault(),onClick:()=>{const Xn=window.prompt("Link address (https://...)");Xn&&document.execCommand("createLink",!1,Xn)},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:vs,contentEditable:!0,suppressContentEditableWarning:!0,onInput:Cn,onBlur:Cn,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:zt}},dn)]}),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 Xn=document.getElementById("gmail-body"),wr=Xn?V.slice(Xn.selectionStart,Xn.selectionEnd):"",Bn=window.prompt("Link text (what the reader sees)",wr||"Click here");if(!Bn)return;let cr=window.prompt("Link address (https://...)","https://");if(!cr)return;cr=cr.trim(),/^(https?:\/\/|mailto:)/i.test(cr)||(cr=`https://${cr}`);const Pa=`[${Bn}](${cr})`,ii=Xn?Xn.selectionStart:V.length,$i=Xn?Xn.selectionEnd:V.length,Ln=V.slice(0,ii)+Pa+V.slice($i);G(Ln),ue(Ln)},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:Xn=>{G(Xn.target.value),ue(Xn.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(jn,{checked:Je&&Ke,onCheckedChange:ft,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 Xn;return(Xn=document.getElementById("gmail-attachments"))==null?void 0:Xn.click()},disabled:Z,children:[e.jsx(KI,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",Jce(W7e)," 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:yt})]}),re.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:re.map((Xn,wr)=>e.jsxs($e,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(KI,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:Xn.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",Jce(Xn.size),")"]}),e.jsx("button",{type:"button",onClick:()=>gs(wr),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(mr,{className:"h-3 w-3"})})]},wr))}),A&&re.some(Xn=>Xn.size>nbt)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",Jce(nbt)," 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:()=>{es(E[0]||null),Ie("reviewing")},disabled:!U||!V,className:"gap-2",children:["Review Emails",e.jsx(Qa,{className:"h-4 w-4"})]}):e.jsxs($,{onClick:Fn,disabled:Z||!U||!V||!D.trim(),className:"gap-2",children:[Z?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),Z?"Sending...":"Send Email"]})]})]}),ke==="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 ",Q2,"."]}),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:Qe,onChange:Xn=>at(Xn.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(Xn=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(gt==null?void 0:gt.id)===Xn.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>es(Xn),children:[Xn.first_name," ",Xn.last_name," — ",Xn.email]},Xn.id))})]}),gt&&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(pn,{className:"h-3.5 w-3.5"}),"Preview for ",gt.first_name," ",gt.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:"})," ",gt.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",uj(ce,gt)]})]}),e.jsx(Vc,{}),zt?e.jsx("div",{className:"rounded-lg border bg-background max-h-72 overflow-y-auto [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:uj(zt,gt)}}):e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:uj(fe,gt)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs($,{variant:"outline",onClick:()=>{Ie("composing"),es(null)},children:[e.jsx(Va,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs($,{onClick:Fn,disabled:Z,className:"gap-2",children:[Z?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),R?`Send First ${Q2}`:`Send to ${E.length}`]})]})]})]}),e.jsx(b6e,{open:x,onOpenChange:v,hasPending:!!(g!=null&&g.hasPendingSes),pendingEmails:g==null?void 0:g.pendingEmails})]})}function zHs(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const BHs={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function CUt({open:s,onOpenChange:t,listing:n}){const{user:r}=_s(),{data:a=[],isLoading:i}=L_(),{data:l=[]}=Uw(),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(new Set),[f,g]=j.useState(!1),[x,v]=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();v((P==null?void 0:P.gmail_email)||null)})()},[s,r]);const y=j.useMemo(()=>a.filter(P=>P.email),[a]),b=j.useMemo(()=>{let P=y;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},[y,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)},A=j.useMemo(()=>y.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})),[y,h]),{defaultSubject:E,defaultBody:I}=j.useMemo(()=>{var te,J,ce,ve;const P=n.property_address||`${n.city}, ${n.state}`,R=zHs(n.price),D=BHs[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}`,Z=((J=(te=n.photos)==null?void 0:te.find(fe=>fe.is_primary))==null?void 0:J.photo_url)||((ve=(ce=n.photos)==null?void 0:ce[0])==null?void 0:ve.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",le=`${ae}: ${P} — ${R}`,re=`

Hi {{first_name}},

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

${Z?` ${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:le,defaultBody:re}},[n]);return f?e.jsx(Nk,{open:f,onOpenChange:P=>{g(P),P||t(!1)},bulkContacts:A,defaultSubject:E,defaultBody:I,gmailEmail:x}):e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(Er,{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($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"}),h.size," selected"]})]}),e.jsx(go,{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(Ct,{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:y.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($e,{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(Vc,{}),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(pn,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}const $Hs="#2a4c64",UHs="#B8965A";function w6e(){const{user:s}=_s();return st({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(y=>y.is_active)||o[0]||{},d=a.data||{},u=i.data||{};let h=null;if(l.brokerage_id){const{data:y}=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=y||null}const m=!!(h!=null&&h.lock_colors),f=(...y)=>y.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 v=l.brokerage_name||d.brokerage_display_name||c.brokerage_legal_name||null;if(!v&&l.brokerage_id){const{data:y}=await q.from("brokerages").select("name").eq("id",l.brokerage_id).maybeSingle();v=(y==null?void 0:y.name)||null}return{name:l.name||s.email||"Your Name",headshotUrl:u.headshot_url||l.avatar_url||null,brokerageName:v,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||$Hs,accentColor:x||UHs,tagline:u.tagline||d.positioning_statement||l.title||d.title||null}}})}const rbt=[{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"}],qHs=[{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"}],WEe=s=>{switch(s){case"price_improvement":return"price_improvement";case"under_contract":return"under_contract";case"sold":return"sold";default:return"just_listed"}},VHs=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)}`},ede=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),abt=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}),ibt=(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)},iQ=(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()}…`},HHs=(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},WHs=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}},bM=(s,t)=>{const{r:n,g:r,b:a}=WHs(s);return`rgba(${n},${r},${a},${t})`};function Zst({listingId:s,open:t,onOpenChange:n,initialStatus:r}){var ve,fe;const a=Zn(),{data:i}=Kae(s||""),{data:l}=w6e(),[o,c]=j.useState(null),[d,u]=j.useState({base:null,accent:null}),[h,m]=j.useState(!1),[f,g]=j.useState(!1),[x,v]=j.useState(null),[y,b]=j.useState(null),[w,S]=j.useState(r||"just_listed"),[A,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,be)=>ue.is_primary&&!be.is_primary?-1:!ue.is_primary&&be.is_primary?1:(ue.sort_order??0)-(be.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,...qHs],[U]),V=W.find(ue=>ue.key===A)||U,G=((ve=rbt.find(ue=>ue.key===w))==null?void 0:ve.ribbon)||"JUST LISTED",Z=y||((fe=O[0])==null?void 0:fe.photo_url)||null,X=VHs((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 be;if(!t)return;S(r||WEe(i==null?void 0:i.status));const ue=((be=O[0])==null?void 0:be.photo_url)||null;b(Ee=>Ee||ue)},[t,i==null?void 0:i.id,O.length]),j.useEffect(()=>{t||(v(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[be,Ee,ke]=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 Ie=be.data;c({name:(Ie==null?void 0:Ie.name)||((Ae=i.agent)==null?void 0:Ae.name)||"Agent",phone:(Ie==null?void 0:Ie.phone)||(Ie==null?void 0:Ie.phone_e164)||null,avatar_url:(Ie==null?void 0:Ie.avatar_url)||null,brokerage:((Ce=Ie==null?void 0:Ie.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,Ne=ke.data||[],Be=Ne.find(Ve=>Ve.is_active)||Ne[0]||{},Se=Ve=>typeof Ve=="string"&&Ve.trim()?Ve.trim():null;u({base:Se(Fe==null?void 0:Fe.brand_color)||Se(Be.brand_color),accent:Se(Fe==null?void 0:Fe.accent_color)||Se(Be.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(", "),be=ae.join(" · "),Ee=ede(i.price),ke=X?`call or text ${X}`:"send me a message",Ie=(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"}!`},Ne={just_listed:`Want a private tour? ${ke}.`,price_improvement:`This one won't last at the new number — ${ke}.`,under_contract:`Looking for something similar? ${ke}.`,sold:`Thinking about making a move? ${ke}.`,open_house:`Stop by or ${ke} for details.`},Be={just_listed:"#JustListed",price_improvement:"#PriceImprovement",under_contract:"#UnderContract",sold:"#JustSold",open_house:"#OpenHouse"},Se=[Fe[w],i.property_address||"",[be,Ee].filter(Boolean).join(" · "),i.description?i.description.split(/\n+/)[0].slice(0,180):"",Ne[w],[Be[w],Ie?`#${Ie}RealEstate`:"","#RealEstate","#DreamHome"].filter(Boolean).join(" ")].filter(Boolean);P(Se.join(` `))},[t,i==null?void 0:i.id,w,X,R]);const le=j.useCallback(async()=>{if(!i)return;const ue=(o==null?void 0:o.name)||(l==null?void 0:l.name)||"Agent",be=(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 ke=Ee.getContext("2d");if(!ke)throw new Error("Canvas unavailable");if(ke.fillStyle=V.base,ke.fillRect(0,0,1080,1080),Z)try{const ze=await abt(Z);ibt(ke,ze,0,0,1080,1080)}catch{}const Ie=ke.createLinearGradient(0,0,0,1080);Ie.addColorStop(0,bM(V.base,.6)),Ie.addColorStop(.34,bM(V.base,.18)),Ie.addColorStop(.62,bM(V.base,.5)),Ie.addColorStop(1,bM(V.base,.98)),ke.fillStyle=Ie,ke.fillRect(0,0,1080,1080),ke.fillStyle=V.accent,ke.fillRect(56,62,72,3),ke.font="600 22px Arial, sans-serif",GHs(ke,G,146,72,8),(w==="sold"||w==="under_contract")&&(ke.save(),ke.fillStyle=bM(V.accent,.92),ke.fillRect(0,430,1080,96),ke.fillStyle=V.base,ke.font="700 46px Arial, sans-serif",ke.textAlign="center",ke.textBaseline="middle",ke.fillText(w==="sold"?"SOLD":"UNDER CONTRACT",540,479),ke.restore(),ke.textAlign="left"),ke.save(),ke.shadowColor="rgba(0,0,0,0.55)",ke.shadowBlur=24,ke.shadowOffsetY=4,ke.fillStyle="#F8FAFC",ke.font="600 64px Georgia, serif",ke.textBaseline="top";const Fe=HHs(ke,i.property_address||`${i.city||""}, ${i.state||""}`.trim(),952,2);let Ne=Fe.length>1?590:654;Fe.forEach(ze=>{ke.fillText(ze,64,Ne),Ne+=70}),ke.restore();const Be=[i.city,i.state].filter(Boolean).join(", ")+(i.neighborhood?` · ${i.neighborhood}`:"");ke.fillStyle="rgba(248,250,252,0.9)",ke.font="600 26px Arial, sans-serif",ke.fillText(iQ(ke,Be.toUpperCase(),952),64,Ne+8),ke.fillStyle=V.accent,ke.font="700 56px Arial, sans-serif";const Se=w==="sold"?`SOLD · ${ede(i.price)}`:w==="price_improvement"?`NOW ${ede(i.price)}`:ede(i.price);ke.fillText(Se,64,Ne+58),ae.length>0&&(ke.fillStyle="rgba(248,250,252,0.86)",ke.font="600 22px Arial, sans-serif",ke.fillText(iQ(ke,ae.join(" · "),400),620,Ne+78));const Ae=ke.createLinearGradient(0,880,0,1080);Ae.addColorStop(0,bM(V.base,.96)),Ae.addColorStop(1,V.base),ke.fillStyle=Ae,ke.fillRect(0,880,1080,200),ke.fillStyle=V.accent,ke.fillRect(0,880,1080,3),ke.save(),ke.beginPath(),ke.arc(124,980,60,0,Math.PI*2),ke.closePath(),ke.fillStyle=bM(V.accent,.18),ke.fill(),ke.lineWidth=6,ke.strokeStyle=V.accent,ke.stroke(),ke.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 abt(Ce);ibt(ke,ze,64,920,120,120),qe=!0}catch{qe=!1}qe||(ke.fillStyle=V.accent,ke.font="700 48px Arial, sans-serif",ke.textAlign="center",ke.textBaseline="middle",ke.fillText(ue.charAt(0).toUpperCase(),124,982)),ke.restore(),ke.textAlign="left",ke.textBaseline="alphabetic",ke.fillStyle="#F8FAFC",ke.font="600 38px Georgia, serif",ke.fillText(iQ(ke,ue,X?430:820),212,970),be&&(ke.fillStyle=V.accent,ke.font="600 20px Arial, sans-serif",ke.fillText(iQ(ke,be.toUpperCase(),X?430:820),212,1008)),X&&(ke.textAlign="right",ke.fillStyle=bM(V.accent,.9),ke.font="600 16px Arial, sans-serif",ke.fillText("CALL · TEXT",1016,958),ke.fillStyle="#F8FAFC",ke.font="600 38px Arial, sans-serif",ke.fillText(X,1016,1008)),v(Ee.toDataURL("image/png"))}catch(Ee){console.error("Generate graphic error",Ee),ne.error("Could not generate graphic")}finally{m(!1)}},[i,o,l,V,Z,G,w,ae,X]);j.useEffect(()=>{if(!t||!i)return;const ue=setTimeout(()=>{le()},300);return()=>clearTimeout(ue)},[t,i==null?void 0:i.id,o==null?void 0:o.name,y,w,A,l==null?void 0:l.brandColor]);const re=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(),ne.success("Downloaded!")},J=async()=>{try{await navigator.clipboard.writeText(I),ne.success("Caption copied")}catch{ne.error("Copy not supported in this browser")}},ce=async()=>{var ue;if(x){g(!0);try{const{data:be}=await q.auth.getUser(),Ee=(ue=be.user)==null?void 0:ue.id;if(!Ee)throw new Error("Not signed in");const ke=await re(x),Ie=`listing-social/${Ee}/${crypto.randomUUID()}.png`,{error:Fe}=await q.storage.from("agent-uploads").upload(Ie,ke,{contentType:"image/png",upsert:!0});if(Fe)throw Fe;const{data:Ne}=q.storage.from("agent-uploads").getPublicUrl(Ie);sessionStorage.setItem("social-studio-seed",JSON.stringify({mediaUrl:Ne.publicUrl,mediaType:"image",caption:I,source:"listing",sourceRef:i==null?void 0:i.id})),n(!1),a("/social-studio"),ne.success("Draft ready in Social Studio")}catch(be){console.error("Push to Social Studio failed",be),ne.error("Could not send to Social Studio")}finally{g(!1)}}};return e.jsx(Os,{open:t,onOpenChange:n,children:e.jsx(Fs,{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($s,{className:"flex items-center gap-2 pr-8",children:[e.jsx(wn,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Share this listing"})]}),e.jsx(Er,{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:rbt.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 ${A===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(Ct,{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 ${y===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(Za,{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 le(),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(ji,{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(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(By,{className:"h-3.5 w-3.5"}),"Push to Social Studio"]})]})]})})})}function KHs({listing:s,canEdit:t}){const n=Zn(),{data:r,isLoading:a}=nDs(s.id),i=C7t(),l=A7t(),[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(N7t),[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(y=>{var b;return(b=y.label)==null?void 0:b.trim()})}}),ne.success("Pitch saved")},x=async()=>{await l.mutateAsync({listingId:s.id,stage:"won"}),ne.success("Assignment won — welcome to Launch"),n(`/mission-control/listings/${s.id}/commercial`)},v=async()=>{await l.mutateAsync({listingId:s.id,stage:"lost",lostReason:h}),ne("Marked as lost opportunity"),n("/mission-control/listings")};return a?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(Ct,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Owner & decision makers"}),e.jsx(Vn,{children:"Who actually signs the listing agreement."})]}),e.jsxs(Le,{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:y=>c({...o,owner_name:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Entity / company"}),e.jsx(pe,{value:o.owner_company,onChange:y=>c({...o,owner_company:y.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:y=>c({...o,owner_email:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:o.owner_phone,onChange:y=>c({...o,owner_phone:y.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:y=>c({...o,decision_maker_notes:y.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:y=>c({...o,pitch_date:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Competing brokers"}),e.jsx(pe,{value:o.competitors,onChange:y=>c({...o,competitors:y.target.value})})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Positioning & pricing strategy"}),e.jsx(Vn,{children:"The argument you're making for how this asset goes to market."})]}),e.jsxs(Le,{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:y=>c({...o,positioning:y.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:y=>c({...o,pricing_strategy:y.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:y=>c({...o,pitch_notes:y.target.value}),placeholder:"Never shown to the owner."})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Proposed launch plan"}),e.jsx(Vn,{children:"Shown on the owner-facing preview — this is what they buy."})]}),e.jsxs(Le,{className:"space-y-3",children:[d.map((y,b)=>e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:y.label,placeholder:"Milestone",onChange:w=>u(d.map((S,A)=>A===b?{...S,label:w.target.value}:S))}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u(d.filter((w,S)=>S!==b)),children:e.jsx(mr,{className:"h-4 w-4"})})]}),e.jsx(Rs,{className:"mt-2",rows:2,value:y.detail??"",placeholder:"What happens in this step",onChange:w=>u(d.map((S,A)=>A===b?{...S,detail:w.target.value}:S))})]},b)),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>u([...d,{label:"",detail:""}]),children:[e.jsx(cn,{className:"mr-1.5 h-3.5 w-3.5"})," Add step"]})]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(je,{className:"border-primary/30 bg-gradient-to-br from-primary/[0.06] to-transparent",children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Owner preview"}),e.jsx(Vn,{children:"A private, seller-facing page showing exactly what happens the day they hire you."})]}),e.jsx(Le,{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),ne.success("Link copied")},children:[e.jsx(Za,{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(Ir,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Outcome"})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsxs($,{className:"w-full",children:[e.jsx(Kl,{className:"mr-2 h-4 w-4"})," Won listing"]})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Convert this pitch into a Commercial Launch?"}),e.jsx(ic,{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(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:x,children:"Yes — we won it"})]})]})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full",children:[e.jsx(ju,{className:"mr-2 h-4 w-4"})," Lost opportunity"]})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Mark as lost?"}),e.jsx(ic,{children:"Kept private in your archive so you can learn from it."})]}),e.jsx(pe,{placeholder:"Reason (optional)",value:h,onChange:y=>m(y.target.value)}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:v,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(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save pitch"]})})]}):e.jsx(je,{children:e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Private pitch workspace"}),e.jsx(Vn,{children:"Only the listing agent can view or update pitch strategy and owner information."})]})})}function YHs({listingId:s}){const{data:t=[],isLoading:n}=r6e(s),r=M$t(),a=P$t(),i=yqs(),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});ne.success("Document uploaded")}catch(g){ne.error(g.message||"Upload failed")}finally{l.current&&(l.current.value="")}},m=async f=>{try{window.open(await $st(f),"_blank")}catch{ne.error("Could not open document")}};return e.jsx("div",{className:"space-y-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Deal room"}),e.jsx(Vn,{children:"Offering memorandum, financials and diligence files. Everything is stored privately and released through expiring secure links only."})]}),e.jsxs(Le,{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(YHe).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(Oyt).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(Ct,{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(Ct,{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(Qr,{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(Qr,{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($e,{variant:"secondary",children:YHe[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(ji,{className:"mr-2 h-3.5 w-3.5"}):f.gate_level==="nda"?e.jsx(Rm,{className:"mr-2 h-3.5 w-3.5"}):e.jsx(jc,{className:"mr-2 h-3.5 w-3.5"}),e.jsx(fs,{})]}),e.jsx(hs,{children:Object.entries(Oyt).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(qn,{className:"h-4 w-4"})})]},f.id))})]})]})})}const ZHs={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 XHs({listingId:s}){const{data:t=[],isLoading:n}=Htt(s),{data:r=[]}=Vtt(s),a=j.useMemo(()=>{const o={};for(const c of r)c.lead_id&&(o[c.lead_id]=(o[c.lead_id]??0)+(Byt[c.event_type]??1));return o},[r]),i=j.useMemo(()=>[...t].map(o=>({...o,score:(a[o.id]??0)+(Byt[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(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[l.length>0&&e.jsxs(je,{className:"border-amber-500/30 bg-amber-500/[0.04]",children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"High-interest prospects"}),e.jsx(Vn,{children:"Ranked by document access, tour requests and repeat engagement."})]}),e.jsx(Le,{className:"grid gap-3 md:grid-cols-2",children:l.slice(0,6).map(o=>{const c=$yt(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||ZHe[o.investor_role||"other"]})]}),e.jsx($e,{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(pn,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Investors & inquiries"}),e.jsx(Vn,{children:"Every prospect is written into your LevelUp CRM automatically."})]}),e.jsx(Le,{children:i.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed py-14 text-center",children:[e.jsx(Yn,{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=$yt(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($e,{variant:"secondary",children:ZHe[o.investor_role]??o.investor_role}),e.jsx($e,{variant:"outline",children:ZHs[o.lead_type]??o.lead_type}),e.jsx($e,{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 QHs={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 JHs({listing:s}){const{data:t=[],isLoading:n}=Vtt(s.id),{data:r=[]}=Htt(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(v=>v.trim()).filter(Boolean)}});if(x)throw x;if(g!=null&&g.error)throw new Error(g.error);ne.success(f?"Activity report sent to your owner":"Weekly report generated")}catch(g){ne.error(g.message||"Could not build the report")}finally{d(!1)}},h=j.useMemo(()=>{const f=v=>{const y=Array.isArray(v)?v:[v];return t.filter(b=>y.includes(b.event_type)).length},g=new Set(t.map(v=>v.session_id).filter(Boolean)),x=new Map;return t.forEach(v=>v.session_id&&x.set(v.session_id,(x.get(v.session_id)??0)+1)),{views:f("page_view")||s.view_count||0,unique:g.size,repeat:[...x.values()].filter(v=>v>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:Ta},{label:"Unique visitors",value:h.unique,icon:Yn},{label:"Repeat visitors",value:h.repeat,icon:rf},{label:"OM requests",value:h.omRequests,icon:xJ},{label:"Document downloads",value:h.downloads,icon:ji},{label:"Tour requests",value:h.tours,icon:rf},{label:"Total inquiries",value:h.inquiries,icon:Yn},{label:"Shares",value:h.shares,icon:Hd}];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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Send the weekly owner report"}),e.jsx(Vn,{children:"Last 7 days of activity, packaged as a branded report the owner can read in their inbox."})]}),e.jsxs(Le,{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(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(pn,{className:"mr-2 h-4 w-4"}),"Send report"]}),e.jsx($,{variant:"outline",onClick:()=>u(!1),disabled:c,children:"Save without sending"})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Owner activity report"}),e.jsx(Vn,{children:"Everything below is what your owner sees in the weekly activity report — proof the asset is being worked."})]}),e.jsx(Le,{children:n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Ct,{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(rf,{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:QHs[f.event_type]??f.event_type}),f.lead_id&&e.jsx($e,{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 eGs({listing:s,details:t,publicUrl:n}){var g,x;const r=Zn(),[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(Va,{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:sL(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(Hc,{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((v,y)=>e.jsx("button",{onClick:()=>c(y),className:`h-16 w-24 shrink-0 overflow-hidden rounded-lg border-2 ${y===o?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:v.photo_url,alt:"",className:"h-full w-full object-cover"})},v.id??y))}),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($e,{variant:"outline",className:"border-primary/30 bg-primary/10 text-primary",children:[e.jsx(wi,{className:"mr-1 h-3 w-3"})," Commercial"]}),(t==null?void 0:t.deal_type)&&e.jsx($e,{variant:"secondary",children:SL[t.deal_type]}),(t==null?void 0:t.commercial_type)&&e.jsx($e,{variant:"secondary",children:r6[t.commercial_type]}),(t==null?void 0:t.is_confidential)&&e.jsxs($e,{variant:"outline",children:[e.jsx(jc,{className:"mr-1 h-3 w-3"})," Confidential"]})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:sL(s,t)}),e.jsxs("p",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(ui,{className:"h-4 w-4"})," ",$ae(s,t)]}),e.jsx("p",{className:"mt-2 text-2xl font-semibold",children:jG(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(Ir,{className:"mr-2 h-4 w-4"})," View microsite"]}),s.allow_sharing&&e.jsxs($,{onClick:()=>i(!0),children:[e.jsx(Hd,{className:"mr-2 h-4 w-4"})," Share link"]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(T7t,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"About this property"})}),e.jsx(Le,{className:"whitespace-pre-line text-sm text-muted-foreground",children:s.description})]}),u.length>0&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Highlights"})}),e.jsx(Le,{className:"space-y-2",children:u.map((v,y)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(wn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("span",{children:v})]},y))})]}),h.length>0&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Available spaces"})}),e.jsx(Le,{className:"space-y-2 text-sm",children:h.map((v,y)=>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:v.suite||`Space ${y+1}`}),e.jsx("span",{className:"text-muted-foreground",children:[xE(v.sf),v.rate,v.use,v.availability].filter(Boolean).join(" · ")})]},y))})]}),m.length>0&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Tenant roster"})}),e.jsx(Le,{className:"space-y-2 text-sm",children:m.map((v,y)=>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:v.name||`Tenant ${y+1}`}),e.jsx("span",{className:"text-muted-foreground",children:[xE(v.sf),v.rent,v.lease_expiry].filter(Boolean).join(" · ")})]},y))})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Listing agent"})}),e.jsxs(Le,{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(pn,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Open to referrals"})}),e.jsx(Le,{className:"text-sm text-muted-foreground",children:"The listing agent welcomes buyer or tenant referrals on this opportunity."})]})]})]})]}),e.jsx(g6e,{open:a,onOpenChange:i,listingId:s.id,listingSlug:s.slug??null,listingTitle:sL(s,t),isCommercial:!0})]})}function tGs(){const{listingId:s=""}=Wi(),t=Zn(),{user:n}=_s(),[r,a]=Nc(),{data:i,isLoading:l}=Kae(s),{data:o}=k7t(s),{data:c=[]}=r6e(s),{data:d=[]}=Vtt(s),{data:u=[]}=Htt(s),h=S7t(),m=A7t(),f=rDs(),g=k$t(),x=S$t(),v=C$t(),y=A$t(),[b,w]=j.useState(!1),[S,A]=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 tDs(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]),Z=async J=>{var ce;if(!(!J||!i)){w(!0);try{for(const ve of Array.from(J)){const fe=ve.name.split(".").pop(),ue=`${n==null?void 0:n.id}/${i.id}/${Date.now()}-${Math.random().toString(36).slice(2)}.${fe}`,{error:be}=await q.storage.from("listing-photos").upload(ue,ve);if(be)throw be;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)})}ne.success("Photos uploaded")}catch(ve){ne.error(ve.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(Ct,{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",le=i7e.findIndex(J=>J.key===ae),re=sL(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(Va,{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($e,{variant:"outline",className:"border-primary/30 bg-primary/10 text-primary",children:[e.jsx(wi,{className:"mr-1 h-3 w-3"})," Commercial Launch"]}),(o==null?void 0:o.deal_type)&&e.jsx($e,{variant:"secondary",children:SL[o.deal_type]}),(o==null?void 0:o.commercial_type)&&e.jsx($e,{variant:"secondary",children:r6[o.commercial_type]}),X&&e.jsxs($e,{className:"bg-amber-500/15 text-amber-600 hover:bg-amber-500/15",children:[e.jsx(ph,{className:"mr-1 h-3 w-3"})," Pitch — private"]}),(o==null?void 0:o.is_confidential)&&e.jsxs($e,{variant:"outline",children:[e.jsx(jc,{className:"mr-1 h-3 w-3"})," Confidential"]})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:re}),e.jsx("p",{className:"text-muted-foreground",children:$ae(i,o)}),e.jsx("p",{className:"mt-2 text-xl font-semibold",children:jG(o,i.price)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[!te&&e.jsxs($e,{variant:"outline",className:"self-center",children:[e.jsx(jc,{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(pi,{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(Ir,{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(Ir,{className:"mr-2 h-4 w-4"})," View microsite"]})]})]}),!X&&e.jsx("div",{className:"mt-6 flex flex-wrap items-center gap-2",children:i7e.filter(J=>J.key!=="pitch").map((J,ce)=>{const ve=i7e.findIndex(be=>be.key===J.key),fe=ve===le,ue=vete&&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 ${fe?"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(ma,{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(KHs,{listing:i,canEdit:te}):e.jsxs(pa,{value:te||["overview","marketing"].includes(U)?U:"overview",onValueChange:W,children:[e.jsxs(ga,{className:"mb-6 flex w-full flex-wrap justify-start",children:[e.jsx(Xt,{value:"overview",children:"Overview"}),e.jsx(Xt,{value:"marketing",children:"Marketing"}),te&&e.jsx(Xt,{value:"investors",children:"Investors & Leads"}),te&&e.jsx(Xt,{value:"reporting",children:"Reporting"}),te&&e.jsx(Xt,{value:"documents",children:"Documents"}),te&&e.jsx(Xt,{value:"settings",children:"Settings"})]}),e.jsxs(Qt,{value:"overview",className:"space-y-6",children:[e.jsx(T7t,{details:o}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs(je,{className:"lg:col-span-2",children:[e.jsxs(St,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Et,{className:"text-base",children:"Launch readiness"}),e.jsx(Vn,{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(Le,{className:"space-y-2",children:K4e.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(ma,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Quick actions"})}),e.jsxs(Le,{className:"grid gap-2",children:[e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>A(!0),children:[e.jsx(Hd,{className:"mr-2 h-4 w-4"})," Share link"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>I(!0),children:[e.jsx(Xp,{className:"mr-2 h-4 w-4"})," Signage QR code"]}),te&&e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>R(!0),children:[e.jsx(pn,{className:"mr-2 h-4 w-4"})," Email brokers & investors"]}),te&&e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>O(!0),children:[e.jsx(wn,{className:"mr-2 h-4 w-4"})," Generate social post"]}),te&&e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>W("documents"),children:[e.jsx(jc,{className:"mr-2 h-4 w-4"})," Manage gated OM"]})]})]}),(o==null?void 0:o.call_for_offers_at)&&e.jsxs(je,{className:"border-amber-500/30 bg-amber-500/[0.05]",children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm",children:"Call for offers"})}),e.jsx(Le,{children:e.jsxs("p",{className:"flex items-center gap-2 text-lg font-semibold",children:[e.jsx(Su,{className:"h-4 w-4"}),new Date(o.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Recent engagement"})}),e.jsxs(Le,{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(Qt,{value:"marketing",className:"space-y-6",children:[e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Photography"}),e.jsx(Vn,{children:"The first image becomes the cinematic microsite hero."})]}),e.jsx(Le,{children:te?e.jsx(sUt,{photos:i.photos??[],uploading:b,onUpload:Z,onRemove:J=>x.mutate({photoId:J,listingId:i.id}),onReorder:J=>v.mutate({photos:J.map(ce=>({id:ce.id,sort_order:ce.sort_order,is_primary:ce.is_primary}))}),onSetPrimary:J=>y.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:re,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:cl,title:"Property microsite",body:"Institutional-grade public page with gated OM.",action:()=>window.open(V,"_blank"),cta:"Preview"},{icon:Xp,title:"Signage QR",body:"On-site sign that routes to the microsite.",action:()=>I(!0),cta:"Create"},...te?[{icon:pn,title:"Broker & investor email",body:"Send to targeted segments of your database.",action:()=>R(!0),cta:"Compose"},{icon:wn,title:"Social & LinkedIn",body:"Branded launch graphics and copy.",action:()=>O(!0),cta:"Generate"}]:[]].map(J=>e.jsxs(je,{className:"flex flex-col",children:[e.jsxs(St,{className:"pb-3",children:[e.jsx(J.icon,{className:"mb-2 h-5 w-5"}),e.jsx(Et,{className:"text-sm",children:J.title}),e.jsx(Vn,{className:"text-xs",children:J.body})]}),e.jsx(Le,{className:"mt-auto",children:e.jsx($,{size:"sm",variant:"outline",className:"w-full",onClick:J.action,children:J.cta})})]},J.title))})]}),te&&e.jsx(Qt,{value:"investors",children:e.jsx(XHs,{listingId:i.id})}),te&&e.jsx(Qt,{value:"reporting",children:e.jsx(JHs,{listing:i})}),te&&e.jsx(Qt,{value:"documents",children:e.jsx(YHs,{listingId:i.id})}),te&&e.jsx(Qt,{value:"settings",className:"space-y-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Visibility"}),e.jsx(Vn,{children:"Control who can see this offering."})]}),e.jsxs(Le,{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(jn,{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(jn,{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(jn,{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(jn,{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),ne.success("Copied")},children:e.jsx(Za,{className:"h-3.5 w-3.5"})})]})]})]})})]})}),e.jsx(g6e,{open:S,onOpenChange:A,listingId:i.id,listingSlug:i.slug,listingTitle:re,isCommercial:!0}),e.jsx(pUt,{open:E,onOpenChange:I,url:V,title:re,fileBase:i.slug||i.id}),e.jsx(CUt,{open:P,onOpenChange:R,listing:i}),e.jsx(Zst,{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(eGs,{listing:i,details:o,publicUrl:V})}function sGs(){var m,f,g;const{token:s=""}=Wi(),{data:t,isLoading:n,error:r}=st({queryKey:["commercial-pitch-preview",s],queryFn:async()=>{const{data:x,error:v}=await q.functions.invoke("commercial-pitch-preview",{body:{token:s}});if(v)throw v;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=Gtt(i).slice(0,4),u=l.launch_plan??[],h=[{icon:cl,label:"Dedicated property microsite",detail:"An institutional-grade page built for this asset alone."},{icon:Qr,label:"Offering Memorandum & teaser",detail:"Gated, tracked and released only to qualified prospects."},{icon:pn,label:"Targeted broker & investor email",detail:"Direct outreach to buyers, brokers and 1031 capital."},{icon:Xp,label:"Signage, QR & social distribution",detail:"On-site and digital presence working together."},{icon:Gl,label:"Weekly owner activity reporting",detail:"Views, OM requests, downloads, tours and prospect interest."},{icon:Rm,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(Dl,{children:[e.jsxs("title",{children:["Marketing proposal — ",sL(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:sL(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(ui,{className:"h-4 w-4"})," ",$ae(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:SL[(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:r6[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:jG(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,v)=>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(v+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})]})]},v))})]})}),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 nGs={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},rGs=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function aGs(){var J;const[s]=Nc(),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,v]=j.useState(""),[y,b]=j.useState(""),[w,S]=j.useState(""),[A,E]=j.useState("tour"),[I,P]=j.useState(!1),[R,D]=j.useState(!1),O=async()=>{if(!f.trim()||!x.trim()){ne.error("Please enter your name and email");return}P(!0);try{const ve=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:y.trim()||null,message:w.trim()||null,intent:A})}),fe=await ve.json();if(!ve.ok||!(fe!=null&&fe.success))throw new Error((fe==null?void 0:fe.error)||"Could not send");D(!0),ne.success("Sent! The agent will be in touch shortly.")}catch(ce){ne.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(ve=>ve.json()).then(ve=>{ve.error?l("This private listing link is no longer valid."):a({listing:ve.listing,agent:ve.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(Dl,{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(jc,{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],Z=nGs[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,le=encodeURIComponent(`Interested in ${U.address}`),re=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(Dl,{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(jc,{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($e,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:Z})}),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(je,{className:"shadow-xl border-slate-200",children:e.jsxs(Le,{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(ui,{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:rGs(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(n2,{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(C0,{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(w_,{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,ve)=>e.jsx("button",{type:"button",onClick:()=>{u(ve),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"})},ve))})]})]})}),e.jsxs(je,{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(Le,{className:"p-6 sm:p-8",children:R?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(Vr,{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 ${A===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=>v(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:y,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(je,{className:"mt-6 mb-12 shadow-lg border-slate-200",children:e.jsxs(Le,{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=${le}&body=${re}`,children:[e.jsx(pn,{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(Su,{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(mr,{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(kd,{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 iGs(){var i;const{slug:s}=Wi(),{data:t,isLoading:n,error:r}=L7t(s);if(j.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),j.useEffect(()=>{t!=null&&t.id&&wu(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(xn,{className:"h-28 w-28 rounded-full"}),e.jsx(xn,{className:"h-6 w-48"}),e.jsx(xn,{className:"h-4 w-36"})]}),e.jsx(xn,{className:"h-12 w-full"}),e.jsx(xn,{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(Dl,{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(Ktt,{card:t})]})}const oGs="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",lGs="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",cGs="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",dGs="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",uGs="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",hGs="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",o3e={"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:hGs},"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:oGs},"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:cGs},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:uGs}},mGs=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function AUt(s){return s&&s in o3e?o3e[s]:o3e["minimal-mono"]}function fGs(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 EUt({slugOverride:s}={}){var Ss;const{slug:t}=Wi(),n=s||t,[r]=Nc(),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,v]=j.useState(null),[y,b]=j.useState(!1),[w,S]=j.useState(!1),[A,E]=j.useState(0),[I,P]=j.useState(!1),[R,D]=j.useState(""),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Z]=j.useState(""),[X,ae]=j.useState(""),[le,re]=j.useState(""),[te,J]=j.useState(""),[ce,ve]=j.useState(""),[fe,ue]=j.useState(""),[be,Ee]=j.useState(""),[ke,Ie]=j.useState(""),[Fe,Ne]=j.useState(""),[Be,Se]=j.useState(""),[Ae,Ce]=j.useState([]),[qe,ze]=j.useState([]),[Ve,ht]=j.useState(""),[Qe,at]=j.useState(""),[rt,Ke]=j.useState(""),[Je,ft]=j.useState([]);j.useEffect(()=>{gt()},[n,a]);const gt=async()=>{if(!n)return;l(!0);const{data:Ds,error:Bt}=await q.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if(Bt||!Ds){P(!0),l(!1);return}u(Ds),m.current=Ds;const{data:zt}=await q.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Ds.user_id).single();if(zt){let vs;if(zt.brokerage_id){const{data:Cn}=await q.from("brokerages").select("name").eq("id",zt.brokerage_id).single();vs=(Cn==null?void 0:Cn.name)||void 0}let dn=zt.avatar_url||null;if(!dn){const{data:Cn}=q.storage.from("avatars").getPublicUrl(`${Ds.user_id}/avatar.jpg`);Cn!=null&&Cn.publicUrl&&(dn=`${Cn.publicUrl}?t=${Date.now()}`)}const Ks={...zt,avatar_url:dn,brokerage_name:vs};c(Ks),h.current=Ks}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",Ds.id);const{data:vs,error:dn}=await q.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:Ds.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:vs,resolveErr:dn}),!dn&&(vs!=null&&vs.contact_id)){v(vs.contact_id);const Ks=vs.contact;Ks&&(g(Ks),D(Ks.first_name||""),U(Ks.last_name||""),V(Ks.email||""),Z(Ks.phone||""),ae(Ks.address||""),re(Ks.city||""),J(Ks.state||""),ve(Ks.zip||""),ue(Ks.birthday||""),Ee(Ks.home_anniversary||""))}}catch(vs){console.error("Failed to resolve token:",vs)}l(!1)},es=async()=>{var Ds,Bt;if(!R.trim()){ne.error("Please enter your first name");return}if(!n){ne.error("Invalid page. Please refresh.");return}S(!0);try{let zt=(Ds=m.current)==null?void 0:Ds.id,vs=(Bt=m.current)==null?void 0:Bt.user_id;if(!zt||!vs){const{data:Cn}=await q.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!Cn){ne.error("This page is no longer active. Please contact the agent directly."),S(!1);return}zt=Cn.id,vs=Cn.user_id}const dn={intake_page_id:zt,agent_user_id:vs,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:le.trim()||null,state:te.trim()||null,zip:ce.trim()||null,birthday:fe||null,home_anniversary:be||null,real_estate_interest:ke||null,message:Fe.trim()||null,life_events:{spouse_name:Be.trim()||null,kids:Ae.filter(Cn=>Cn.name.trim()),pets:qe.filter(Cn=>Cn.name.trim()),favorite_spots:Ve.trim()||null,dream_neighborhood:Qe.trim()||null,wedding_anniversary:rt||null},referrals:Je.filter(Cn=>Cn.name.trim()&&Cn.contact.trim())},{error:Ks}=await q.from("contact_intake_submissions").insert(dn);if(console.log("[ConnectPage] Insert result:",{error:Ks}),Ks)throw Ks;a&&await q.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const Cn=[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:vs,contactName:Cn,contactEmail:W.trim()||null,contactPhone:G.trim()||null,slug:n})})}catch(Cn){console.warn("Connect page notification failed (non-blocking):",Cn)}b(!0)}catch(zt){console.error(zt),ne.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(Ct,{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(y)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(Dl,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(Fr.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(Fr.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(Vr,{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 Ht=!!a&&!!f,as=(d==null?void 0:d.show_little_things)??!0,bs=[{title:Ht?"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:Ds=>D(Ds.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:Ds=>U(Ds.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:Ds=>V(Ds.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:Ds=>Z(Ds.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:Ds=>ae(Ds.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:le,onChange:Ds=>re(Ds.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:Ds=>J(Ds.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:Ds=>ve(Ds.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:fe,onChange:Ds=>ue(Ds.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:be,onChange:Ds=>Ee(Ds.target.value),className:"connect-input"})]})]})]})},...as?[{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:Be,onChange:Ds=>Se(Ds.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:rt,onChange:Ds=>Ke(Ds.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(Ds=>[...Ds,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(cn,{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((Ds,Bt)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Ds.name,onChange:zt=>Ce(vs=>vs.map((dn,Ks)=>Ks===Bt?{...dn,name:zt.target.value}:dn)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Ds.age,onChange:zt=>Ce(vs=>vs.map((dn,Ks)=>Ks===Bt?{...dn,age:zt.target.value}:dn)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>Ce(zt=>zt.filter((vs,dn)=>dn!==Bt)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(mr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Bt))]})]}),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(Ds=>[...Ds,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(cn,{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((Ds,Bt)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Ds.name,onChange:zt=>ze(vs=>vs.map((dn,Ks)=>Ks===Bt?{...dn,name:zt.target.value}:dn)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Ds.kind,onChange:zt=>ze(vs=>vs.map((dn,Ks)=>Ks===Bt?{...dn,kind:zt.target.value}:dn)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>ze(zt=>zt.filter((vs,dn)=>dn!==Bt)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(mr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Bt))]})]}),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:Ve,onChange:Ds=>ht(Ds.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:Qe,onChange:Ds=>at(Ds.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."})]}),Je.length<3&&e.jsxs("button",{type:"button",onClick:()=>ft(Ds=>[...Ds,{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(cn,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:Je.map((Ds,Bt)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Ds.name,onChange:zt=>ft(vs=>vs.map((dn,Ks)=>Ks===Bt?{...dn,name:zt.target.value}:dn)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Ds.contact,onChange:zt=>ft(vs=>vs.map((dn,Ks)=>Ks===Bt?{...dn,contact:zt.target.value}:dn)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>ft(zt=>zt.filter((vs,dn)=>dn!==Bt)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx(mr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Bt))})]})]})}]:[],{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(Ds=>e.jsxs("button",{type:"button",onClick:()=>Ie(ke===Ds.value?"":Ds.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${ke===Ds.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:Ds.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Ds.desc})]},Ds.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:Ds=>Ne(Ds.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],Ut=bs.length,Ft=AUt(d==null?void 0:d.theme),is=fGs(Ft,(d==null?void 0:d.accent_color)||null),jt=(d==null?void 0:d.cover_image_url)||Ft.defaultCover,zs=(d==null?void 0:d.headline)||"Let's stay connected",yt=(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:is,children:[e.jsxs(Dl,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${zs} — ${(o==null?void 0:o.name)||"your agent"}`}),jt&&e.jsx("meta",{property:"og:image",content:jt}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:zs}),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(Fr.img,{src:jt,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(Fr.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:zs}),yt&&e.jsx(Fr.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:yt})]})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[e.jsxs(Fr.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(pn,{className:"h-4 w-4"})})]})]}),e.jsx(Fr.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:Ut}).map((Ds,Bt)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:Bt<=A?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},Bt))}),e.jsxs(Fr.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(nK,{mode:"wait",children:e.jsxs(Fr.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(wn,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:bs[A].title})]}),bs[A].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:bs[A].subtitle})]}),bs[A].fields]},A)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[A>0?e.jsx("button",{type:"button",onClick:()=>E(Ds=>Ds-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",{}),A{if(A===0&&!R.trim()){ne.error("Please enter your first name");return}E(Ds=>Ds+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:()=>es(),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(Ct,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),A>0&&AE(Ds=>Ds+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 dK=()=>({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 EZ({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=j.useState(0),[i,l]=j.useState(!1),{trackEngagement:o}=dK(),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(kd,{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 pGs=["reserved","scheduled_for_charge","paid","payment_failed","completed"],AG=s=>!!s&&(s.access_override||pGs.includes(s.status)),Ng=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),ase=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`},OGe=(s,t="usd",n)=>`One-time payment: ${Ng(s,t)} for the ${ase(n)}`,Xst=[{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}],ise=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:[]}},gGs=(s,t)=>!s.hidden.includes(t),obt=(s,t)=>s.required.includes(t)&&!s.hidden.includes(t),th=(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,j6e=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&&rst({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||[]}}),Qst=s=>st({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}}),MUt=s=>st({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}}),Jst=()=>{const{user:s}=_s();return st({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||[]}})},ent=s=>{const{data:t=[],...n}=Jst();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},xGs=()=>{const{user:s}=_s(),t=Zt();return mt({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=>ne.error(n.message||"Could not save your answers")})},PUt=s=>{const{user:t}=_s();return st({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}})},yGs=()=>{const s=Zt();return mt({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"]})}})},vGs=(s,t)=>{const{user:n}=_s(),r=t||(n==null?void 0:n.id);return st({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}}})},bGs=s=>{const{user:t}=_s(),n=Zt();return mt({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=>ne.error(r.message||"Could not update progress")})},_Gs=s=>{const{user:t}=_s(),n=Zt();return mt({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:()=>{ne.success("Video logged — nice work"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ne.error(r.message||"Could not log the video")})},wGs=s=>{const{user:t}=_s(),n=Zt();return mt({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:()=>{ne.success("Weekly check-in saved"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ne.error(r.message||"Could not save your check-in")})},jGs=s=>{const{user:t}=_s(),n=Zt();return mt({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=>ne.error(r.message||"Could not update your RSVP")})},NGs=s=>st({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||[]}}),kGs=s=>{const t=Zt();return mt({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:()=>{ne.success("Discount code saved"),t.invalidateQueries({queryKey:["program-discount-codes"]})},onError:n=>{var r;return ne.error((r=n.message)!=null&&r.includes("duplicate")?"That code already exists for this program":n.message||"Could not save the code")}})},SGs=()=>{const s=Zt();return mt({mutationFn:async t=>{const{error:n}=await q.from("program_discount_codes").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ne.success("Discount code deleted"),s.invalidateQueries({queryKey:["program-discount-codes"]})},onError:t=>ne.error(t.message||"Could not delete the code")})},CGs=()=>mt({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}}),AGs=()=>mt({mutationFn:async s=>{const{error:t}=await q.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),EGs=s=>st({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||[]}}),TGs=s=>{const t=Zt();return mt({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:()=>{ne.success("Session saved"),t.invalidateQueries({queryKey:["admin-program-events"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ne.error(n.message||"Could not save the session")})},MGs=()=>{const s=Zt();return mt({mutationFn:async t=>{const{error:n}=await q.from("program_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ne.success("Session removed"),s.invalidateQueries({queryKey:["admin-program-events"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ne.error(t.message||"Could not remove the session")})},PGs=s=>st({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||[]}}}),IGs=s=>{const t=Zt();return mt({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:()=>{ne.success("Video saved"),t.invalidateQueries({queryKey:["admin-program-lessons"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ne.error(n.message||"Could not save the video")})},LGs=()=>{const s=Zt();return mt({mutationFn:async t=>{const{error:n}=await q.from("program_lessons").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ne.success("Video removed"),s.invalidateQueries({queryKey:["admin-program-lessons"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ne.error(t.message||"Could not remove the video")})},IUt=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},_ee=s=>!!s&&/\.(mp4|webm|mov|m4v)(\?|$)/i.test(s),LUt=[{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"}],uK="event-images",tie=s=>{if(s.file_path){const{data:t}=q.storage.from(uK).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},wee=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(uK).download(s.file_path);if(r||!n){const c=tie(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)},RUt=s=>st({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||[]}}),RGs=s=>{const t=Zt();return mt({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:()=>{ne.success("Resource saved"),t.invalidateQueries({queryKey:["admin-program-resources"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ne.error(n.message||"Could not save the resource")})},DGs=()=>{const s=Zt();return mt({mutationFn:async t=>{t.file_path&&await q.storage.from(uK).remove([t.file_path]);const{error:n}=await q.from("program_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ne.success("Resource removed"),s.invalidateQueries({queryKey:["admin-program-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ne.error(t.message||"Could not remove the resource")})},FGs=(s,t)=>st({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||[]}}),OGs=(s,t)=>{const n=Zt(),{user:r}=_s();return mt({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:()=>{ne.success("Personal resource saved"),n.invalidateQueries({queryKey:["admin-program-member-resources"]}),n.invalidateQueries({queryKey:["program-workspace"]})},onError:a=>ne.error(a.message||"Could not save the resource")})},zGs=()=>{const s=Zt();return mt({mutationFn:async t=>{t.file_path&&await q.storage.from(uK).remove([t.file_path]);const{error:n}=await q.from("program_member_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ne.success("Personal resource removed"),s.invalidateQueries({queryKey:["admin-program-member-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ne.error(t.message||"Could not remove the resource")})},BGs=s=>{const{user:t}=_s();return st({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}})},$Gs=s=>{const t=Zt(),{user:n}=_s();return mt({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=>{ne.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=>ne.error(r.message||"Could not update your notify preference")})},UGs=s=>st({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}})}}),qGs=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)},VGs=()=>{const{data:s=[]}=TUt(),{data:t=[]}=Jst(),n=new Set(t.filter(AG).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=qGs(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(By,{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($e,{variant:"secondary",children:l})]}),e.jsxs("p",{className:"mt-0.5 text-sm text-muted-foreground",children:[a.kickoff_at?`Starts ${th(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(br,{to:`/programs/${a.slug}/workspace`,children:["Open program dashboard",e.jsx(Qa,{className:"ml-1.5 h-4 w-4"})]})})]},a.id)})})},HGs={url:"/exp-agent-advantage.webp"};function GGs({className:s}){const{isMember:t,program:n,packageName:r}=bC();return!t||!((n==null?void 0:n.name)||"").toLowerCase().includes("exp")?null:e.jsxs(je,{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:HGs.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(wn,{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 WGs({className:s}){var E,I,P;const{user:t}=_s(),{isMember:n,program:r,pkg:a,packageName:i}=bC(),l=j.useMemo(()=>!n||!(a!=null&&a.includes_coaching)?!1:((r==null?void 0:r.name)||"").toLowerCase().includes("exp"),[n,a,r]),{data:o}=Ast(),c=o==null?void 0:o.id,{data:d=[]}=Est(c),{data:u=[]}=Tst(c),{data:h}=st({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,v=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],y=u.filter(R=>R.status!=="done"),b=u.length-y.length,w=(h==null?void 0:h.items)||[],S=w.filter(R=>R.done).length,A=w.length?Math.round(S/w.length*100):0;return e.jsxs(je,{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(Ii,{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(wn,{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(br,{to:"/my-coach",children:[e.jsx(vv,{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(br,{to:"/my-coach",children:[e.jsx(no,{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(fa,{className:"h-3.5 w-3.5"})," Next session"]}),v?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-2 text-lg font-semibold text-foreground",children:Js(new Date(v.scheduled_at),"EEE, MMM d")}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Js(new Date(v.scheduled_at),"h:mm a"),v.title?` · ${v.title}`:""]}),v.meeting_url&&e.jsx($,{asChild:!0,size:"sm",variant:"outline",className:"mt-3",children:e.jsx("a",{href:v.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(br,{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(Sv,{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:y.length}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"open"}),b>0&&e.jsxs($e,{variant:"secondary",className:"ml-auto",children:[b," done"]})]}),e.jsxs("ul",{className:"mt-2 space-y-1",children:[y.slice(0,3).map(R=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Dg,{className:"mt-1 h-3 w-3 shrink-0"}),e.jsx("span",{className:"line-clamp-1",children:R.title||R.description})]},R.id)),y.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(Fg,{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:[A,"%"]})]}),e.jsx(Yi,{value:A,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(Vr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}):e.jsx(Dg,{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(af,{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(br,{to:"/coaching/onboarding",children:"Start questionnaire"})})]})]})]})]})}function KGs(s){return"EST"}function ose(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=KGs();return`${n} ${r}`}function i8(s){const t=new Date,n=new Date(s),r=yyt(n,-15),a=yyt(n,30);return t>a?"ended":PS(t,{start:n,end:a})?"live":PS(t,{start:r,end:n})?"starting_soon":"upcoming"}function tnt(s){const t=i8(s);return t==="starting_soon"||t==="live"}const YGs=tnt,ZGs=({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=>tnt(f.event_date));if(i.length===0)return null;const l=i[0],o=i8(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(bb,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(ca,{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 ${ose(new Date(l.event_date))}`:`Starts at ${ose(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(Ir,{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(Yn,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function Gy(){const{user:s}=_s(),{data:t,isLoading:n}=st({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}=st({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 XGs(){var A;const{user:s}=_s(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=Gy(),a=bC(),i=a.isMember&&!!((A=a.pkg)!=null&&A.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}=st({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(le=>le.id);let W=!1;if(U.length){const{count:le}=await q.from("coaching_sessions").select("id",{count:"exact",head:!0}).in("assignment_id",U);W=(le||0)>0}const V=E.data,G=!!(V!=null&&V.avatar_url&&(V!=null&&V.phone)&&(V!=null&&V.bio)),Z=I.count||0,X=(P.count||0)>0,ae=R.count||0;return{profile:V,profileComplete:G,contactsCount:Z,contactsComplete:Z>=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 v=x.filter(E=>E.complete).length,y=x.length;return{steps:x,completedCount:v,totalCount:y,allComplete:v===y,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 QGs={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:pn,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:Yn,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:Ea,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:no,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:af,accent:"from-[#0ea5e9] to-[#38bdf8]",cta:"Book Session"}};function JGs(){var x,v;const s=Zn(),{user:t}=_s(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=XGs(),[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)||((v=t==null?void 0:t.user_metadata)==null?void 0:v.name)||"there").split(" ")[0],f=r/a*100,g=async y=>{switch(y){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")?(ne.error("Could not register — opening events page."),s("/events")):ne.success(`You're registered for ${b.title}!`);break}case"community":s("/community");break;case"coaching":s("/my-coach");break}};return e.jsxs(je,{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(mr,{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(wn,{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(Qa,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>h(y=>!y),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(xb,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(wl,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(Le,{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(y=>{const b=QGs[y.id],w=b.icon;return e.jsx("div",{className:Pt("relative rounded-xl border p-4 transition-all group",y.complete?"bg-muted/40 border-muted":"bg-card hover:shadow-md hover:border-primary/40 cursor-pointer"),onClick:()=>!y.complete&&g(y.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",y.complete?"from-emerald-500 to-emerald-600":b.accent),children:y.complete?e.jsx(Vr,{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",y.complete&&"text-muted-foreground line-through"),children:b.title})}),e.jsx("p",{className:Pt("text-xs text-muted-foreground mt-1 leading-relaxed",y.complete&&"line-through"),children:b.description}),y.id==="event"&&!y.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"]}),!y.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(y.id)},children:[b.cta," ",e.jsx(Qa,{className:"h-3 w-3 ml-1"})]})]}),y.complete&&e.jsx("span",{className:"text-xs font-medium text-emerald-600 shrink-0",children:"✓ Done"})]})},y.id)})})})]})}function eWs(s){return st({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 tWs(s,t){return st({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 sWs(s,t=4){return st({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 nWs(s){const t=Zt();return mt({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 rWs(){const s=Zt();return mt({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 aWs(s){const t=Zt();return mt({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 iWs(){const s=Zt();return mt({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 oWs(s){const t=Zt();return mt({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:Ou,pdf:Qr,link:nu,event:Ea,graphic:yd},cWs={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 uWs(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 hWs({item:s}){const t=Zn(),n=lWs[s.content_type]||nu,r=cWs[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"||!uWs(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(je,{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(Le,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs($e,{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:Js(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function mWs(){const{brokerageId:s}=_s(),t=Zn(),{data:n=[],isLoading:r}=sWs(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(wi,{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(Qa,{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(hWs,{item:a},a.id))})]})}const DUt=({className:s,variant:t="default"})=>e.jsx($e,{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"}),fWs={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"},pWs={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function gWs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function xWs(){const s=Zn(),{data:t,isLoading:n}=b$t(),{data:r,isLoading:a}=_$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(je,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(Le,{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(DUt,{})]}),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(Qa,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(je,{className:"bg-muted/30 border-dashed",children:e.jsx(Le,{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($e,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(ei,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx($e,{className:`text-[10px] px-1.5 py-0.5 ${fWs[u.status]}`,children:pWs[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:gWs(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 FUt(s=10,t){return st({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 OUt(s){return st({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 zUt(s){return st({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 BUt(s,t){return st({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 yWs(){const{user:s,brokerageId:t,isAdmin:n}=_s();Zn();const r=!!t,[a,i]=j.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=FUt(5,l()),{data:d}=OUt(s==null?void 0:s.id),{data:u}=BUt(s==null?void 0:s.id,l()),{data:h}=zUt(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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(Kl,{className:"h-4 w-4 text-yellow-500"}),f()]})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-2",children:[...Array(m?5:3)].map((x,v)=>e.jsx(xn,{className:"h-10 w-full"},v))})})]});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(je,{children:[e.jsxs(St,{className:"pb-2",children:[e.jsxs(Et,{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(Le,{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((v,y)=>{var b,w,S;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${v.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":y===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:g(y)}),e.jsx(Oa,{className:"h-6 w-6",children:e.jsx(za,{className:"text-xs",children:((w=(b=v.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=v.profile)==null?void 0:S.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:v.total_points})]},v.user_id)}),x.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(br,{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(dl,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(Di,{className:"h-4 w-4"})]})]})]})}return e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(Kl,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(Le,{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(sh,{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(Im,{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(br,{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(dl,{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(ei,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(br,{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(dl,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(Di,{className:"h-4 w-4"})]})]})})]})}const OB=()=>st({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}}),snt=()=>{const s=Zt(),{user:t}=_s();return mt({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"]}),ne.success("Lead source added")},onError:n=>{ne.error("Failed to add lead source"),console.error(n)}})},vWs=()=>{const s=Zt();return mt({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"]}),ne.success("Lead source updated")},onError:t=>{ne.error(t.message||"Failed to update lead source")}})},bWs=()=>{const s=Zt();return mt({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"]}),ne.success("Lead source removed")},onError:t=>{ne.error(t.message||"Failed to remove lead source")}})},nnt=(s,t)=>{const{user:n,isAdmin:r}=_s(),a=r&&t?t:n==null?void 0:n.id;return st({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})},rnt=s=>{const{user:t,isAdmin:n}=_s(),r=n&&s?s:t==null?void 0:t.id;return st({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})},N6e=()=>{const s=Zt(),{user:t}=_s();return mt({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"]}),ne.success("Transaction added")},onError:n=>{ne.error("Failed to add transaction"),console.error(n)}})},_Ws=()=>{const s=Zt();return mt({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"]}),ne.success("Transaction updated")},onError:t=>{ne.error("Failed to update transaction"),console.error(t)}})},wWs=()=>{const s=Zt();return mt({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"]}),ne.success("Transaction deleted")},onError:t=>{ne.error("Failed to delete transaction"),console.error(t)}})},$Ut=(s,t)=>{const{user:n,isAdmin:r}=_s(),a=r&&t?t:n==null?void 0:n.id;return st({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})},jWs=()=>{const s=Zt(),{user:t}=_s();return mt({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]}),ne.success("Goals saved")},onError:n=>{ne.error("Failed to save goals"),console.error(n)}})},k6e=()=>{const{user:s}=_s();return st({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)})},NWs=()=>{const s=Zt(),{user:t}=_s();return mt({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"]}),ne.success("Settings saved")},onError:n=>{ne.error("Failed to save settings"),console.error(n)}})},UUt=(s,t)=>{const{data:n,isLoading:r}=nnt(s,t),{data:a,isLoading:i}=rnt(t),{data:l}=k6e(),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(A=>A.transaction_type==="buyer").length,h=d.filter(A=>A.transaction_type==="seller").length,m=d.reduce((A,E)=>A+Number(E.sale_price),0),f=d.reduce((A,E)=>A+(Number(E.commission_amount)||0),0),g=d.reduce((A,E)=>{const I=Number(E.commission_amount)||0;if(!I)return A;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),A+Math.max(0,P)},0),x={};d.forEach(A=>{var I;const E=((I=A.lead_source)==null?void 0:I.name)||"Unknown";x[E]=(x[E]||0)+1});const v=Object.entries(x).map(([A,E])=>({name:A,count:E})).sort((A,E)=>E.count-A.count),y=v[0]||null,b={};d.forEach(A=>{const E=kh(A.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(A=>({month:A,count:b[A]||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:y,transactionsByMonth:S,leadSourceBreakdown:v}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},kWs=()=>{const{isAdmin:s}=_s();return st({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})},cP={recency:40,touchpoints:30,transactions:20},lbt={warm:70,cooling:40};function SWs(s){return s===null?0:s<=14?cP.recency:s<=30?cP.recency*.85:s<=60?cP.recency*.65:s<=90?cP.recency*.4:s<=180?cP.recency*.2:cP.recency*.05}function CWs(s){const t=Math.min(s/12,1);return Math.round(cP.touchpoints*t)}function AWs(s){return s?cP.transactions:0}function EWs(){return 0}function TWs(s){return s>=lbt.warm?"warm":s>=lbt.cooling?"cooling":"at-risk"}function sie(){const{data:s,isLoading:t}=L_(),{data:n}=jUt(),{data:r}=cK(365),{data:a}=rnt(),i=j.useMemo(()=>{if(!s)return[];const o=new Date,c=n8(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?ck(o,new Date(m)):null,g=d[h.id]||0,x=u.has(h.id),v=SWs(f),y=CWs(g),b=AWs(x),w=EWs(),S=Math.round(v+y+b+w),A={score:S,status:TWs(S),breakdown:{recency:Math.round(v),touchpoints:Math.round(y),transactions:Math.round(b),referrals:Math.round(w)},lastTouchDate:m,daysSinceTouch:f,touchCountLast12Months:g,hasTransaction:x};return{...h,relationshipScore:A}})},[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 MWs(s){const{contactsWithScores:t,isLoading:n}=sie(),r=j.useMemo(()=>t.find(a=>a.id===s),[t,s]);return{score:r==null?void 0:r.relationshipScore,isLoading:n}}function qUt(){const s=Zn(),{stats:t,contactsWithScores:n,isLoading:r}=sie();if(r)return e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(xn,{className:"h-5 w-40"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsx(xn,{className:"h-20 w-full"}),e.jsx(xn,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"text-lg flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Et,{className:"text-lg flex items-center gap-2",children:[e.jsx(Zl,{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(Le,{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(tC,{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 PWs=()=>{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"},IWs=()=>new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date);function LWs({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 RWs({name:s,eventsThisWeek:t=0}){const n=Zn(),{user:r}=_s(),{data:a}=Yst(),{data:i}=vUt(),l=v6e(),{hasAccess:o,hasAssignment:c}=Ezt(),{hasFeature:d}=bC(),{data:u}=st({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,v=[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(" • "),y=[{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:sh}],b=[{label:"Add Contact",icon:lc,to:"/mission-control/contacts?new=true"},...d("social")?[{label:"Create Post",icon:Hd,to:"/social-swag-2"}]:[],...d("presentations")?[{label:"Listing Presentation",icon:vb,to:"/mission-control/listing-presentations"}]:[],...o?[{label:"Book Coaching",icon:Su,to:c?"/my-coach":"/coaching"}]:[],{label:"Ask AI",icon:wn,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:IWs()}),e.jsxs("h1",{className:"mt-1 text-2xl sm:text-3xl font-bold",children:[PWs(),", ",s]}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:v?`Today: ${v}.`:"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:y.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(LWs,{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(Qa,{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 YU=24*60*60*1e3,DWs=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}},tde=s=>{const t=DWs(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,OWs=s=>s===0?"today":s===1?"tomorrow":`in ${s} days`,zWs={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}},BWs=(s=5)=>{const t=Sa(),{data:n,isLoading:r}=Yst(),{data:a,isLoading:i}=L_(),l=st({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*YU).toISOString()),q.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-90*YU).toISOString())]),x=new Set([...(m||[]).map(P=>P.contact_id),...(f||[]).map(P=>P.contact_id)]),v=new Set((g||[]).map(P=>P.contact_id)),y=P=>!x.has(P)&&!c.has(P);for(const P of u){if(!y(P.id))continue;const D=[{days:tde(P.birthday),label:"Birthday"},{days:tde(P.home_anniversary),label:"Home anniversary"},{days:tde(P.wedding_anniversary),label:"Wedding anniversary"},{days:tde(P.spouse_birthday),label:`${P.spouse_name||"Spouse"}'s birthday`}].find(O=>FWs(O.days,7));D&&d({key:`milestone-${P.id}`,contact:P,kind:"milestone",actionLabel:"Send wishes",reason:`${D.label} ${OWs(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||!y(P.contact_id))continue;const D=zWs[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||!y(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*YU;for(const P of u)y(P.id)&&(v.has(P.id)||new Date(P.created_at).getTime()y(P.id)&&!v.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}},$Ws=()=>{const s=Sa(),t=Zt();return mt({mutationFn:async n=>{const r=new Date(Date.now()+14*YU).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"})})},UWs=s=>(s||"?").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),qWs={plan:{icon:gb,tint:"var(--nav-crm)"},milestone:{icon:Rg,tint:"var(--nav-events)"},signal:{icon:sh,tint:"var(--nav-marketing)"},deal:{icon:wx,tint:"var(--nav-listings)"},new:{icon:wn,tint:"var(--nav-apps)"},cold:{icon:Zj,tint:"var(--nav-more)"}};function VWs(){const s=Zn(),{data:t,isLoading:n}=BWs(5),r=$Ws(),a=v6e(),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(ph,{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(xn,{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(Vr,{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(lc,{className:"h-3.5 w-3.5"})," Add Contact"]})]}):e.jsx(vk,{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=qWs[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:UWs(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($e,{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(HWs,{contact:d,onOpen:()=>s(`/mission-control/contacts/${d.id}`)}),e.jsxs(ry,{children:[e.jsx(ay,{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(mr,{className:"h-4 w-4"})})}),e.jsx(vx,{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 HWs({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(no,{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(pn,{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 GWs=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 WWs({events:s,registrations:t}){const n=Zn(),{data:r}=Ast(),{data:a}=st({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:YGs(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(Wc,{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(Wc,{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(bb,{className:"h-4 w-4 text-destructive"}):l.kind==="coaching"?e.jsx(af,{className:"h-4 w-4",style:{color:"hsl(var(--nav-academy))"}}):e.jsx(fa,{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":`${GWs(l.date)} · ${ose(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(Ir,{className:"h-3 w-3"})," Join"]})]})},l.id))})]})}const cbt=s=>s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${Math.round(s/1e3)}K`:`$${s}`;function KWs(){const s=Zn(),{data:t,isLoading:n}=st({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(i2,{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(xn,{className:"h-12 w-full"}),e.jsx(xn,{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:cbt(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:cbt(t.wonVolume)})," volume"]})]})]})}function YWs(){const s=Zn(),{user:t}=_s(),{hasFeature:n}=bC(),{data:r}=st({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:vb,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:gm,hue:"--nav-marketing",to:"/marketing-studio"}),i.slice(0,8)}}),a=(r||[]).filter(i=>{const l=kOt(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(ca,{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(Qa,{className:"h-4 w-4 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]},i.id))})]})}function ZWs({videos:s,kits:t,templates:n,services:r}){const a=Zn(),i=[{id:"videos",label:"Academy",icon:ef,hue:"--nav-academy",items:s,viewAll:"/academy",emptyText:"No new videos yet."},{id:"kits",label:"Resource Kits",icon:Nv,hue:"--nav-apps",items:t,viewAll:"/toolbox",emptyText:"No resource kits yet."},{id:"templates",label:"Templates",icon:$I,hue:"--nav-marketing",items:n,viewAll:"/templates",emptyText:"No new templates yet.",fit:"contain"},{id:"services",label:"Services",icon:wn,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(Qa,{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 XWs=()=>{var re;const{user:s,isAdmin:t}=_s(),n=Zn(),{hasFeature:r}=bC(),[a,i]=j.useState([]),[l,o]=j.useState([]),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,f]=j.useState([]),[g,x]=j.useState([]),[v,y]=j.useState(new Set),[b,w]=j.useState([]),[S,A]=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,ve,fe;try{const[ue,be,Ee,ke,Ie,Fe,Ne,Be,Se,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(rt=>rt.tag))||[],ze=new Set(((ce=Ee.data)==null?void 0:ce.map(rt=>rt.app_id))||[]);y(ze);const ht=(((ve=be.data)==null?void 0:ve.filter(rt=>!rt.required_tags||rt.required_tags.length===0?!0:rt.required_tags.some(Ke=>qe.includes(Ke))))||[]).sort((rt,Ke)=>rt.name==="LevelUp Members Portal"?-1:Ke.name==="LevelUp Members Portal"?1:0);i(ht.slice(0,6));const Qe=((fe=ke.data)==null?void 0:fe.filter(rt=>i8(rt.event_date)!=="ended"))||[];o(Qe.slice(0,4)),w(Ie.data||[]),d(Fe.data||[]),h(Ne.data||[]),f(Be.data||[]),x(Se.data||[]);const at=Ae.data||[];A(at.filter(rt=>rt.placement==="top")),I(at.filter(rt=>rt.placement==="between"))}catch(ue){console.error("Error loading dashboard:",ue),ne.error("Failed to load dashboard data")}finally{O(!1)}},W=async te=>{var ce,ve,fe;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 be=(ve=ue==null?void 0:ue.session)==null?void 0:ve.access_token;if(!be){J==null||J.close(),ne.error("Your session expired — please sign in again to launch this app.");return}const{data:Ee,error:ke}=await q.functions.invoke("sso-launch",{body:{app_id:te.app_id},headers:{Authorization:`Bearer ${be}`}});if(ke)throw ke;Ee!=null&&Ee.redirect_url?J&&!J.closed?(J.location.href=Ee.redirect_url,(fe=J.focus)==null||fe.call(J)):window.location.assign(Ee.redirect_url):(J==null||J.close(),ne.error("Launch link unavailable"))}catch(ue){J==null||J.close(),console.error("Error launching app:",ue),ne.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)}),Z=te=>E.filter(J=>J.section_after===te),X=(P||((re=s==null?void 0:s.user_metadata)==null?void 0:re.name)||"there").split(" ")[0],ae=Date.now()+7*24*60*60*1e3,le=l.filter(te=>new Date(te.event_date).getTime()<=ae).length;return e.jsxs(Vs,{title:"Dashboard",children:[r("learn")&&e.jsx(ZGs,{events:l,registrations:b,onNavigateToEvents:()=>n("/events")}),e.jsx(VGs,{}),e.jsx(GGs,{}),e.jsx(WGs,{}),e.jsx(RWs,{name:X,eventsThisWeek:le}),e.jsx(JGs,{}),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(VWs,{})}),r("learn")&&e.jsx(WWs,{events:l,registrations:b})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 mb-8 lg:grid-cols-3",children:[e.jsx(qUt,{}),r("deals")&&e.jsx(KWs,{}),r("learn")&&e.jsx(yWs,{})]}),e.jsx(YWs,{}),S.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(EZ,{banners:S})}),e.jsx(mWs,{}),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(ZWs,{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")}))}),Z("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(EZ,{banners:Z("academy")})}),r("listing_exchange")&&e.jsx("div",{className:"mb-10",children:e.jsx(xWs,{})}),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(Qa,{className:"h-4 w-4"})]})]}),G.length===0?e.jsx(je,{className:"bg-muted/30 border-dashed",children:e.jsx(Le,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(A0,{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=v.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(A0,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},te.id)})})]}),Z("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(EZ,{banners:Z("templates")})}),Z("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(EZ,{banners:Z("events")})}),Z("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(EZ,{banners:Z("toolbox")})})]})},QWs=[{key:"contacts",label:"Contacts",icon:Da,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:HI,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:Nv,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:fa,description:"View and upload videos"},{key:"listings",label:"Listings",icon:va,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:Fg,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:ui,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:jv,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:_x,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:vb,description:"Create and manage smart presentations"}];function JWs(){var I;const{user:s}=_s(),[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,v]=j.useState(!1),[y,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()){ne.error("Please enter the assistant's email");return}v(!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){ne.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){ne.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;ne.success(`${R.name||R.email} linked as your assistant`),l(!1),m({email:"",name:"",password:""}),w()}catch(P){console.error("Error linking assistant:",P),ne.error(P.message||"Failed to link assistant")}finally{v(!1)}return}if(!h.email.trim()||!h.name.trim()||!h.password.trim()){ne.error("Please fill in all fields");return}if(h.password.length<6){ne.error("Password must be at least 6 characters");return}v(!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;ne.success(`Assistant account created for ${h.name.trim()}`),l(!1),m({email:"",name:"",password:""}),w()}catch(P){console.error("Error adding assistant:",P),ne.error(P.message||"Failed to add assistant")}finally{v(!1)}}},A=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"})}),ne.success("Assistant removed"),c(!1),u(null),w()}catch(P){console.error("Error removing assistant:",P),ne.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),ne.error("Failed to update permissions")}finally{b(null)}};return r?e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(Le,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(Vn,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs($,{size:"sm",onClick:()=>{g("create"),l(!0)},children:[e.jsx(cn,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Le,{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($e,{variant:"secondary",className:"ml-2",children:[e.jsx(Tf,{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(qn,{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:QWs.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(jn,{checked:P.permissions[W.key]||!1,onCheckedChange:G=>E(P.id,W.key,G),disabled:y===P.id})]},W.key)})})]})]},P.id)})})})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Add Assistant"}),e.jsx(Er,{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(cn,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs($,{variant:f==="link"?"default":"outline",size:"sm",onClick:()=>g("link"),children:[e.jsx(Sd,{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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs($,{onClick:S,disabled:x,children:[x&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),f==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(fc,{open:o,onOpenChange:c,children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Remove Assistant?"}),e.jsxs(ic,{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(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:A,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function tb(s){this.content=s}tb.prototype={constructor:tb,find:function(s){for(var t=0;t>1}};tb.from=function(s){if(s instanceof tb)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new tb(t)};function VUt(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 WUt(s){return s>=55296&&s<56320}let di=class Z1{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 Z1(r,a)}cutByIndex(t,n){return t==n?Z1.empty:t==0&&n==this.content.length?this:new Z1(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 Z1(a,i)}addToStart(t){return new Z1([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new Z1(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?sde(n+1,i):sde(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 Z1.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return Z1.fromArray(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return Z1.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}};Nf.none=[];class lse 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=YUt(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(KUt(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(di.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(di.empty,0,0);function KUt(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(KUt(i.content,t-a-1,n-a-1)))}function YUt(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=YUt(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 eKs(s,t,n){if(n.openStart>s.depth)throw new lse("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new lse("Inconsistent open depths");return ZUt(s,t,n,0)}function ZUt(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 jee(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&&(i7(s.nodeAfter,r),i++));for(let o=i;oa&&BGe(s,t,a+1),l=r.depth>a&&BGe(n,r,a+1),o=[];return jee(null,s,a,o),i&&l&&t.index(a)==n.index(a)?(XUt(i,l),i7(o7(i,QUt(s,t,n,r,a+1)),o)):(i&&i7(o7(i,YEe(s,t,a+1)),o),jee(t,n,a,o),l&&i7(o7(l,YEe(n,r,a+1)),o)),jee(r,null,a,o),new di(o)}function YEe(s,t,n){let r=[];if(jee(null,s,n,r),s.depth>n){let a=BGe(s,t,n+1);i7(o7(a,YEe(s,t,n+1)),r)}return jee(t,null,n,r),new di(r)}function tKs(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(di.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class cse{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 ZEe(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 cse(n,r,i)}static resolveCached(t,n){let r=dbt.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()+")"),JUt(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=di.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=di.fromJSON(t,n.content);return t.nodeType(n.type).create(n.attrs,a,r)}};nL.prototype.text=void 0;class XEe extends nL{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):JUt(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 XEe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new XEe(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 JUt(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}function ubt(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 q7{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new aKs(t,n);if(r.next==null)return q7.empty;let a=eqt(r);r.next&&r.err("Unexpected trailing text");let i=hKs(uKs(a));return mKs(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(` `)}}q7.empty=new q7(!0);class aKs{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 eqt(s){let t=[];do t.push(iKs(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function iKs(s){let t=[];do t.push(oKs(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function oKs(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 hbt(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=hbt(s),r=n;return s.eat(",")&&(s.next!="}"?r=hbt(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function cKs(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=eqt(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=cKs(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 uKs(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 q7(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:nqt(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new nL(this,this.computeAttrs(t),di.from(n),Nf.setFrom(r))}createChecked(t=null,n,r){return n=di.from(n),this.checkContent(n),new nL(this,this.computeAttrs(t),n,Nf.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=di.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(di.empty,!0);return i?new nL(this,t,n.append(i),Nf.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 aqt(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 fKs(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 pKs{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?fKs(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class S6e{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=rqt(t,a.attrs),this.excluded=null;let i=sqt(this.attrs);this.instance=i?new Nf(this,i):null}create(t=null){return!t&&this.instance?this.instance:new Nf(this,nqt(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new S6e(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}let iqt=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=tb.from(t.nodes),n.marks=tb.from(t.marks||{}),this.nodes=fbt.compile(this.spec.nodes,this),this.marks=S6e.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]=q7.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?pbt(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==""?[]:pbt(this,l.split(" "))}this.nodeFromJSON=a=>nL.fromJSON(this,a),this.markFromJSON=a=>Nf.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 fbt){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 XEe(r,r.defaultAttrs,t,Nf.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 pbt(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 gKs(s){return s.tag!=null}function xKs(s){return s.style!=null}let Nee=class UGe{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(gKs(a))this.tags.push(a);else if(xKs(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 xbt(this,n,!1);return r.addAll(t,Nf.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new xbt(this,n,!0);return r.addAll(t,Nf.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=ybt(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=ybt(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new UGe(t,UGe.schemaRules(t)))}};const oqt={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},yKs={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},lqt={ol:!0,ul:!0},dse=1,qGe=2,kee=4;function gbt(s,t,n){return t!=null?(t?dse:0)|(t==="full"?qGe:0):s&&s.whitespace=="pre"?dse|qGe:n&~kee}class nde{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=Nf.none,this.match=i||(l&kee?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(di.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&dse)){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=di.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(di.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&&!oqt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class xbt{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=gbt(null,n.preserveWhitespace,0)|(r?kee:0);a?i=new nde(a.type,a.attrs,Nf.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new nde(null,null,Nf.none,!0,null,l):i=new nde(t.schema.topNodeType,null,Nf.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&qGe?"full":this.localPreserveWS||(a.options&dse)>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):vbt(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new nde(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|=dse)}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 vKs(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&lqt.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function bKs(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function ybt(s){let t={};for(let n in s)t[n]=s[n];return t}function vbt(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&&l3e(rde(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return typeof n=="string"?{dom:t.createTextNode(n)}:l3e(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new zB(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=bbt(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return bbt(t.marks)}}function bbt(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function rde(s){return s.document||window.document}const _bt=new WeakMap;function _Ks(s){let t=_bt.get(s);return t===void 0&&_bt.set(s,t=wKs(s)),t}function wKs(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}=l3e(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 cqt=65535,dqt=Math.pow(2,16);function jKs(s,t){return s+t*dqt}function wbt(s){return s&cqt}function NKs(s){return(s-(s&cqt))/dqt}const uqt=1,hqt=2,c3e=4,mqt=8;class VGe{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&mqt)>0}get deletedBefore(){return(this.delInfo&(uqt|c3e))>0}get deletedAfter(){return(this.delInfo&(hqt|c3e))>0}get deletedAcross(){return(this.delInfo&c3e)>0}}class Gj{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Gj.empty)return Gj.empty}recover(t){let n=0,r=wbt(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:jKs(o/3,t-c),x=t==c?hqt:t==h?uqt:c3e;return(n<0?t!=c:t!=h)&&(x|=mqt),new VGe(f,x,g)}a+=u-d}return r?t+a:new VGe(t+a,0,null)}touches(t,n){let r=0,a=wbt(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 use;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 Fy.fromReplace(t,this.from,this.to,i)}invert(){return new p4(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 pI(n.pos,r.pos,this.mark)}merge(t){return t instanceof pI&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new pI(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 pI(n.from,n.to,t.markFromJSON(n.mark))}}C1.jsonID("addMark",pI);class p4 extends C1{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(ant(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return Fy.fromReplace(t,this.from,this.to,r)}invert(){return new pI(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 p4(n.pos,r.pos,this.mark)}merge(t){return t instanceof p4&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new p4(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 p4(n.from,n.to,t.markFromJSON(n.mark))}}C1.jsonID("removeMark",p4);class gI extends C1{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Fy.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Fy.fromReplace(t,this.pos,this.pos+1,new Ki(di.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 Ev(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 Ev(n.from,n.to,n.gapFrom,n.gapTo,Ki.fromJSON(t,n.slice),n.insert,!!n.structure)}}C1.jsonID("replaceAround",Ev);function HGe(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 kKs(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 SKs(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 S6e){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 p4(l.from,l.to,l.style)))}function int(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 CKs(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function hK(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=di.from(r.node(g).copy(u)),h++):c--;let m=di.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=di.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new Ev(a,i,a,i,new Ki(r,0,0),n.length,!0))}function PKs(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)&&IKs(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),int(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 Ev(h,m,h+1,m-1,new Ki(di.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&fqt(s,l,o,i),!1}})}function fqt(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 IKs(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function LKs(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 Ev(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new Ki(di.from(l),0,0),1,!0))}function $E(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 RKs(s,t,n=1,r){let a=s.doc.resolve(t),i=di.empty,l=di.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=di.from(a.node(o).copy(i));let u=r&&r[d];l=di.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new Py(t,t,new Ki(i.append(l),n,n),!0))}function i6(s,t){let n=s.resolve(t),r=n.index();return gqt(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function DKs(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&&gqt(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 FKs(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&&int(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 Py(d,c.map(t+n,-1),Ki.empty,!0)),r===!0){let u=s.doc.resolve(d);fqt(s,u.node(),u.before(),s.steps.length)}return s}function OKs(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 A6e(s,t,n=t,r=Ki.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return yqt(a,i,r)?new Py(t,n,r):new zKs(a,i,r).fit()}function yqt(s,t,n){return!n.openStart&&!n.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),n.content)}class zKs{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=di.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=di.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 Ev(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Py(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=Nbt(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(di.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 kbt(t,-1)<=n?!1:(this.unplaced.size>1&&kbt(t,1)>r&&r++,this.unplaced=new Ki(t,n+1,r),!0)}dropNode(){let{content:t,openStart:n,openEnd:r}=this.unplaced,a=Nbt(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new Ki(oQ(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new Ki(oQ(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=v,u.push(vqt(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=lQ(this.placed,n,di.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,v=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=Z7e(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=lQ(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=lQ(this.placed,this.depth,di.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(di.empty,!0);n.childCount&&(this.placed=lQ(this.placed,this.frontier.length,n))}}function oQ(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(oQ(s.firstChild.content,t-1,n)))}function lQ(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(lQ(s.lastChild.content,t-1,n)))}function Nbt(s,t){for(let n=0;n1&&(r=r.replaceChild(0,vqt(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(di.empty,!0)))),s.copy(r)}function Z7e(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&&!BKs(n,i.content,l)?o:null}function BKs(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=$Ks(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 bqt(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(di.empty,!0))}return s}function qKs(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=OKs(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new Ki(di.from(r),0,0))}function VKs(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=_qt(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 _qt(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 _V extends C1{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 Fy.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 Fy.fromReplace(t,this.pos,this.pos+1,new Ki(di.from(a),0,n.isLeaf?0:1))}getMap(){return Gj.empty}invert(t){return new _V(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 _V(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 _V(n.pos,n.attr,n.value)}}C1.jsonID("attr",_V);class hse extends C1{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 Fy.ok(r)}getMap(){return Gj.empty}invert(t){return new hse(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 hse(n.attr,n.value)}}C1.jsonID("docAttr",hse);let EG=class extends Error{};EG=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};EG.prototype=Object.create(Error.prototype);EG.prototype.constructor=EG;EG.prototype.name="TransformError";let lnt=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new use}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new EG(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=A6e(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new Ki(di.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 UKs(this,t,n,r),this}replaceRangeWith(t,n,r){return qKs(this,t,n,r),this}deleteRange(t,n){return VKs(this,t,n),this}lift(t,n){return AKs(this,t,n),this}join(t,n=1){return FKs(this,t,n),this}wrap(t,n){return MKs(this,t,n),this}setBlockType(t,n=t,r,a=null){return PKs(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return LKs(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new _V(t,n,r)),this}setDocAttribute(t,n){return this.step(new hse(t,n)),this}addNodeMark(t,n){return this.step(new gI(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 Nf)n.isInSet(r.marks)&&this.step(new V7(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new V7(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 RKs(this,t,n,r),this}addMark(t,n,r){return kKs(this,t,n,r),this}removeMark(t,n,r){return SKs(this,t,n,r),this}clearIncompatible(t,n,r){return int(this,t,n,r),this}};const X7e=Object.create(null);class wc{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new wqt(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?fU(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):fU(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 m2(t.node(0))}static atStart(t){return fU(t,t,0,0,1)||new m2(t)}static atEnd(t){return fU(t,t,t.content.size,t.childCount,-1)||new m2(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=X7e[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 X7e)throw new RangeError("Duplicate use of selection JSON ID "+t);return X7e[t]=n,n.prototype.jsonID=t,n}getBookmark(){return El.between(this.$anchor,this.$head).getBookmark()}}wc.prototype.visible=!0;class wqt{constructor(t,n){this.$from=t,this.$to=n}}let Sbt=!1;function Cbt(s){!Sbt&&!s.parent.inlineContent&&(Sbt=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class El extends wc{constructor(t,n=t){Cbt(t),Cbt(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 wc.near(r);let a=t.resolve(n.map(this.anchor));return new El(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 El&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new E6e(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 El(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=wc.findFrom(n,r,!0)||wc.findFrom(n,-r,!0);if(i)n=i.$head;else return wc.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(wc.findFrom(t,-r,!0)||wc.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&&Tl.isSelectable(o))return Tl.create(s,n-(a<0?o.nodeSize:0))}else{let c=fU(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function Abt(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection(wc.near(s.doc.resolve(l),n))}const Ebt=1,ade=2,Tbt=4;class GKs extends lnt{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|=ade,this}ensureMarks(t){return Nf.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&ade)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~ade,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)||Nf.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(wc.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|=Tbt,this}get scrolledIntoView(){return(this.updated&Tbt)>0}}function Mbt(s,t){return!t||!s?s:s.bind(t)}class cQ{constructor(t,n,r){this.name=t,this.init=Mbt(n.init,r),this.apply=Mbt(n.apply,r)}}const WKs=[new cQ("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new cQ("selection",{init(s,t){return s.selection||wc.atStart(t.doc)},apply(s){return s.selection}}),new cQ("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new cQ("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class Q7e{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=WKs.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 cQ(r.key,r.spec.state,r))})}}class ZU{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 Q7e(t.schema,t.plugins),i=new ZU(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=nL.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=wc.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 jqt(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=jqt(a,t,{})),n[r]=a}return n}class O0{constructor(t){this.spec=t,this.props={},t.props&&jqt(t.props,this,this.props),this.key=t.key?t.key.key:Nqt("plugin")}getState(t){return t[this.key]}}const J7e=Object.create(null);function Nqt(s){return s in J7e?s+"$"+ ++J7e[s]:(J7e[s]=0,s+"$")}class A1{constructor(t="key"){this.key=Nqt(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const rb=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},TG=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let GGe=null;const SA=function(s,t,n){let r=GGe||(GGe=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},KKs=function(){GGe=null},H7=function(s,t,n,r){return n&&(Pbt(s,t,n,r,-1)||Pbt(s,t,n,r,1))},YKs=/^(img|br|input|textarea|hr)$/i;function Pbt(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:IN(s))){let l=s.parentNode;if(!l||l.nodeType!=1||nie(s)||YKs.test(s.nodeName)||s.contentEditable=="false")return!1;t=rb(s)+(a<0?0:1),s=l}else if(s.nodeType==1){let l=s.childNodes[t+(a<0?-1:0)];if(l.nodeType==1&&l.contentEditable=="false")if(!((i=l.pmViewDesc)===null||i===void 0)&&i.ignoreForSelection)t+=a;else return!1;else s=l,t=a<0?IN(s):0}else return!1}}function IN(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function ZKs(s,t){for(;;){if(s.nodeType==3&&t)return s;if(s.nodeType==1&&t>0){if(s.contentEditable=="false")return null;s=s.childNodes[t-1],t=IN(s)}else if(s.parentNode&&!nie(s))t=rb(s),s=s.parentNode;else return null}}function XKs(s,t){for(;;){if(s.nodeType==3&&t2),wN=MG||(Y4?/Mac/.test(Y4.platform):!1),Cqt=Y4?/Win/.test(Y4.platform):!1,yE=/Android \d/.test(o6),rie=!!Ibt&&"webkitFontSmoothing"in Ibt.documentElement.style,tYs=rie?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function sYs(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 Z3(s,t){return typeof s=="number"?s:s[t]}function nYs(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 Lbt(s,t,n){if(!ZGe(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(l.nodeType!=1){l=TG(l);continue}let o=l,c=o==i.body,d=c?sYs(i):nYs(o),u=0,h=0;if(t.topd.bottom-Z3(r,"bottom")&&(h=t.bottom-t.top>d.bottom-d.top?t.top+Z3(a,"top")-d.top:t.bottom-d.bottom+Z3(a,"bottom")),t.leftd.right-Z3(r,"right")&&(u=t.right-d.right+Z3(a,"right")),u||h)if(c)i.defaultView.scrollBy(u,h);else{let f=o.scrollLeft,g=o.scrollTop;h&&(o.scrollTop+=h),u&&(o.scrollLeft+=u);let x=o.scrollLeft-f,v=o.scrollTop-g;t={left:t.left-x,top:t.top-v,right:t.right-x,bottom:t.bottom-v}}let m=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(m))break;l=m=="absolute"?l.offsetParent:TG(l)}}function rYs(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:Aqt(s.dom)}}function Aqt(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=TG(r));return t}function aYs({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;Eqt(n,r==0?0:r-t)}function Eqt(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&&n.nodeType==3?oYs(n,a):!n||r&&n.nodeType==1?{node:s,offset:i}:Tqt(n,a)}function oYs(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 dnt(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(o.dom.nodeType==1&&(o.node.isBlock&&o.parent||!o.contentDOM)&&((c=o.dom.getBoundingClientRect()).width||c.height)&&(o.node.isBlock&&o.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(o.dom.nodeName)&&(!l&&c.left>r.left||c.top>r.top?a=o.posBefore:(!l&&c.right-1?a:s.docView.posFromDOM(t,n,-1)}function Mqt(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;rie&&a&&r.nodeType==1&&(d=r.childNodes[a-1]).nodeType==1&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=t.top&&a--,r==s.dom&&a==r.childNodes.length-1&&r.lastChild.nodeType==1&&t.top>r.lastChild.getBoundingClientRect().bottom?o=s.state.doc.content.size:(a==0||r.nodeType!=1||r.childNodes[a-1].nodeName!="BR")&&(o=dYs(s,r,a,t))}o==null&&(o=cYs(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function ZGe(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,TZ(VM(SA(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==IN(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return eBe(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==IN(r))){let c=r.childNodes[a-1],d=c.nodeType==3?SA(c,IN(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return TZ(VM(d,1),!1)}if(i==null&&a=0)}function TZ(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 eBe(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 Iqt(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 mYs(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return Iqt(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=Pqt(s,a.pos,1);for(let o=i.firstChild;o;o=o.nextSibling){let c;if(o.nodeType==1)c=o.getClientRects();else if(o.nodeType==3)c=SA(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 fYs=/[\u0590-\u08ac]/;function pYs(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?!fYs.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:Iqt(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(),v=g&&!f.contains(g.nodeType==1?g:g.parentNode)||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),v}):r.pos==r.start()||r.pos==r.end()}let Rbt=null,Dbt=null,Fbt=!1;function gYs(s,t,n){return Rbt==t&&Dbt==n?Fbt:(Rbt=t,Dbt=n,Fbt=n=="up"||n=="down"?mYs(s,t,n):pYs(s,t,n))}const sk=0,Obt=1,o8=2,aC=3;class aie{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=sk,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;nrb(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))a=t.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(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)&&!(l.nodeType==1?l.contains(t.nodeType==1?t:t.parentNode):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||l instanceof Rqt){a=t-i;break}i=o}if(a)return this.children[r].domFromPos(a-this.children[r].border,n);for(let i;r&&!(i=this.children[r-1]).size&&i instanceof Lqt&&i.side>=0;r--);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?rb(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=rb(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?o8:Obt,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=aC:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?o8:aC}r=l}this.dirty=o8}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?o8:Obt;n.dirty{if(!i)return a;if(i.parent)return i.parent.posBeforeChild(i)})),!n.type.spec.raw){if(l.nodeType!=1){let o=document.createElement("span");o.appendChild(l),l=o}l.hasAttribute("contenteditable")||(l.contentEditable="false"),l.classList.add("ProseMirror-widget")}super(t,[],l,null),this.widget=n,this.widget=n,i=this}matchesWidget(t){return this.dirty==sk&&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 xYs extends aie{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 aL extends aie{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=zB.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new aL(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&aC||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=aC&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=sk){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=QGe(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(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:h}=zB.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=Oqt(u,r,n),d?c=new yYs(t,n,r,a,u,h||null,m,d):n.isText?new M6e(t,n,r,a,u,m):new iL(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=>a.nodeType==1&&t.indexOf(a.parentNode)<0&&this.dom.contains(a));r?n.contentElement=r:n.getContent=()=>di.empty}}return n}matchesNode(t,n,r){return this.dirty==sk&&t.eq(this.node)&&QEe(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 bYs(this,l&&l.node,t);jYs(this.node,this.innerDeco,(d,u,h)=>{d.spec.marks?c.syncToMarks(d.spec.marks,r,t,u):d.type.side>=0&&!h&&c.syncToMarks(u==this.node.childCount?Nf.none:this.node.child(u).marks,r,t,u),c.placeWidget(d,t,a)},(d,u,h,m)=>{c.syncToMarks(d.marks,r,t,m);let f;c.findNodeMatch(d,u,h,m)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,u,h,f,t)||c.updateNextNode(d,u,h,t,m,a)||c.addNode(d,u,h,t,a),a+=d.nodeSize}),c.syncToMarks([],r,t,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==o8)&&(l&&this.protectLocalComposition(t,l),Dqt(this.contentDOM,this.children,t),MG&&NYs(this.dom))}localCompositionInfo(t,n){let{from:r,to:a}=t.state.selection;if(!(t.state.selection instanceof El)||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=kYs(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 xYs(this,i,n,a);t.input.compositionNodes.push(l),this.children=QGe(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==aC||!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=sk}updateOuterDeco(t){if(QEe(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Fqt(this.dom,this.nodeDOM,XGe(this.outerDeco,this.node,n),XGe(t,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=t}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function zbt(s,t,n,r,a){Oqt(r,t,s);let i=new iL(void 0,s,t,n,r,r,r);return i.contentDOM&&i.updateChildren(a,0),i}class M6e extends iL{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==aC||this.dirty!=sk&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=sk||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=sk,!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 M6e(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=aC)}get domAtom(){return!1}isText(t){return this.node.text==t}}class Rqt extends aie{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==sk&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class yYs extends iL{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==aC)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 Dqt(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=aL.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 aL)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 wYs(s,t){return s.type.side-t.type.side}function jYs(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 v=g;l!v.inline):o.slice();r(m,x,t.forChild(i,m),f),i=g}}function NYs(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 kYs(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 QGe(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 unt(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(T6e(n)){for(c=l;a&&!a.node;)a=a.parent;let h=a.node;if(a&&h.isAtom&&Tl.isSelectable(h)&&a.parent&&!(h.isInline&&QKs(n.focusNode,n.focusOffset,a.dom))){let m=a.posBefore;d=new Tl(l==m?o:r.resolve(m))}}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(()=>{(!zqt(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function CYs(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,rb(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&Tw&&rL<=11&&(n.disabled=!0,n.disabled=!1)}function Bqt(s,t){if(t instanceof Tl){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(Vbt(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else Vbt(s)}function Vbt(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function hnt(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||El.between(t,n,r)}function Hbt(s){return s.editable&&!s.hasFocus()?!1:$qt(s)}function $qt(s){let t=s.domSelectionRange();if(!t.anchorNode)return!1;try{return s.dom.contains(t.anchorNode.nodeType==3?t.anchorNode.parentNode:t.anchorNode)&&(s.editable||s.dom.contains(t.focusNode.nodeType==3?t.focusNode.parentNode:t.focusNode))}catch{return!1}}function AYs(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return H7(t.node,t.offset,n.anchorNode,n.anchorOffset)}function JGe(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&&wc.findFrom(i,t)}function dP(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function Gbt(s,t,n){let r=s.state.selection;if(r instanceof El)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 dP(s,new El(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=JGe(s.state,t);return a&&a instanceof Tl?dP(s,a):!1}else if(!(wN&&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?Tl.isSelectable(i)?dP(s,new Tl(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):rie?dP(s,new El(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof Tl&&r.node.isInline)return dP(s,new El(t>0?r.$to:r.$from));{let a=JGe(s.state,t);return a?dP(s,a):!1}}}function JEe(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function Cee(s,t){let n=s.pmViewDesc;return n?n.size==0&&(t<0||s.nextSibling||s.nodeName!="BR"):s.nodeType==1&&s.contentEditable=="false"}function _$(s,t){return t<0?EYs(s):TYs(s)}function EYs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(tk&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let o=n.childNodes[r-1];if(Cee(o,-1))a=n,i=--r;else if(o.nodeType==3)n=o,r=n.nodeValue.length;else break}}else{if(Uqt(n))break;{let o=n.previousSibling;for(;o&&Cee(o,-1);)a=n.parentNode,i=rb(o),o=o.previousSibling;if(o)n=o,r=JEe(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?eWe(s,n,r):a&&eWe(s,a,i)}function TYs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=JEe(n),i,l;for(;;)if(r{s.state==a&&UE(s)},50)}function Wbt(s,t){let n=s.state.doc.resolve(t);if(!(hb||Cqt)&&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 Kbt(s,t,n){let r=s.state.selection;if(r instanceof El&&!r.empty||n.indexOf("s")>-1||wN&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=JGe(s.state,t);if(l&&l instanceof Tl)return dP(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof m2?wc.near(l,t):wc.findFrom(l,t);return o?dP(s,o):!1}return!1}function Ybt(s,t){if(!(s.state.selection instanceof El))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 Zbt(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function IYs(s){if(!j1||s.state.selection.$head.parentOffset>0)return!1;let{focusNode:t,focusOffset:n}=s.domSelectionRange();if(t&&t.nodeType==1&&n==0&&t.firstChild&&t.firstChild.contentEditable=="false"){let r=t.firstChild;Zbt(s,r,"true"),setTimeout(()=>Zbt(s,r,"false"),20)}return!1}function LYs(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function RYs(s,t){let n=t.keyCode,r=LYs(t);if(n==8||wN&&n==72&&r=="c")return Ybt(s,-1)||_$(s,-1);if(n==46&&!t.shiftKey||wN&&n==68&&r=="c")return Ybt(s,1)||_$(s,1);if(n==13||n==27)return!0;if(n==37||wN&&n==66&&r=="c"){let a=n==37?Wbt(s,s.state.selection.from)=="ltr"?-1:1:-1;return Gbt(s,a,r)||_$(s,a)}else if(n==39||wN&&n==70&&r=="c"){let a=n==39?Wbt(s,s.state.selection.from)=="ltr"?1:-1:1;return Gbt(s,a,r)||_$(s,a)}else{if(n==38||wN&&n==80&&r=="c")return Kbt(s,-1,r)||_$(s,-1);if(n==40||wN&&n==78&&r=="c")return IYs(s)||Kbt(s,1,r)||_$(s,1);if(r==(wN?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function mnt(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")||zB.fromSchema(s.state.schema),o=Kqt(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=Wqt[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&&d.nodeType==1&&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 qqt(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(di.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=zB.fromSchema(f);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(x=>{let v=l.appendChild(document.createElement("p"));x&&v.appendChild(g.serializeNode(f.text(x,m)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=zYs(n),rie&&BYs(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&&m.nodeType!=1;)m=m.nextSibling;if(!m)break;l=m}if(o||(o=(s.someProp("clipboardParser")||s.someProp("domParser")||Nee.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(m){return m.nodeName=="BR"&&!m.nextSibling&&m.parentNode&&!DYs.test(m.parentNode.nodeName)?{ignore:!0}:null}})),u)o=$Ys(Xbt(o,+u[1],+u[2]),u[4]);else if(o=Ki.maxOpen(FYs(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 DYs=/^(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 FYs(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&&Hqt(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=Gqt(l[l.length-1],i.length));let u=Vqt(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return di.from(l)}return s}function Vqt(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,di.from(s));return s}function Hqt(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(di.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function Xbt(s,t,n){return tn})}return MZ.createHTML(s)}function zYs(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=Kqt(),r=n.body,a=/<([a-z][^>\s]+)/i.exec(s),i;if((i=a&&Wqt[a[1].toLowerCase()])&&(s=i.map(l=>"<"+l+">").join("")+s+i.map(l=>"").reverse().join("")),r.innerHTML=OYs(s),i)for(let l=0;l=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;try{a=di.from(c.create(r[o+1],a))}catch{break}i++,l++}return new Ki(a,i,l)}const T_={},M_={},UYs={touchstart:!0,touchmove:!0};class qYs{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 VYs(s){for(let t in T_){let n=T_[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{GYs(s,r)&&!fnt(s,r)&&(s.editable||!(r.type in M_))&&n(s,r)},UYs[t]?{passive:!0}:void 0)}j1&&s.dom.addEventListener("input",()=>null),sWe(s)}function vE(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function HYs(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 sWe(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>fnt(s,r))})}function fnt(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function GYs(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 WYs(s,t){!fnt(s,t)&&T_[t.type]&&(s.editable||!(t.type in M_))&&T_[t.type](s,t)}M_.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!Qqt(s)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(yE&&hb&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),MG&&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,VO(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||RYs(s,n)?n.preventDefault():vE(s,"key")};M_.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};M_.keypress=(s,t)=>{let n=t;if(Qqt(s)||!n.charCode||n.ctrlKey&&!n.altKey||wN&&n.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,n))){n.preventDefault();return}let r=s.state.selection;if(!(r instanceof El)||!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 iie(s){return{left:s.clientX,top:s.clientY}}function KYs(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function pnt(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 oie(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 YYs(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&Tl.isSelectable(r)?(oie(s,new Tl(n)),!0):!1}function ZYs(s,t){if(t==-1)return!1;let n=s.state.selection,r,a;n instanceof Tl&&(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(Tl.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?(oie(s,Tl.create(s.state.doc,a)),!0):!1}function XYs(s,t,n,r,a){return pnt(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?ZYs(s,n):YYs(s,n))}function QYs(s,t,n,r){return pnt(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function JYs(s,t,n,r){return pnt(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||eZs(s,n,r)}function eZs(s,t,n){if(n.button!=0)return!1;let r=Yqt(s,t,!0),a=s.state.doc;return r?(oie(s,r),r instanceof El&&a.eq(s.state.doc)&&(s.input.mouseDown=new sZs(s,r)),!0):!1}function Yqt(s,t,n){let r=s.state.doc;if(t==-1)return r.inlineContent?El.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 El.create(r,o+1,o+1+l.content.size);if(n&&Tl.isSelectable(l))return Tl.create(r,o)}return null}function gnt(s){return eTe(s)}const Zqt=wN?"metaKey":"ctrlKey";T_.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=gnt(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&KYs(n,s.input.lastClick)&&!n[Zqt]&&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(iie(n));l&&(i=="singleClick"?s.input.mouseDown=new tZs(s,l,n,!!r):(i=="doubleClick"?QYs:JYs)(s,l.pos,l.inside,n)?n.preventDefault():vE(s,"pointer"))};class Xqt{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 tZs extends Xqt{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[Zqt],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&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:d}=t.state;r.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||d instanceof Tl&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&tk&&!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()),vE(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||UE(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(iie(t))),this.updateAllowDefault(t),this.allowDefault||!n?vE(this.view,"pointer"):XYs(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||j1&&this.mightDrag&&!this.mightDrag.node.isAtom||hb&&!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)?(oie(this.view,wc.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):vE(this.view,"pointer")}move(t){this.updateAllowDefault(t),vE(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 sZs extends Xqt{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(),vE(this.view,"pointer");let n=this.view.posAtCoords(iie(t)),r=n&&Yqt(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(),gnt(s),vE(s,"pointer")};T_.touchmove=s=>{s.input.lastTouch=Date.now(),vE(s,"pointer")};T_.contextmenu=s=>gnt(s);function Qqt(s,t){return s.composing?!0:j1&&Math.abs(Date.now()-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const nZs=yE?5e3:-1;M_.compositionstart=M_.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,n=t.selection.$to;if(t.selection instanceof El&&t.selection.empty&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||hb&&Cqt&&rZs(s)))s.markCursor=s.state.storedMarks||n.marks(),eTe(s,!0),s.markCursor=null;else if(eTe(s,!t.selection.empty),tk&&t.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=s.domSelectionRange();for(let a=r.focusNode,i=r.focusOffset;a&&a.nodeType==1&&i!=0;){let l=i<0?a.lastChild:a.childNodes[i-1];if(!l)break;if(l.nodeType==3){let o=s.domSelection();o&&o.collapse(l,l.nodeValue.length);break}else a=l,i=-1}}s.input.composing=!0}Jqt(s,nZs)};function rZs(s){let{focusNode:t,focusOffset:n}=s.domSelectionRange();if(!t||t.nodeType!=1||n>=t.childNodes.length)return!1;let r=t.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}M_.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++,Jqt(s,20))};function Jqt(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>eTe(s),t))}function eVt(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=Date.now());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function aZs(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=ZKs(t.focusNode,t.focusOffset),r=XKs(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 eTe(s,t=!1){if(!(yE&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),eVt(s),t||s.docView&&s.docView.dirty){let n=unt(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 iZs(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 mse=Tw&&rL<15||MG&&tYs<604;T_.copy=M_.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=mse?null:n.clipboardData,l=r.content(),{dom:o,text:c}=mnt(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):iZs(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function oZs(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?fse(s,r.value,null,a,t):fse(s,r.textContent,r.innerHTML,a,t)},50)}function fse(s,t,n,r,a){let i=qqt(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=oZs(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 tVt(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," "):""}M_.paste=(s,t)=>{let n=t;if(s.composing&&!yE)return;let r=mse?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&fse(s,tVt(r),r.getData("text/html"),a,n)?n.preventDefault():lZs(s,n)};class sVt{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const cZs=wN?"altKey":"ctrlKey";function nVt(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[cZs]}T_.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(iie(n)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof Tl?a.to-1:a.to))){if(r&&r.mightDrag)l=Tl.create(s.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let h=s.docView.nearestDesc(n.target,!0);h&&h.node.type.spec.draggable&&h!=s.docView&&(l=Tl.create(s.state.doc,h.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=mnt(s,o);(!n.dataTransfer.files.length||!hb||Sqt>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(mse?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",mse||n.dataTransfer.setData("text/plain",d),s.dragging=new sVt(u,nVt(s,n),l)};T_.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};M_.dragover=M_.dragenter=(s,t)=>t.preventDefault();M_.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(iie(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=qqt(s,tVt(t.dataTransfer),mse?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&nVt(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?xqt(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&&Tl.isSelectable(i.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new Tl(m));else{let f=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((g,x,v,y)=>f=y),c.setSelection(hnt(s,m,c.doc.resolve(f)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}T_.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())&&UE(s)},20))};T_.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)};T_.beforeinput=(s,t)=>{if(yE&&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,VO(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 M_)T_[s]=M_[s];function pse(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 tTe{constructor(t,n){this.toDOM=t,this.spec=n||l7,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 g_(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof tTe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&pse(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class oL{constructor(t,n){this.attrs=t,this.spec=n||l7}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 g_(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==i1||t.maps.length==0?this:this.mapInner(t,n,0,0,r||l7)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=aVt(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 oL){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,l7));return jP.from(r)}forChild(t,n){if(n.isLeaf)return px.empty;let r=[];for(let a=0;an instanceof px)?t:t.reduce((n,r)=>n.concat(r instanceof px?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let v=x-g-(f-m);for(let y=0;yb+u-h)continue;let w=o[y]+u-h;f>=w?o[y+1]=m<=w?-2:-1:m>=u&&v&&(o[y]+=v,o[y+1]+=v)}h+=v}),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),v=r.maybeChild(g);if(v&&x==h&&x+v.nodeSize==f){let y=o[d+2].mapInner(n,v,u+1,s[d]+i+1,l);y!=i1?(o[d]=h,o[d+1]=f,o[d+2]=y):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=hZs(o,s,t,n,a,i,l),u=sTe(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=aVt(s,o,c+n);if(d){i=!0;let u=sTe(d,o,n+c+1,r);u!=i1&&a.push(c,c+o.nodeSize,u)}});let l=rVt(i?iVt(s):s,-n).sort(c7);for(let o=0;o0;)t++;s.splice(t,0,n)}function sBe(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=i1&&t.push(r)}),s.cursorWrapper&&t.push(px.create(s.state.doc,[s.cursorWrapper.deco])),jP.from(t)}const mZs={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},fZs=Tw&&rL<=11;class pZs{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 gZs{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new pZs,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():j1&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),fZs&&(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,mZs)),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(Hbt(this.view)){if(this.suppressingSelectionUpdates)return UE(this.view);if(Tw&&rL<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&H7(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=TG(i))n.add(i);for(let i=t.anchorNode;i;i=TG(i))if(n.has(i)){r=i;break}let a=r&&this.view.docView.nearestDesc(r);if(a&&a.ignoreMutation({type:"selection",target:r.nodeType==3?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)&&Hbt(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||hb&&(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&&h.nodeType==1;){if(h.contentEditable=="false"){u.parentNode.removeChild(u);break}h=h.firstChild}}}else if(tk&&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||vZs(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),xZs(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,bZs(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||UE(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;y--){let b=a.childNodes[y-1],w=b.pmViewDesc;if(b.nodeName=="BR"&&!w){l=y;break}if(!w||w.size)break}let m=s.state.doc,f=s.someProp("domParser")||Nee.fromSchema(s.state.schema),g=m.resolve(o),x=null,v=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:wZs(r),context:g});if(u&&u[0].pos!=null){let y=u[0].pos,b=u[1]&&u[1].pos;b==null&&(b=y),x={anchor:y+o,head:b+o}}return{doc:v,sel:x,from:o,to:c}}const wZs=s=>t=>{let n=t.pmViewDesc;if(n)return n.parseRule(s);if(t.nodeName=="BR"&&t.parentNode){if(j1&&/^(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||j1&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null},jZs=/^(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 NZs(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=unt(s,I);if(P&&!s.state.selection.eq(P)){if(hb&&yE&&s.input.lastKeyCode===13&&Date.now()-100D(s,VO(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=_Zs(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||yE)&&a.some(I=>I.nodeType==1&&!jZs.test(I.nodeName))&&(!g||g.endA>=g.endB)&&s.someProp("handleKeyDown",I=>I(s,VO(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!g)if(r&&c instanceof El&&!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=s1t(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)),Tw&&rL<=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),v=d.doc.resolveNoCache(g.endB-d.from),y=u.resolve(g.start),b=x.sameParent(v)&&x.parent.inlineContent&&y.end()>=g.endA;if((MG&&s.input.lastIOSEnter>Date.now()-225&&(!b||a.some(I=>I.nodeName=="DIV"||I.nodeName=="P"))||!b&&CZs(d.doc,x.pos,v.pos))&&s.someProp("handleKeyDown",I=>I(s,VO(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>g.start&&SZs(u,g.start,g.endA,x,v)&&s.someProp("handleKeyDown",I=>I(s,VO(8,"Backspace")))){yE&&hb&&s.domObserver.suppressSelectionUpdates();return}hb&&g.endB==g.start&&(s.input.lastChromeDelete=Date.now()),yE&&!b&&x.start()!=v.start()&&v.parentOffset==0&&x.depth==v.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==g.endA&&(g.endB-=2,v=d.doc.resolveNoCache(g.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(I){return I(s,VO(13,"Enter"))})},20));let w=g.start,S=g.endA,A=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=s1t(s,P.doc,d.sel);R&&!(hb&&s.composing&&R.empty&&(g.start!=g.endB||s.input.lastChromeDeleteUE(s),20));let I=A(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=kZs(x.parent.content.cut(x.parentOffset,v.parentOffset),y.parent.content.cut(y.parentOffset,g.endA-y.start())))){let I=A(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()==v.index()-(v.textOffset?0:1)){let I=x.parent.textBetween(x.parentOffset,v.parentOffset),P=()=>A(s.state.tr.insertText(I,w,S));s.someProp("handleTextInput",R=>R(s,w,S,I,P))||s.dispatch(P())}else s.dispatch(A());else s.dispatch(A())}function s1t(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:hnt(s,t.resolve(n.anchor),t.resolve(n.head))}function kZs(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||nBe(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 AZs(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 oVt{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 qYs,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(o1t),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=a1t(this),r1t(this),this.nodeViews=i1t(this),this.docView=zbt(this.state.doc,n1t(this),sBe(this),this.dom,this),this.domObserver=new gZs(this,(r,a,i,l)=>NZs(this,r,a,i,l)),this.domObserver.start(),VYs(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&&sWe(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(o1t),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&&(eVt(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=i1t(this);TZs(f,this.nodeViews)&&(this.nodeViews=f,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&sWe(this),this.editable=a1t(this),r1t(this);let c=sBe(this),d=n1t(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&&rYs(this);if(l){this.domObserver.stop();let f=h&&(Tw||hb)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&EZs(a.selection,t.selection);if(h){let x=hb?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=aZs(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=zbt(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())&&AYs(this)&&g.delaySelUpdate())?UE(this,f):(Bqt(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&&aYs(m)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!(!t||!this.dom.contains(t.nodeType==1?t:t.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof Tl){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&Lbt(this,n.getBoundingClientRect(),t)}else Lbt(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 uYs(this,t)}coordsAtPos(t,n=1){return Pqt(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 gYs(this,n||this.state,t)}pasteHTML(t,n){return fse(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return fse(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return mnt(this,t)}destroy(){this.docView&&(HYs(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],sBe(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,KKs())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return WYs(this,t)}domSelectionRange(){let t=this.domSelection();return t?j1&&this.root.nodeType===11&&JKs(this.dom.ownerDocument)==this.dom&&yZs(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}oVt.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function n1t(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"),[g_.node(0,s.state.doc.content.size,t)]}function r1t(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:g_.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function a1t(s){return!s.someProp("editable",t=>t(s.state)===!1)}function EZs(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 i1t(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 TZs(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 o1t(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 ML={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:"'"},nTe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},MZs=typeof navigator<"u"&&/Mac/.test(navigator.platform),PZs=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var ab=0;ab<10;ab++)ML[48+ab]=ML[96+ab]=String(ab);for(var ab=1;ab<=24;ab++)ML[ab+111]="F"+ab;for(var ab=65;ab<=90;ab++)ML[ab]=String.fromCharCode(ab+32),nTe[ab]=String.fromCharCode(ab);for(var rBe in ML)nTe.hasOwnProperty(rBe)||(nTe[rBe]=ML[rBe]);function IZs(s){var t=MZs&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||PZs&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?nTe:ML)[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 LZs=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),RZs=typeof navigator<"u"&&/Win/.test(navigator.platform);function DZs(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 lVt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const cVt=(s,t,n)=>{let r=lVt(s,n);if(!r)return!1;let a=_nt(r);if(!a){let l=r.blockRange(),o=l&&hK(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(yVt(s,a,t,-1))return!0;if(r.parent.content.size==0&&(PG(i,"end")||Tl.isSelectable(i)))for(let l=r.depth;;l--){let o=A6e(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},zZs=(s,t,n)=>{let r=lVt(s,n);if(!r)return!1;let a=_nt(r);return a?dVt(s,a,t):!1},BZs=(s,t,n)=>{let r=hVt(s,n);if(!r)return!1;let a=wnt(r);return a?dVt(s,a,t):!1};function dVt(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=A6e(s.doc,i,c,Ki.empty);if(!d||d.from!=i||d instanceof Py&&d.slice.size>=c-i)return!1;if(n){let u=s.tr.step(d);u.setSelection(El.create(u.doc,i)),n(u.scrollIntoView())}return!0}function PG(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 uVt=(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=_nt(r)}let l=i&&i.nodeBefore;return!l||!Tl.isSelectable(l)?!1:(t&&t(s.tr.setSelection(Tl.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function _nt(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 hVt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=hVt(s,n);if(!r)return!1;let a=wnt(r);if(!a)return!1;let i=a.nodeAfter;if(yVt(s,a,t,1))return!0;if(r.parent.content.size==0&&(PG(i,"start")||Tl.isSelectable(i))){let l=A6e(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 Tl,a;if(r){if(n.node.isTextblock||!i6(s.doc,n.from))return!1;a=n.from}else if(a=C6e(s.doc,n.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);r&&i.setSelection(Tl.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},UZs=(s,t)=>{let n=s.selection,r;if(n instanceof Tl){if(n.node.isTextblock||!i6(s.doc,n.to))return!1;r=n.to}else if(r=C6e(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},qZs=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&hK(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 jnt(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=jnt(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(wc.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},gVt=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof m2||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=jnt(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($E(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&hK(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)};function HZs(s){return(t,n)=>{if(t.selection instanceof Tl&&t.selection.node.isBlock){let{$from:f}=t.selection;return!f.parentOffset||!$E(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 El||t.selection instanceof m2)&&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=jnt(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=$E(r.doc,h,l.length,l);if(m||(l[0]=c?{type:c}:null,m=$E(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 GZs=HZs(),WZs=(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(Tl.create(s.doc,a))),!0)};function KZs(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||i6(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function yVt(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&KZs(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=di.empty;for(let y=l.length-1;y>=0;y--)g=di.from(l[y].create(null,g));g=di.from(a.copy(g));let x=s.tr.step(new Ev(t.pos-1,f,t.pos,f,new Ki(g,1,0),l.length,!0)),v=x.doc.resolve(f+2*l.length);v.nodeAfter&&v.nodeAfter.type==a.type&&i6(x.doc,v.pos)&&x.join(v.pos),n(x.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:wc.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),m=h&&hK(h);if(m!=null&&m>=t.depth)return n&&n(s.tr.lift(h,m).scrollIntoView()),!0;if(d&&PG(i,"start",!0)&&PG(a,"end")){let f=a,g=[];for(;g.push(f),!f.isTextblock;)f=f.lastChild;let x=i,v=1;for(;!x.isTextblock;x=x.firstChild)v++;if(f.canReplace(f.childCount,f.childCount,x.content)){if(n){let y=di.empty;for(let w=g.length-1;w>=0;w--)y=di.from(g[w].copy(y));let b=s.tr.step(new Ev(t.pos-g.length,t.pos+i.nodeSize,t.pos+v,t.pos+i.nodeSize-v,new Ki(y,g.length,0),0,!0));n(b.scrollIntoView())}return!0}}return!1}function vVt(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(El.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const YZs=vVt(-1),ZZs=vVt(1);function XZs(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&ont(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function l1t(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 ZEe(c,c,t.depth),t.endIndex=0;u--)i=di.from(n[u].type.create(n[u].attrs,i));s.step(new Ev(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?sXs(t,n,s,i):nXs(t,n,i):!0:!1}}function sXs(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?di.empty:di.from(a))))return!1;let h=i.pos,m=h+l.nodeSize;return r.step(new Ev(h-(o?1:0),m+(c?1:0),h+1,m-1,new Ki((o?di.empty:di.from(a.copy(di.empty))).append(c?di.empty:di.from(a.copy(di.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function rXs(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=di.from(d?s.create():null),h=new Ki(di.from(s.create(null,di.from(o.type.create(null,u)))),d?3:1,0),m=i.start,f=i.end;n(t.tr.step(new Ev(m-(d?3:1),f,m,f,h,1,!0)).scrollIntoView())}return!0}}function P6e(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 I6e=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 v=this.buildProps(d,n),y=f(...x)(v);return o.push(y),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:P6e({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}},aXs=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 L6e(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 bVt(s){const t=[],{nodeExtensions:n,markExtensions:r}=L6e(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 Mv(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 Jf(...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 nWe(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)=>Jf(n,r),{})}function _Vt(s){return typeof s=="function"}function wd(s,t=void 0,...n){return _Vt(s)?t?s.bind(t)(...n):s(...n):s}function iXs(s={}){return Object.keys(s).length===0&&s.constructor===Object}function oXs(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function c1t(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):oXs(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function d1t(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&iXs(n)?!1:n!=null))}function lXs(s,t){var n;const r=bVt(s),{nodeExtensions:a,markExtensions:i}=L6e(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(y=>y.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((y,b)=>{const w=Uo(b,"extendNodeSchema",h);return{...y,...w?w(d):{}}},{}),f=d1t({...m,content:wd(Uo(d,"content",h)),marks:wd(Uo(d,"marks",h)),group:wd(Uo(d,"group",h)),inline:wd(Uo(d,"inline",h)),atom:wd(Uo(d,"atom",h)),selectable:wd(Uo(d,"selectable",h)),draggable:wd(Uo(d,"draggable",h)),code:wd(Uo(d,"code",h)),whitespace:wd(Uo(d,"whitespace",h)),linebreakReplacement:wd(Uo(d,"linebreakReplacement",h)),defining:wd(Uo(d,"defining",h)),isolating:wd(Uo(d,"isolating",h)),attrs:Object.fromEntries(u.map(y=>{var b;return[y.name,{default:(b=y==null?void 0:y.attribute)===null||b===void 0?void 0:b.default}]}))}),g=wd(Uo(d,"parseHTML",h));g&&(f.parseDOM=g.map(y=>c1t(y,u)));const x=Uo(d,"renderHTML",h);x&&(f.toDOM=y=>x({node:y,HTMLAttributes:nWe(y,u)}));const v=Uo(d,"renderText",h);return v&&(f.toText=v),[d.name,f]})),c=Object.fromEntries(i.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,y)=>{const b=Uo(y,"extendMarkSchema",h);return{...v,...b?b(d):{}}},{}),f=d1t({...m,inclusive:wd(Uo(d,"inclusive",h)),excludes:wd(Uo(d,"excludes",h)),group:wd(Uo(d,"group",h)),spanning:wd(Uo(d,"spanning",h)),code:wd(Uo(d,"code",h)),attrs:Object.fromEntries(u.map(v=>{var y;return[v.name,{default:(y=v==null?void 0:v.attribute)===null||y===void 0?void 0:y.default}]}))}),g=wd(Uo(d,"parseHTML",h));g&&(f.parseDOM=g.map(v=>c1t(v,u)));const x=Uo(d,"renderHTML",h);return x&&(f.toDOM=v=>x({mark:v,HTMLAttributes:nWe(v,u)})),[d.name,f]}));return new iqt({topNode:l,nodes:o,marks:c})}function iBe(s,t){return t.nodes[s]||t.marks[s]||null}function u1t(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function knt(s,t){const n=zB.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const cXs=(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 Snt(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class R6e{constructor(t){this.find=t.find,this.handler=t.handler}}const dXs=(s,t)=>{if(Snt(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 ide(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=cXs(d)+i;return l.forEach(m=>{if(u)return;const f=dXs(h,m.find);if(!f)return;const g=c.state.tr,x=P6e({state:c.state,transaction:g}),v={from:r-(f[0].length-i.length),to:a},{commands:y,chain:b,can:w}=new I6e({editor:n,state:x});m.handler({state:x,range:v,match:f,commands:y,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 uXs(s){const{editor:t,rules:n}=s,r=new O0({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=knt(di.from(u),l.schema);const{from:h}=c,m=h+u.length;ide({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 ide({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&ide({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?ide({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function hXs(s){return Object.prototype.toString.call(s).slice(8,-1)}function ode(s){return hXs(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function D6e(s,t){const n={...s};return ode(s)&&ode(t)&&Object.keys(t).forEach(r=>{ode(t[r])&&ode(s[r])?n[r]=D6e(s[r],t[r]):n[r]=t[r]}),n}class fC{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=wd(Uo(this,"addOptions",{name:this.name}))),this.storage=wd(Uo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new fC(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>D6e(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new fC(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=wd(Uo(n,"addOptions",{name:n.name})),n.storage=wd(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 mXs(s){return typeof s=="number"}class wVt{constructor(t){this.find=t.find,this.handler=t.handler}}const fXs=(s,t,n)=>{if(Snt(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 pXs(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new I6e({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),v=Math.min(a,g+f.content.size),y=f.textBetween(x-g,v-g,void 0,"");fXs(y,i.find,l).forEach(w=>{if(w.index===void 0)return;const S=x+w.index+1,A=S+w[0].length,E={from:n.tr.mapping.map(S),to:n.tr.mapping.map(A)},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 lde=null;const gXs=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 xXs(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,v=P6e({state:u,transaction:x});if(!(!pXs({editor:t,state:v,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 O0({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&&(lde=t)},f=()=>{lde&&(lde=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=lde;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,v=g.getMeta("uiEvent")==="drop"&&!i,y=g.getMeta("applyPasteRules"),b=!!y;if(!x&&!v&&!b)return;if(b){let{text:A}=y;typeof A=="string"?A=A:A=knt(di.from(A),f.schema);const{from:E}=y,I=E+A.length,P=gXs(A);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(!(!mXs(w)||!S||w===S.b))return c({rule:u,state:f,from:w,to:S,pasteEvt:l})}}))}function yXs(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class XU{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=XU.resolve(t),this.schema=lXs(this.extensions,n),this.setupExtensions()}static resolve(t){const n=XU.sort(XU.flatten(t)),r=yXs(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:iBe(n.name,this.schema)},a=Uo(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=XU.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:iBe(l.name,this.schema)},c=[],d=Uo(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&Uo(l,"exitable",o)&&(u.ArrowRight=()=>fC.handleExit({editor:t,mark:l})),d){const x=Object.fromEntries(Object.entries(d()).map(([v,y])=>[v,()=>y({editor:t})]));u={...u,...x}}const h=OZs(u);c.push(h);const m=Uo(l,"addInputRules",o);u1t(l,t.options.enableInputRules)&&m&&r.push(...m());const f=Uo(l,"addPasteRules",o);u1t(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[uXs({editor:t,rules:r}),...xXs({editor:t,rules:a}),...i]}get attributes(){return bVt(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=L6e(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:Mv(r.name,this.schema)},l=Uo(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,m)=>{const f=nWe(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:iBe(t.name,this.schema)};t.type==="mark"&&(!((n=wd(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 Sb{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=wd(Uo(this,"addOptions",{name:this.name}))),this.storage=wd(Uo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new Sb(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>D6e(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new Sb({...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=wd(Uo(n,"addOptions",{name:n.name})),n.storage=wd(Uo(n,"addStorage",{name:n.name,options:n.options})),n}}function jVt(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 NVt(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const vXs=Sb.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new O0({key:new A1("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=NVt(n);return jVt(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),bXs=()=>({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),_Xs=(s=!1)=>({commands:t})=>t.setContent("",s),wXs=()=>({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=hK(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},jXs=s=>t=>s(t),NXs=()=>({state:s,dispatch:t})=>gVt(s,t),kXs=(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 El(r.doc.resolve(Math.max(l-1,0)))),!0},SXs=()=>({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},CXs=s=>({tr:t,state:n,dispatch:r})=>{const a=Mv(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},AXs=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},EXs=()=>({state:s,dispatch:t})=>bnt(s,t),TXs=()=>({commands:s})=>s.keyboardShortcut("Enter"),MXs=()=>({state:s,dispatch:t})=>VZs(s,t);function rTe(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:Snt(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function kVt(s,t,n={}){return s.find(r=>r.type===t&&rTe(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function h1t(s,t,n={}){return!!kVt(s,t,n)}function Cnt(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),!kVt([...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&&h1t([...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=l6(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=Cnt(c,i,t);if(h&&h.from<=d&&h.to>=u){const m=El.create(l,h.from,h.to);n.setSelection(m)}}return!0},IXs=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=()=>{(aTe()||m1t())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),LXs()&&!aTe()&&!m1t()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!SVt(n.state.selection))return l(),!0;const o=CVt(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},DXs=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),FXs=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),AVt=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&&AVt(r)}return s};function cde(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return AVt(n)}function gse(s,t,n){if(s instanceof nL||s instanceof di)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 di.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),gse("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new iqt({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?Nee.fromSchema(c).parseSlice(cde(s),n.parseOptions):Nee.fromSchema(c).parse(cde(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=Nee.fromSchema(t);return n.slice?i.parseSlice(cde(s),n.parseOptions).content:i.parse(cde(s),n.parseOptions)}return gse("",t,n)}function OXs(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection(wc.near(s.doc.resolve(l),n))}const zXs=s=>!("type"in s),BXs=(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=v=>{i.emit("contentError",{editor:i,error:v,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{gse(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(v){c(v)}try{o=gse(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=n.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(v){return c(v),!1}let{from:u,to:h}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},m=!0,f=!0;if((zXs(o)?o:[o]).forEach(v=>{v.check(),m=m?v.isText&&v.marks.length===0:!1,f=f?v.isBlock:!1}),u===h&&f){const{parent:v}=r.doc.resolve(u);v.isTextblock&&!v.type.spec.code&&!v.childCount&&(u-=1,h+=1)}let x;if(m){if(Array.isArray(t))x=t.map(v=>v.text||"").join("");else if(t instanceof di){let v="";t.forEach(y=>{y.text&&(v+=y.text)}),x=v}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&&OXs(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},$Xs=()=>({state:s,dispatch:t})=>$Zs(s,t),UXs=()=>({state:s,dispatch:t})=>UZs(s,t),qXs=()=>({state:s,dispatch:t})=>cVt(s,t),VXs=()=>({state:s,dispatch:t})=>mVt(s,t),HXs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=C6e(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},GXs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=C6e(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},WXs=()=>({state:s,dispatch:t})=>zZs(s,t),KXs=()=>({state:s,dispatch:t})=>BZs(s,t);function EVt(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function YXs(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=YXs(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 xse(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?Mv(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=>rTe(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,m)=>h+m.to-m.from,0)>=c}const XXs=(s,t={})=>({state:n,dispatch:r})=>{const a=Mv(s,n.schema);return xse(n,a,t)?qZs(n,r):!1},QXs=()=>({state:s,dispatch:t})=>xVt(s,t),JXs=s=>({state:t,dispatch:n})=>{const r=Mv(s,t.schema);return tXs(r)(t,n)},eQs=()=>({state:s,dispatch:t})=>pVt(s,t);function F6e(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function f1t(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 tQs=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=F6e(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Mv(s,r.schema)),o==="mark"&&(l=l6(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,f1t(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(f1t(h.attrs,t)))})})}),!0):!1},sQs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),nQs=()=>({tr:s,dispatch:t})=>{if(t){const n=new m2(s.doc);s.setSelection(n)}return!0},rQs=()=>({state:s,dispatch:t})=>uVt(s,t),aQs=()=>({state:s,dispatch:t})=>fVt(s,t),iQs=()=>({state:s,dispatch:t})=>WZs(s,t),oQs=()=>({state:s,dispatch:t})=>ZZs(s,t),lQs=()=>({state:s,dispatch:t})=>YZs(s,t);function rWe(s,t,n={},r={}){return gse(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const cQs=(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=rWe(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 TVt(s,t){const n=l6(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 lnt(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function uQs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function MVt(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 Ant(s){return t=>MVt(t.$from,s)}function mQs(s,t){const n={from:0,to:s.content.size};return jVt(s,n,t)}function fQs(s,t){const n=Mv(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 PVt(s,t){const n=F6e(typeof t=="string"?t:t.name,s.schema);return n==="node"?fQs(s,t):n==="mark"?TVt(s,t):{}}function pQs(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 gQs(s){const t=pQs(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 xQs(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}})})}),gQs(r)}function Ent(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=Cnt(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 d3e(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 aWe(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?l6(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>rTe(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,v)=>{if(!x.isText&&!x.marks.length)return;const y=Math.max(f,v),b=Math.min(g,v+x.nodeSize),w=b-y;l+=w,o.push(...x.marks.map(S=>({mark:S,from:y,to:b})))})}),l===0)return!1;const c=o.filter(h=>i?i.name===h.mark.type.name:!0).filter(h=>rTe(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 yQs(s,t,n={}){if(!t)return xse(s,null,n)||aWe(s,null,n);const r=F6e(t,s.schema);return r==="node"?xse(s,t,n):r==="mark"?aWe(s,t,n):!1}function p1t(s,t){const{nodeExtensions:n}=L6e(t),r=n.find(l=>l.name===s);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},i=wd(Uo(r,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function Tnt(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&&(Tnt(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function vQs(s){return s instanceof Tl}function bQs(s,t,n){var r;const{selection:a}=t;let i=null;if(SVt(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 _Qs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=l6(s,r.schema);if(a)if(l){const d=TVt(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(y=>y.type===c)?m.marks.forEach(y=>{c===y.type&&n.addMark(g,x,c.create({...y.attrs,...t}))}):n.addMark(g,x,c.create(t))})});return bQs(r,n,c)},wQs=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),jQs=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=Mv(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})=>l1t(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>l1t(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},NQs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=c8(s,0,r.content.size),i=Tl.create(r,a);t.setSelection(i)}return!0},kQs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=El.atStart(r).from,o=El.atEnd(r).to,c=c8(a,l,o),d=c8(i,l,o),u=El.create(r,c,d);t.setSelection(u)}return!0},SQs=s=>({state:t,dispatch:n})=>{const r=Mv(s,t.schema);return rXs(r)(t,n)};function g1t(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 CQs=({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=d3e(d,o.node().type.name,o.node().attrs);if(i instanceof Tl&&i.node.isBlock)return!o.parentOffset||!$E(l,o.pos)?!1:(r&&(s&&g1t(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:uQs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let f=h&&m?[{type:m,attrs:u}]:void 0,g=$E(t.doc,t.mapping.map(o.pos),1,f);if(!f&&!g&&$E(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 El&&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()),v=t.doc.resolve(x);o.node(-1).canReplaceWith(v.index(),v.index()+1,m)&&t.setNodeMarkup(t.mapping.map(o.before()),m)}s&&g1t(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return g},AQs=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=Mv(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 y=di.empty;const b=c.index(-1)?1:c.index(-2)?2:3;for(let P=c.depth-b;P>=c.depth-3;P-=1)y=di.from(c.node(P).copy(y));const w=c.indexAfter(-1){if(I>-1)return!1;P.isTextblock&&P.content.size===0&&(I=R+1)}),I>-1&&n.setSelection(El.near(n.doc.resolve(I))),n.scrollIntoView()}return!0}const f=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,g={...d3e(m,h.type.name,h.attrs),...t},x={...d3e(m,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const v=f?[{type:o,attrs:g},{type:f,attrs:x}]:[{type:o,attrs:g}];if(!$E(n.doc,c.pos,2))return!1;if(a){const{selection:y,storedMarks:b}=r,{splittableMarks:w}=i.extensionManager,S=b||y.$to.parentOffset&&y.$from.marks();if(n.split(c.pos,2,v).scrollIntoView(),!S||!a)return!0;const A=S.filter(E=>w.includes(E.type.name));n.ensureMarks(A)}return!0},oBe=(s,t)=>{const n=Ant(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)&&i6(s.doc,n.pos)&&s.join(n.pos),!0},lBe=(s,t)=>{const n=Ant(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)&&i6(s.doc,r)&&s.join(r),!0},EQs=(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=Mv(s,l.schema),g=Mv(t,l.schema),{selection:x,storedMarks:v}=l,{$from:y,$to:b}=x,w=y.blockRange(b),S=v||x.$to.parentOffset&&x.$from.marks();if(!w)return!1;const A=Ant(E=>p1t(E.type.name,h))(x);if(w.depth>=1&&A&&w.depth-A.depth<=1){if(A.node.type===f)return d.liftListItem(g);if(p1t(A.node.type.name,h)&&f.validContent(A.node.content)&&o)return c().command(()=>(i.setNodeMarkup(A.pos,f),!0)).command(()=>oBe(i,f)).command(()=>lBe(i,f)).run()}return!n||!S||!o?c().command(()=>u().wrapInList(f,r)?!0:d.clearNodes()).wrapInList(f,r).command(()=>oBe(i,f)).command(()=>lBe(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(()=>oBe(i,f)).command(()=>lBe(i,f)).run()},TQs=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=l6(s,r.schema);return aWe(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},MQs=(s,t,n={})=>({state:r,commands:a})=>{const i=Mv(s,r.schema),l=Mv(t,r.schema),o=xse(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})},PQs=(s,t={})=>({state:n,commands:r})=>{const a=Mv(s,n.schema);return xse(n,a,t)?r.lift(a):r.wrapIn(a,t)},IQs=()=>({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},LQs=()=>({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},RQs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=l6(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(v=>v.type===c))===null||i===void 0?void 0:i.attrs,x=Cnt(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},DQs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=F6e(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Mv(s,r.schema)),o==="mark"&&(l=l6(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,v)=>{i&&i===x.type&&(f=Math.max(v,d),g=Math.min(v+x.nodeSize,u),h=v,m=x)}):r.doc.nodesBetween(d,u,(x,v)=>{v=d&&v<=u&&(i&&i===x.type&&n.setNodeMarkup(v,void 0,{...x.attrs,...t}),l&&x.marks.length&&x.marks.forEach(y=>{if(l===y.type){const b=Math.max(v,d),w=Math.min(v+x.nodeSize,u);n.addMark(b,w,l.create({...y.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},FQs=(s,t={})=>({state:n,dispatch:r})=>{const a=Mv(s,n.schema);return XZs(a,t)(n,r)},OQs=(s,t={})=>({state:n,dispatch:r})=>{const a=Mv(s,n.schema);return QZs(a,t)(n,r)};var zQs=Object.freeze({__proto__:null,blur:bXs,clearContent:_Xs,clearNodes:wXs,command:jXs,createParagraphNear:NXs,cut:kXs,deleteCurrentNode:SXs,deleteNode:CXs,deleteRange:AXs,deleteSelection:EXs,enter:TXs,exitCode:MXs,extendMarkRange:PXs,first:IXs,focus:RXs,forEach:DXs,insertContent:FXs,insertContentAt:BXs,joinBackward:qXs,joinDown:UXs,joinForward:VXs,joinItemBackward:HXs,joinItemForward:GXs,joinTextblockBackward:WXs,joinTextblockForward:KXs,joinUp:$Xs,keyboardShortcut:ZXs,lift:XXs,liftEmptyBlock:QXs,liftListItem:JXs,newlineInCode:eQs,resetAttributes:tQs,scrollIntoView:sQs,selectAll:nQs,selectNodeBackward:rQs,selectNodeForward:aQs,selectParentNode:iQs,selectTextblockEnd:oQs,selectTextblockStart:lQs,setContent:cQs,setMark:_Qs,setMeta:wQs,setNode:jQs,setNodeSelection:NQs,setTextSelection:kQs,sinkListItem:SQs,splitBlock:CQs,splitListItem:AQs,toggleList:EQs,toggleMark:TQs,toggleNode:MQs,toggleWrap:PQs,undoInputRule:IQs,unsetAllMarks:LQs,unsetMark:RQs,updateAttributes:DQs,wrapIn:FQs,wrapInList:OQs});const BQs=Sb.create({name:"commands",addCommands(){return{...zQs}}}),$Qs=Sb.create({name:"drop",addProseMirrorPlugins(){return[new O0({key:new A1("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),UQs=Sb.create({name:"editable",addProseMirrorPlugins(){return[new O0({key:new A1("editable"),props:{editable:()=>this.editor.options.editable}})]}}),qQs=new A1("focusEvents"),VQs=Sb.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new O0({key:qQs,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}}}})]}}),HQs=Sb.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,v=h.pos-h.parentOffset,y=x&&g.parent.childCount===1?v===h.pos:wc.atStart(d).from===m;return!u||!f.type.isTextblock||f.textContent.length||!y||y&&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 aTe()||EVt()?i:a},addProseMirrorPlugins(){return[new O0({key:new A1("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=wc.atStart(t.doc).from,d=wc.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!Tnt(n.doc))return;const m=n.tr,f=P6e({state:n,transaction:m}),{commands:g}=new I6e({editor:this.editor,state:f});if(g.clearNodes(),!!m.steps.length)return m}})]}}),GQs=Sb.create({name:"paste",addProseMirrorPlugins(){return[new O0({key:new A1("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),WQs=Sb.create({name:"tabindex",addProseMirrorPlugins(){return[new O0({key:new A1("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class HO{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 HO(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 HO(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 HO(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 HO(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new HO(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 KQs=`.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 YQs(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 ZQs extends aXs{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=YQs(KQs,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=_Vt(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?[UQs,vXs.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),BQs,VQs,HQs,WQs,$Qs,GQs].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 XU(a,this)}createCommandManager(){this.commandManager=new I6e({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=rWe(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=rWe(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=CVt(n,this.options.autofocus);this.view=new oVt(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:ZU.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 PVt(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return yQs(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return knt(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return mQs(this.state.doc,{blockSeparator:n,textSerializers:{...NVt(this.schema),...r}})}get isEmpty(){return Tnt(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 HO(n,this)}get $doc(){return this.$pos(0)}}function IG(s){return new R6e({find:s.find,handler:({state:t,range:n,match:r})=>{const a=wd(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(Ent(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 IVt(s){return new R6e({find:s.find,handler:({state:t,range:n,match:r})=>{const a=wd(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 iWe(s){return new R6e({find:s.find,handler:({state:t,range:n,match:r})=>{const a=t.doc.resolve(n.from),i=wd(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 yse(s){return new R6e({find:s.find,handler:({state:t,range:n,match:r,chain:a})=>{const i=wd(s.getAttributes,void 0,r)||{},l=t.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&ont(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(v=>f.includes(v.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&&i6(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let Pv=class oWe{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=wd(Uo(this,"addOptions",{name:this.name}))),this.storage=wd(Uo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new oWe(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>D6e(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new oWe(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=wd(Uo(n,"addOptions",{name:n.name})),n.storage=wd(Uo(n,"addStorage",{name:n.name,options:n.options})),n}};function G7(s){return new wVt({find:s.find,handler:({state:t,range:n,match:r,pasteEvent:a})=>{const i=wd(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(Ent(n.from,n.to,t.doc).filter(g=>g.mark.type.excluded.find(v=>v===s.type&&v!==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 XQs(s,t){const{selection:n}=s,{$from:r}=n;if(n instanceof Tl){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 QQs(s){return new wVt({find:s.find,handler({match:t,chain:n,range:r,pasteEvent:a}){const i=wd(s.getAttributes,void 0,t,a),l=wd(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 JQs(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var LVt={exports:{}},cBe={};/** * @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 x1t;function eJs(){if(x1t)return cBe;x1t=1;var s=Kt;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,v=g[1];return i(function(){x.value=f,x.getSnapshot=m,c(x)&&v({inst:x})},[h,f,m]),a(function(){return c(x)&&v({inst:x}),h(function(){c(x)&&v({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 cBe.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,cBe}LVt.exports=eJs();var Mnt=LVt.exports;const tJs=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},sJs=({contentComponent:s})=>{const t=Mnt.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return Kt.createElement(Kt.Fragment,null,Object.values(t))};function nJs(){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]:I6t.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 rJs extends Kt.Component{constructor(t){var n;super(t),this.editorContentRef=Kt.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=nJs(),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 Kt.createElement(Kt.Fragment,null,Kt.createElement("div",{ref:tJs(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&Kt.createElement(sJs,{contentComponent:t.contentComponent}))}}const aJs=j.forwardRef((s,t)=>{const n=Kt.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return Kt.createElement(rJs,{key:n,innerRef:t,...s})}),O6e=Kt.memo(aJs);var iJs=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},oJs=JQs(iJs),RVt={exports:{}},dBe={};/** * @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 y1t;function lJs(){if(y1t)return dBe;y1t=1;var s=Kt,t=Mnt;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 dBe.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 y(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,A=h===void 0?null:h;return[function(){return y(u())},A===null?void 0:function(){return y(A())}]},[u,h,m,f]);var v=a(d,g[0],g[1]);return l(function(){x.hasValue=!0,x.value=v},[v]),c(v),v},dBe}RVt.exports=lJs();var cJs=RVt.exports;const dJs=typeof window<"u"?j.useLayoutEffect:j.useEffect;class uJs{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 hJs(s){var t;const[n]=j.useState(()=>new uJs(s.editor)),r=cJs.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:oJs);return dJs(()=>n.watch(s.editor),[s.editor,n]),j.useDebugValue(r),r}const mJs=!1,lWe=typeof window>"u",fJs=lWe||!!(typeof window<"u"&&window.next);class Pnt{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?lWe||fJs?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 ZQs(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?Pnt.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 z6e(s={},t=[]){const n=j.useRef(s);n.current=s;const[r]=j.useState(()=>new Pnt(n)),a=Mnt.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return j.useDebugValue(a),j.useEffect(r.onRender(t)),hJs({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const pJs=j.createContext({editor:null});pJs.Consumer;const gJs=j.createContext({onDragStart:void 0}),xJs=()=>j.useContext(gJs);Kt.forwardRef((s,t)=>{const{onDragStart:n}=xJs(),r=s.as||"div";return Kt.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const yJs=/^\s*>\s$/,vJs=Pv.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",Jf(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[yse({find:yJs,type:this.type})]}}),bJs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,_Js=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,wJs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,jJs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,NJs=fC.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",Jf(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[IG({find:bJs,type:this.type}),IG({find:wJs,type:this.type})]},addPasteRules(){return[G7({find:_Js,type:this.type}),G7({find:jJs,type:this.type})]}}),kJs="listItem",v1t="textStyle",b1t=/^\s*([-+*])\s$/,SJs=Pv.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",Jf(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(kJs,this.editor.getAttributes(v1t)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=yse({find:b1t,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=yse({find:b1t,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(v1t),editor:this.editor})),[s]}}),CJs=/(^|[^`])`([^`]+)`(?!`)/,AJs=/(^|[^`])`([^`]+)`(?!`)/g,EJs=fC.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",Jf(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[IG({find:CJs,type:this.type})]},addPasteRules(){return[G7({find:AJs,type:this.type})]}}),TJs=/^```([a-z]+)?[\s\n]$/,MJs=/^~~~([a-z]+)?[\s\n]$/,PJs=Pv.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",Jf(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(wc.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[iWe({find:TJs,type:this.type,getAttributes:s=>({language:s[1]})}),iWe({find:MJs,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new O0({key:new A1("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(El.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),IJs=Pv.create({name:"doc",topNode:!0,content:"block+"});function LJs(s={}){return new O0({view(t){return new RJs(t,s)}})}class RJs{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 v=this.width/2*o;r={left:g.left,right:g.right,top:x-v,bottom:x+v}}}}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=xqt(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 DJs=Sb.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[LJs(this.options)]}});class gx extends wc{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return gx.valid(r)?new gx(r):wc.near(r)}content(){return Ki.empty}eq(t){return t instanceof gx&&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 gx(t.resolve(n.pos))}getBookmark(){return new Int(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!FJs(t)||!OJs(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&&gx.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(gx.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!Tl.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(gx.valid(o))return o}return null}}}gx.prototype.visible=!1;gx.findFrom=gx.findGapCursorFrom;wc.jsonID("gapcursor",gx);class Int{constructor(t){this.pos=t}map(t){return new Int(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return gx.valid(n)?new gx(n):wc.near(n)}}function DVt(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function FJs(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||DVt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function OJs(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||DVt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function zJs(){return new O0({props:{decorations:qJs,createSelectionBetween(s,t,n){return t.pos==n.pos&&gx.valid(n)?new gx(n):null},handleClick:$Js,handleKeyDown:BJs,handleDOMEvents:{beforeinput:UJs}}})}const BJs=vnt({ArrowLeft:dde("horiz",-1),ArrowRight:dde("horiz",1),ArrowUp:dde("vert",-1),ArrowDown:dde("vert",1)});function dde(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 El){if(!i.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=r.doc.resolve(t>0?o.after():o.before())}let d=gx.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new gx(d))),!0):!1}}function $Js(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!gx.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&Tl.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new gx(r))),!0)}function UJs(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof gx))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=di.empty;for(let l=r.length-1;l>=0;l--)a=di.from(r[l].createAndFill(null,a));let i=s.state.tr.replace(n.pos,n.pos,new Ki(a,0,0));return i.setSelection(El.near(i.doc.resolve(n.pos+1))),s.dispatch(i),!1}function qJs(s){if(!(s.selection instanceof gx))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",px.create(s.doc,[g_.widget(s.selection.head,t,{key:"gapcursor"})])}const VJs=Sb.create({name:"gapCursor",addProseMirrorPlugins(){return[zJs()]},extendNodeSchema(s){var t;const n={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=wd(Uo(s,"allowGapCursor",n)))!==null&&t!==void 0?t:null}}}),HJs=Pv.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",Jf(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()}}}),GJs=Pv.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]}`,Jf(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=>iWe({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var iTe=200,Tv=function(){};Tv.prototype.append=function(t){return t.length?(t=Tv.from(t),!this.length&&t||t.length=n?Tv.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};Tv.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};Tv.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)};Tv.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};Tv.from=function(t){return t instanceof Tv?t:t&&t.length?new FVt(t):Tv.empty};var FVt=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<=iTe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=iTe)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}(Tv);Tv.empty=new FVt([]);var WJs=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}(Tv);const KJs=500;class BS{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 _M(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 _M(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 BS(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;uZJs&&(o=YJs(o,d),l-=d),new BS(o.append(i),l)}remapping(t,n){let r=new use;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 BS(this.items.append(t.map(n=>new _M(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]),v=m.selection&&m.selection.map(i.slice(c+1,f));v&&o++,r.push(new _M(g,x,v))}else r.push(new _M(g))},a);let d=[];for(let m=n;mKJs&&(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 _M(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 BS(Tv.from(a.reverse()),i)}}BS.empty=new BS(Tv.empty,0);function YJs(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let _M=class OVt{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 OVt(n.getMap().invert(),n,this.selection)}}};class uP{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const ZJs=20;function XJs(s,t,n,r){let a=n.getMeta(d7),i;if(a)return a.historyState;n.getMeta(een)&&(s=new uP(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(d7))return l.getMeta(d7).redo?new uP(s.done.addTransform(n,void 0,r,u3e(t)),s.undone,_1t(n.mapping.maps),s.prevTime,s.prevComposition):new uP(s.done,s.undone.addTransform(n,void 0,r,u3e(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||!QJs(n,s.prevRanges)),d=l?uBe(s.prevRanges,n.mapping):_1t(n.mapping.maps);return new uP(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,u3e(t)),BS.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new uP(s.done.rebased(n,i),s.undone.rebased(n,i),uBe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new uP(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),uBe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function QJs(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 _1t(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 uBe(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=d7.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=JJs(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const BVt=zVt(!1,!0),$Vt=zVt(!0,!0),sen=Sb.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>BVt(s,t),redo:()=>({state:s,dispatch:t})=>$Vt(s,t)}},addProseMirrorPlugins(){return[ten(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()}}}),nen=Pv.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",Jf(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!XQs(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}):vQs(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(El.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(Tl.create(l.doc,d.pos)):l.setSelection(El.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(El.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[IVt({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),ren=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,aen=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,ien=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,oen=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,len=fC.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",Jf(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[IG({find:ren,type:this.type}),IG({find:ien,type:this.type})]},addPasteRules(){return[G7({find:aen,type:this.type}),G7({find:oen,type:this.type})]}}),cen=Pv.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",Jf(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",j1t="textStyle",N1t=/^(\d+)\.\s$/,uen=Pv.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",Jf(this.options.HTMLAttributes,n),0]:["ol",Jf(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(j1t)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=yse({find:N1t,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=yse({find:N1t,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(j1t)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),hen=Pv.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",Jf(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),men=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,fen=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,pen=fC.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",Jf(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[IG({find:men,type:this.type})]},addPasteRules(){return[G7({find:fen,type:this.type})]}}),gen=Pv.create({name:"text",group:"inline"}),B6e=Sb.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(NJs.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(vJs.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(SJs.configure(this.options.bulletList)),this.options.code!==!1&&s.push(EJs.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(PJs.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(IJs.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(DJs.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(VJs.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(HJs.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(GJs.configure(this.options.heading)),this.options.history!==!1&&s.push(sen.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(nen.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(len.configure(this.options.italic)),this.options.listItem!==!1&&s.push(cen.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(uen.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(hen.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(pen.configure(this.options.strike)),this.options.text!==!1&&s.push(gen.configure(this.options.text)),s}}),xen="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",yen="ελ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",cWe="numeric",dWe="ascii",uWe="alpha",Aee="asciinumeric",dQ="alphanumeric",hWe="domain",UVt="emoji",ven="scheme",ben="slashscheme",mBe="whitespace";function _en(s,t){return s in t||(t[s]=[]),t[s]}function d8(s,t,n){t[cWe]&&(t[Aee]=!0,t[dQ]=!0),t[dWe]&&(t[Aee]=!0,t[uWe]=!0),t[Aee]&&(t[dQ]=!0),t[uWe]&&(t[dQ]=!0),t[dQ]&&(t[hWe]=!0),t[UVt]&&(t[hWe]=!0);for(const r in t){const a=_en(r,n);a.indexOf(s)<0&&a.push(s)}}function wen(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function pw(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}pw.groups={};pw.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),rx=(s,t,n,r,a)=>s.tr(t,n,r,a),k1t=(s,t,n,r,a)=>s.ts(t,n,r,a),bi=(s,t,n,r,a)=>s.tt(t,n,r,a),xA="WORD",mWe="UWORD",qVt="ASCIINUMERICAL",VVt="ALPHANUMERICAL",vse="LOCALHOST",fWe="TLD",pWe="UTLD",h3e="SCHEME",gU="SLASH_SCHEME",Lnt="NUM",gWe="WS",Rnt="NL",Eee="OPENBRACE",Tee="CLOSEBRACE",oTe="OPENBRACKET",lTe="CLOSEBRACKET",cTe="OPENPAREN",dTe="CLOSEPAREN",uTe="OPENANGLEBRACKET",hTe="CLOSEANGLEBRACKET",mTe="FULLWIDTHLEFTPAREN",fTe="FULLWIDTHRIGHTPAREN",pTe="LEFTCORNERBRACKET",gTe="RIGHTCORNERBRACKET",xTe="LEFTWHITECORNERBRACKET",yTe="RIGHTWHITECORNERBRACKET",vTe="FULLWIDTHLESSTHAN",bTe="FULLWIDTHGREATERTHAN",_Te="AMPERSAND",wTe="APOSTROPHE",jTe="ASTERISK",hP="AT",NTe="BACKSLASH",kTe="BACKTICK",STe="CARET",u8="COLON",Dnt="COMMA",CTe="DOLLAR",_5="DOT",ATe="EQUALS",Fnt="EXCLAMATION",mN="HYPHEN",Mee="PERCENT",ETe="PIPE",TTe="PLUS",MTe="POUND",Pee="QUERY",Ont="QUOTE",HVt="FULLWIDTHMIDDLEDOT",znt="SEMI",w5="SLASH",Iee="TILDE",PTe="UNDERSCORE",GVt="EMOJI",ITe="SYM";var WVt=Object.freeze({__proto__:null,ALPHANUMERICAL:VVt,AMPERSAND:_Te,APOSTROPHE:wTe,ASCIINUMERICAL:qVt,ASTERISK:jTe,AT:hP,BACKSLASH:NTe,BACKTICK:kTe,CARET:STe,CLOSEANGLEBRACKET:hTe,CLOSEBRACE:Tee,CLOSEBRACKET:lTe,CLOSEPAREN:dTe,COLON:u8,COMMA:Dnt,DOLLAR:CTe,DOT:_5,EMOJI:GVt,EQUALS:ATe,EXCLAMATION:Fnt,FULLWIDTHGREATERTHAN:bTe,FULLWIDTHLEFTPAREN:mTe,FULLWIDTHLESSTHAN:vTe,FULLWIDTHMIDDLEDOT:HVt,FULLWIDTHRIGHTPAREN:fTe,HYPHEN:mN,LEFTCORNERBRACKET:pTe,LEFTWHITECORNERBRACKET:xTe,LOCALHOST:vse,NL:Rnt,NUM:Lnt,OPENANGLEBRACKET:uTe,OPENBRACE:Eee,OPENBRACKET:oTe,OPENPAREN:cTe,PERCENT:Mee,PIPE:ETe,PLUS:TTe,POUND:MTe,QUERY:Pee,QUOTE:Ont,RIGHTCORNERBRACKET:gTe,RIGHTWHITECORNERBRACKET:yTe,SCHEME:h3e,SEMI:znt,SLASH:w5,SLASH_SCHEME:gU,SYM:ITe,TILDE:Iee,TLD:fWe,UNDERSCORE:PTe,UTLD:pWe,UWORD:mWe,WORD:xA,WS:gWe});const X3=/[a-z]/,PZ=new RegExp("\\p{L}","u"),fBe=new RegExp("\\p{Emoji}","u"),Q3=/\d/,pBe=/\s/,S1t="\r",gBe=` `,jen="️",Nen="‍",xBe="";let ude=null,hde=null;function ken(s=[]){const t={};pw.groups=t;const n=new pw;ude==null&&(ude=C1t(xen)),hde==null&&(hde=C1t(yen)),bi(n,"'",wTe),bi(n,"{",Eee),bi(n,"}",Tee),bi(n,"[",oTe),bi(n,"]",lTe),bi(n,"(",cTe),bi(n,")",dTe),bi(n,"<",uTe),bi(n,">",hTe),bi(n,"(",mTe),bi(n,")",fTe),bi(n,"「",pTe),bi(n,"」",gTe),bi(n,"『",xTe),bi(n,"』",yTe),bi(n,"<",vTe),bi(n,">",bTe),bi(n,"&",_Te),bi(n,"*",jTe),bi(n,"@",hP),bi(n,"`",kTe),bi(n,"^",STe),bi(n,":",u8),bi(n,",",Dnt),bi(n,"$",CTe),bi(n,".",_5),bi(n,"=",ATe),bi(n,"!",Fnt),bi(n,"-",mN),bi(n,"%",Mee),bi(n,"|",ETe),bi(n,"+",TTe),bi(n,"#",MTe),bi(n,"?",Pee),bi(n,'"',Ont),bi(n,"/",w5),bi(n,";",znt),bi(n,"~",Iee),bi(n,"_",PTe),bi(n,"\\",NTe),bi(n,"・",HVt);const r=rx(n,Q3,Lnt,{[cWe]:!0});rx(r,Q3,r);const a=rx(r,X3,qVt,{[Aee]:!0}),i=rx(r,PZ,VVt,{[dQ]:!0}),l=rx(n,X3,xA,{[dWe]:!0});rx(l,Q3,a),rx(l,X3,l),rx(a,Q3,a),rx(a,X3,a);const o=rx(n,PZ,mWe,{[uWe]:!0});rx(o,X3),rx(o,Q3,i),rx(o,PZ,o),rx(i,Q3,i),rx(i,X3),rx(i,PZ,i);const c=bi(n,gBe,Rnt,{[mBe]:!0}),d=bi(n,S1t,gWe,{[mBe]:!0}),u=rx(n,pBe,gWe,{[mBe]:!0});bi(n,xBe,u),bi(d,gBe,c),bi(d,xBe,u),rx(d,pBe,u),bi(u,S1t),bi(u,gBe),rx(u,pBe,u),bi(u,xBe,u);const h=rx(n,fBe,GVt,{[UVt]:!0});bi(h,"#"),rx(h,fBe,h),bi(h,jen,h);const m=bi(h,Nen);bi(m,"#"),rx(m,fBe,h);const f=[[X3,l],[Q3,a]],g=[[X3,null],[PZ,o],[Q3,i]];for(let x=0;xx[0]>v[0]?1:-1);for(let x=0;x=0?b[hWe]=!0:X3.test(v)?Q3.test(v)?b[Aee]=!0:b[dWe]=!0:b[cWe]=!0,k1t(n,v,v,b)}return k1t(n,"localhost",vse,{ascii:!0}),n.jd=new pw(ITe),{start:n,tokens:Object.assign({groups:t},WVt)}}function KVt(s,t){const n=Sen(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 Sen(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 wM(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 bse={defaultProtocol:"http",events:null,format:A1t,formatHref:A1t,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Bnt(s,t=null){let n=Object.assign({},bse);s&&(n=Object.assign(n,s instanceof Bnt?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=bse.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 $6e(s,t){class n extends YVt{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 Cen=$6e("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),E1t=$6e("text"),Aen=$6e("nl"),mde=$6e("url",{isLink:!0,toHref(s=bse.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==vse&&s[1].t===u8}}),J2=s=>new pw(s);function Een({groups:s}){const t=s.domain.concat([_Te,jTe,hP,NTe,kTe,STe,CTe,ATe,mN,Lnt,Mee,ETe,TTe,MTe,w5,ITe,Iee,PTe]),n=[wTe,u8,Dnt,_5,Fnt,Mee,Pee,Ont,znt,uTe,hTe,Eee,Tee,lTe,oTe,cTe,dTe,mTe,fTe,pTe,gTe,xTe,yTe,vTe,bTe],r=[_Te,wTe,jTe,NTe,kTe,STe,CTe,ATe,mN,Eee,Tee,Mee,ETe,TTe,MTe,Pee,w5,ITe,Iee,PTe],a=J2(),i=bi(a,Iee);Qd(i,r,i),Qd(i,s.domain,i);const l=J2(),o=J2(),c=J2();Qd(a,s.domain,l),Qd(a,s.scheme,o),Qd(a,s.slashscheme,c),Qd(l,r,i),Qd(l,s.domain,l);const d=bi(l,hP);bi(i,hP,d),bi(o,hP,d),bi(c,hP,d);const u=bi(i,_5);Qd(u,r,i),Qd(u,s.domain,i);const h=J2();Qd(d,s.domain,h),Qd(h,s.domain,h);const m=bi(h,_5);Qd(m,s.domain,h);const f=J2(Cen);Qd(m,s.tld,f),Qd(m,s.utld,f),bi(d,vse,f);const g=bi(h,mN);bi(g,mN,g),Qd(g,s.domain,h),Qd(f,s.domain,h),bi(f,_5,m),bi(f,mN,g);const x=bi(l,mN),v=bi(l,_5);bi(x,mN,x),Qd(x,s.domain,l),Qd(v,r,i),Qd(v,s.domain,l);const y=J2(mde);Qd(v,s.tld,y),Qd(v,s.utld,y),Qd(y,s.domain,l),Qd(y,r,i),bi(y,_5,v),bi(y,mN,x),bi(y,hP,d);const b=bi(y,u8),w=J2(mde);Qd(b,s.numeric,w);const S=J2(mde),A=J2();Qd(S,t,S),Qd(S,n,A),Qd(A,t,S),Qd(A,n,A),bi(y,w5,S),bi(w,w5,S);const E=bi(o,u8),I=bi(c,u8),P=bi(I,w5),R=bi(P,w5);Qd(o,s.domain,l),bi(o,_5,v),bi(o,mN,x),Qd(c,s.domain,l),bi(c,_5,v),bi(c,mN,x),Qd(E,s.domain,S),bi(E,w5,S),bi(E,Pee,S),Qd(R,s.domain,S),Qd(R,t,S),bi(R,w5,S);const D=[[Eee,Tee],[oTe,lTe],[cTe,dTe],[uTe,hTe],[mTe,fTe],[pTe,gTe],[xTe,yTe],[vTe,bTe]];for(let O=0;O=0&&m++,a++,u++;if(m<0)a-=u,a0&&(i.push(yBe(E1t,t,l)),l=[]),a-=m,u-=m;const f=h.t,g=n.slice(a-u,a);i.push(yBe(f,t,g))}}return l.length>0&&i.push(yBe(E1t,t,l)),i}function yBe(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 Men=typeof console<"u"&&console&&console.warn||(()=>{}),Pen="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",vp={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function Ien(){return pw.groups={},vp.scanner=null,vp.parser=null,vp.tokenQueue=[],vp.pluginQueue=[],vp.customSchemes=[],vp.initialized=!1,vp}function T1t(s,t=!1){if(vp.initialized&&Men(`linkifyjs: already initialized - will not register custom scheme "${s}" ${Pen}`),!/^[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`);vp.customSchemes.push([s,t])}function Len(){vp.scanner=ken(vp.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(xQs(o).forEach(({newRange:d})=>{const u=hQs(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(!Den.test(f))return;h=u[0],m=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&m){const f=m.split(Ren).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 v=$nt(g).map(y=>y.toObject(s.defaultProtocol));if(!Oen(v))return!1;v.filter(y=>y.isLink).map(y=>({...y,from:x+y.start+1,to:x+y.end+1})).filter(y=>r.schema.marks.code?!r.doc.rangeHasMark(y.from,y.to,r.schema.marks.code):!0).filter(y=>s.validate(y.value)).filter(y=>s.shouldAutoLink(y.value)).forEach(y=>{Ent(y.from,y.to,r.doc).some(b=>b.mark.type===s.type)||l.addMark(y.from,y.to,s.type.create({href:y.href}))})}}),!!l.steps.length)return l}})}function Ben(s){return new O0({key:new A1("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=PVt(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 $en(s){return new O0({key:new A1("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=ZVt(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 uR(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(Fen,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const U6e=fC.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"){T1t(s);return}T1t(s.scheme,s.optionalSlashes)})},onDestroy(){Ien()},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)=>!!uR(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=>!!uR(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=>!!uR(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Jf(this.options.HTMLAttributes,s),0]:["a",Jf(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!uR(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=>!!uR(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[G7({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=ZVt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!uR(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(zen({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!uR(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(Ben({type:this.type})),this.options.linkOnPaste&&s.push($en({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),q6e=Sb.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")}}}),Uen=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}`)})},qnt=fC.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&Uen(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",Jf(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}}}}),qen=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,XVt=Pv.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",Jf(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[IVt({find:qen,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let xWe,yWe;if(typeof WeakMap<"u"){let s=new WeakMap;xWe=t=>s.get(t),yWe=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;xWe=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var xx=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:y-w});break}const S=a+w*t;for(let A=0;Ar&&(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 Gen(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 Ken(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 _C(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 V6e(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=W7(t.$head)||Yen(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function Yen(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 vWe(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function Zen(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function Vnt(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function QVt(s,t,n){const r=s.node(-1),a=xx.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 K7(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 JVt(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 wqt(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(vWe(r)&&vWe(a)&&Vnt(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?yA.rowSelection(r,a):i&&this.isColSelection()?yA.colSelection(r,a):new yA(r,a)}return El.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=xx.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||v>0){let y=g.attrs;if(x>0&&(y=K7(y,0,x)),v>0&&(y=K7(y,y.colspan-v,v)),f.lefta.bottom){const y={...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=xx.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 yA&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=xx.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(g_.node(r,r+n.nodeSize,{class:"selectedCell"}))}),px.create(s.doc,t)}function etn({$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 ttn({$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 stn(s,t,n){const r=(t||s).selection,a=(t||s).doc;let i,l;if(r instanceof Tl&&(l=r.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=Qf.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=Qf.rowSelection(o,o)}else if(!n){const o=xx.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=Qf.create(a,c+1,d)}}else r instanceof El&&etn(r)?i=El.create(a,r.from):r instanceof El&&ttn(r)&&(i=El.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const ntn=new A1("fix-tables");function tHt(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=rtn(s,a,i,n))};return t?t.doc!=s.doc&&tHt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function rtn(s,t,n,r){const a=xx.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 v=0;v0?-1:0;Xen(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;ctn(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=M1t(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new Qf(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function I1t(s,t){const n=N1(s.schema);return ptn(({node:r})=>n[r.type.spec.tableRole])(s,t)}function ptn(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof Qf){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=Ken(r.$from),!a)return!1;i=(l=W7(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=i3(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 xtn(s){return function(t,n){if(!_C(t))return!1;if(n){const r=N1(t.schema),a=i3(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}}_se("row",{useDeprecatedLogic:!0});_se("column",{useDeprecatedLogic:!0});const ytn=_se("cell",{useDeprecatedLogic:!0});function vtn(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 fde(s,t){const n=s.selection;if(!(n instanceof Qf))return!1;if(t){const r=s.tr,a=N1(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 _tn(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(di.empty),n[a]r&&(m=m.type.createChecked(K7(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(di.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function Ntn(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=N1(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(v?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const m=c.row.create(null,di.from(h)),f=[];for(let g=t.height;g{if(!a)return!1;const i=n.selection;if(i instanceof Qf)return m3e(n,r,wc.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=aHt(a,s,t);if(l==null)return!1;if(s=="horiz")return m3e(n,r,wc.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=QVt(o,s,t);let d;return c?d=wc.near(c,1):t<0?d=wc.near(n.doc.resolve(o.before(-1)),-1):d=wc.near(n.doc.resolve(o.after(-1)),1),m3e(n,r,d)}}}function gde(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof Qf)l=i;else{const c=aHt(a,s,t);if(c==null)return!1;l=new Qf(n.doc.resolve(c))}const o=QVt(l.$headCell,s,t);return o?m3e(n,r,new Qf(l.$anchorCell,o)):!1}}function Stn(s,t){const n=s.state.doc,r=W7(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new Qf(r))),!0):!1}function Ctn(s,t,n){if(!_C(s.state))return!1;let r=_tn(n);const a=s.state.selection;if(a instanceof Qf){r||(r={width:1,height:1,rows:[di.from(bWe(N1(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=xx.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=jtn(r,o.right-o.left,o.bottom-o.top),O1t(s.state,s.dispatch,l,o,r),!0}else if(r){const i=V6e(s.state),l=i.start(-1);return O1t(s.state,s.dispatch,l,xx.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function Atn(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=z1t(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof Qf)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=W7(s.state.selection.$anchor))!=null&&((n=vBe(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=vBe(s,d);const h=NP.getState(s.state)==null;if(!u||!Vnt(c,u))if(h)u=c;else return;const m=new Qf(c,u);if(h||!s.state.selection.eq(m)){const f=s.state.tr.setSelection(m);h&&f.setMeta(NP,c.pos),s.dispatch(f)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),NP.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(NP,-1))}function o(c){const d=c,u=NP.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(z1t(s,d.target)!=r&&(h=vBe(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 aHt(s,t,n){if(!(s.state.selection instanceof El))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 z1t(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function vBe(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&&W7(s.state.doc.resolve(r))||W7(s.state.doc.resolve(a))}var Etn=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")),_We(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,_We(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function _We(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 Mtn(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=Wj.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{Ptn(l,o,s,a)},mouseleave:l=>{Itn(l)},mousedown:(l,o)=>{Ltn(l,o,t,n)}},decorations:l=>{const o=Wj.getState(l);if(o&&o.activeHandle>-1)return ztn(l,o.activeHandle)},nodeViews:{}}});return i}var Mtn=class f3e{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(Wj);if(r&&r.setHandle!=null)return new f3e(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new f3e(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return vWe(t.doc.resolve(a))||(a=-1),new f3e(a,n.dragging)}return n}};function Ptn(s,t,n,r){if(!s.editable)return;const a=Wj.getState(s.state);if(a&&!a.dragging){const i=Dtn(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=B1t(s,t,"left",n):c-t.clientX<=n&&(l=B1t(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=xx.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}iHt(s,l)}}}function Itn(s){if(!s.editable)return;const t=Wj.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&iHt(s,-1)}function Ltn(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=Wj.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=Rtn(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(Wj,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const m=Wj.getState(s.state);m!=null&&m.dragging&&(Ftn(s,m.activeHandle,$1t(m.dragging,h,n)),s.dispatch(s.state.tr.setMeta(Wj,{setDragging:null})))}function u(h){if(!h.which)return d(h);const m=Wj.getState(s.state);if(m&&m.dragging){const f=$1t(m.dragging,h,n);U1t(s,m.activeHandle,f,r)}}return U1t(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function Rtn(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 Vtn(s,t,n,r,a){const i=qtn(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!Htn(t))return!1;let n=0;const r=MVt(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},Gtn=Pv.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:$tn,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}=Utn(s,this.options.cellMinWidth),i=["table",Jf(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=Vtn(i.schema,s,t,n);if(a){const o=r.selection.from+1;r.replaceSelectionWith(l).scrollIntoView().setSelection(El.near(r.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>atn(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>itn(s,t),deleteColumn:()=>({state:s,dispatch:t})=>ltn(s,t),addRowBefore:()=>({state:s,dispatch:t})=>dtn(s,t),addRowAfter:()=>({state:s,dispatch:t})=>utn(s,t),deleteRow:()=>({state:s,dispatch:t})=>mtn(s,t),deleteTable:()=>({state:s,dispatch:t})=>btn(s,t),mergeCells:()=>({state:s,dispatch:t})=>P1t(s,t),splitCell:()=>({state:s,dispatch:t})=>I1t(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>_se("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>_se("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>ytn(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>P1t(s,t)?!0:I1t(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>gtn(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>R1t(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>R1t(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&sHt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=Qf.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:xde,"Mod-Backspace":xde,Delete:xde,"Mod-Delete":xde}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[Ttn({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],Btn({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:wd(Uo(s,"tableRole",t))}}}),Wtn=Pv.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",Jf(this.options.HTMLAttributes,s),0]}}),Ktn=Pv.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",Jf(this.options.HTMLAttributes,s),0]}}),Ytn=Pv.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",Jf(this.options.HTMLAttributes,s),0]}});function kk({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=z6e({extensions:[B6e,U6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),q6e.configure({types:["heading","paragraph"]}),qnt,XVt.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}),Gtn.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}),Wtn.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),style:{default:null}}}}),Ktn.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}}}}),Ytn.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,v)=>{var b;const y=(b=v.clipboardData)==null?void 0:b.items;if(!y)return!1;for(const w of Array.from(y))if(w.type.startsWith("image/")){v.preventDefault();const S=w.getAsFile();if(!S)continue;const A=new FileReader;return A.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})))},A.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||"",v=h.getAttributes("link").target;c(x),u(v==="_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(Iq,{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(Oz,{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(kE,{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(AE,{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(E0,{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(c2,{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(RI,{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(LI,{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(DI,{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(Sd,{className:"h-4 w-4"})}),h.isActive("link")&&e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:g,title:"Remove Link",children:e.jsx(Sd,{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(FE,{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(RE,{className:"h-4 w-4"})})]}),e.jsx(O6e,{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(Os,{open:i,onOpenChange:l,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{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(jn,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(ee,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(Nr,{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 Hnt={x:0,y:0,width:0,height:0,unit:"px"},w$=(s,t,n)=>Math.min(Math.max(s,t),n),Ztn=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),H1t=(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 Xtn(s,t,n,r){let a=j5(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==="%"?mP(a,n,r):a}function Qtn(s,t,n){let r=j5(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?mP(r,t,n):r}function mP(s,t,n){return s.unit==="%"?{...Hnt,...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 j5(s,t,n){return!s.unit||s.unit==="px"?{...Hnt,...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 G1t(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 v=d.width/d.height;if(vt){let y=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=y-d.width),d.width=y}}return d}function Jtn(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 j$={capture:!0,passive:!1},esn=0,ux,tsn=(ux=class extends j.PureComponent{constructor(){super(...arguments);_r(this,"docMoveBound",!1);_r(this,"mouseDownOnCrop",!1);_r(this,"dragStarted",!1);_r(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0});_r(this,"componentRef",j.createRef());_r(this,"mediaRef",j.createRef());_r(this,"resizeObserver");_r(this,"initChangeCalled",!1);_r(this,"instanceId",`rc-${esn++}`);_r(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1});_r(this,"onCropPointerDown",n=>{let{crop:r,disabled:a}=this.props,i=this.getBox();if(!r)return;let l=j5(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,v=0;o==="ne"||o=="e"?(x=f-(l.x+l.width),v=g-l.y,h=l.x,m=l.y+l.height):o==="se"||o==="s"?(x=f-(l.x+l.width),v=g-(l.y+l.height),h=l.x,m=l.y):o==="sw"||o=="w"?(x=f-l.x,v=g-(l.y+l.height),h=l.x+l.width,m=l.y):(o==="nw"||o=="n")&&(x=f-l.x,v=g-l.y,h=l.x+l.width,m=l.y+l.height),d=h+i.x+x,u=m+i.y+v}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})});_r(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(j5(h,c.width,c.height),mP(h,c.width,c.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})});_r(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(),H1t(r,d)||i(j5(d,o.width,o.height),mP(d,o.width,o.height))});_r(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)?ux.nudgeStepLarge:n.shiftKey?ux.nudgeStepMedium:ux.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=w$(u.x,0,d.width-u.width),u.y=w$(u.y,0,d.height-u.height);let m=j5(u,d.width,d.height),f=mP(u,d.width,d.height);i(m,f),l&&l(m,f)}});_r(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)?ux.nudgeStepLarge:n.shiftKey?ux.nudgeStepMedium:ux.nudgeStep,x=G1t(Jtn(j5(i,f.width,f.height),n.key,g,r),a,r,f.width,f.height,o,c,d,u);if(!H1t(i,x)){let v=mP(x,f.width,f.height);h(x,v),m&&m(x,v)}});_r(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(j5(r,o.width,o.height),mP(r,o.width,o.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))});_r(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(j5(r,i,l),mP(r,i,l))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.docMoveBound=(this.document.addEventListener("pointermove",this.onDocPointerMove,j$),this.document.addEventListener("pointerup",this.onDocPointerDone,j$),this.document.addEventListener("pointercancel",this.onDocPointerDone,j$),!0))}unbindDocMove(){this.docMoveBound&&(this.docMoveBound=(this.document.removeEventListener("pointermove",this.onDocPointerMove,j$),this.document.removeEventListener("pointerup",this.onDocPointerDone,j$),this.document.removeEventListener("pointercancel",this.onDocPointerDone,j$),!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=w$(n.startCropX+i,0,r.width-a.width),a.y=w$(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=G1t(g,r,u,l.width,l.height,o,c,a,i);return r||ux.xyOrds.indexOf(h)>-1?d=x:ux.xOrds.indexOf(h)>-1?(d.x=x.x,d.width=x.width):ux.yOrds.indexOf(h)>-1&&(d.y=x.y,d.height=x.height),d.x=w$(d.x,0,l.width-d.width),d.y=w$(d.y,0,l.height-d.height),d}renderCropSelection(){let{ariaLabels:n=ux.defaultProps.ariaLabels,disabled:r,locked:a,renderSelectionAddon:i,ruleOfThirds:l,crop:o}=this.props,c=this.getCropStyle();if(o)return Kt.createElement("div",{style:c,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":n.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!r&&!a&&Kt.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},Kt.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),Kt.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),Kt.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),Kt.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),Kt.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"}),Kt.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"}),Kt.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"}),Kt.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"}),Kt.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"}),Kt.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"}),Kt.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"}),Kt.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&&Kt.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:d=>d.stopPropagation()},i(this.state)),l&&Kt.createElement(Kt.Fragment,null,Kt.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),Kt.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(n){return j5({...Hnt,...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=Ztn("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 Kt.createElement("div",{ref:this.componentRef,className:g,style:d},Kt.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},r),l?Kt.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},Kt.createElement("defs",null,Kt.createElement("mask",{id:`hole-${this.instanceId}`},Kt.createElement("rect",{width:"100%",height:"100%",fill:"white"}),a?Kt.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"}):Kt.createElement("rect",{x:`${l.x}${l.unit}`,y:`${l.y}${l.unit}`,width:`${l.width}${l.unit}`,height:`${l.height}${l.unit}`,fill:"black"}))),Kt.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,f)}},_r(ux,"xOrds",["e","w"]),_r(ux,"yOrds",["n","s"]),_r(ux,"xyOrds",["nw","ne","se","sw"]),_r(ux,"nudgeStep",1),_r(ux,"nudgeStepMedium",10),_r(ux,"nudgeStepLarge",100),_r(ux,"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"}}),ux);function ssn(s,t,n){return Qtn(Xtn({unit:"%",width:90},n,s,t),s,t)}const Gnt=({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(y=>{const{width:b,height:w}=y.currentTarget;o(ssn(b,w,a))},[a]),x=j.useCallback(async()=>{const y=i.current;if(!y||!c)return;const b=document.createElement("canvas"),w=b.getContext("2d");if(!w)return;const S=y.naturalWidth/y.width,A=y.naturalHeight/y.height,E=400;b.width=E,b.height=E,w.imageSmoothingQuality="high";const I=c.x*S,P=c.y*A,R=c.width*S,D=c.height*A,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(y,I,P,R,D,0,0,E,E),w.restore(),new Promise((V,G)=>{b.toBlob(Z=>{Z?V(Z):G(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,m]),v=async()=>{try{const y=await x();y&&(r(y),t())}catch(y){console.error("Error cropping image:",y)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx($s,{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(tsn,{crop:l,onChange:(y,b)=>o(b),onComplete:y=>d(y),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(hV,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(bx,{value:[u],min:.5,max:3,step:.1,onValueChange:([y])=>h(y),className:"flex-1"}),e.jsx(JI,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Wz,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(bx,{value:[m],min:-180,max:180,step:1,onValueChange:([y])=>f(y),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[m,"°"]})]})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx($,{onClick:v,children:"Save Photo"})]})]})})},W1t="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 nsn(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 rsn(){const{user:s}=_s(),{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 v=async()=>{const b=nsn(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:W1t,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."})},y=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(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(no,{className:"h-5 w-5"}),"Text Message (SMS) Alerts",u&&e.jsx($e,{variant:"secondary",children:"Opted in"})]}),e.jsx(Vn,{children:"Get a text the moment a new lead comes in, plus important account notifications."})]}),e.jsx(Le,{className:"space-y-4",children:n?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{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:W1t})]})}),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:v,disabled:a||u&&!l,children:[a&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),u?"Update Number":"Opt in to SMS"]}),u?e.jsx($,{variant:"outline",onClick:y,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 K1t="#2a4c64",Y1t="#B8965A",Z1t="Inter",X1t="Inter";function xU(s){if(typeof s!="string")return null;const t=s.trim();return t.length?t:null}function X_(s,t=null){for(const[n,r]of s){const a=xU(r);if(a)return{value:a,source:n}}return{value:t,source:"default"}}function asn(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=X_(l(t.brand_color,n.primary_color,r.brand_color),K1t),c=X_(l(t.accent_color,n.accent_color,r.accent_color),Y1t),d=X_([["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=X_(u),m=X_([["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]]),f=X_([["agent",t.headshot_url],["legacy",r.avatar_url]]),g=X_([["agent",t.tagline],["legacy",r.tagline||r.title]]),x=X_([["agent",t.preferred_font],["brokerage",n.heading_font]],Z1t),v=X_([["brokerage",n.body_font]],X1t),y=X_([["agent",t.license_number],["legacy",r.license_number]]),b=X_([["agent",t.license_state],["legacy",r.license_state],["brokerage",n.license_state]]),w=X_([["agent",t.website_url],["legacy",r.website_url]]),S=X_([["brokerage",n.legal_name],["legacy",r.brokerage_name]]),A=X_([["brokerage",n.compliance_line]]);return{agent_name:xU(r.name),brokerage_name:S.value,brand_color:o.value??K1t,secondary_color:d.value,accent_color:c.value??Y1t,heading_font:x.value??Z1t,body_font:v.value??X1t,logo_url:h.value,logo_dark_url:xU(n.logo_dark_url),brokerage_logo_url:m.value,icon_mark_url:xU(n.icon_mark_url),headshot_url:f.value,tagline:g.value,license_number:y.value,license_state:b.value,website_url:w.value,email:xU(r.email),phone:xU(r.phone),compliance_line:A.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:v.source,license_number:y.source,license_state:b.source,website_url:w.source,brokerage_name:S.source,compliance_line:A.source}}}function isn(){const{user:s}=_s();return st({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 osn(){const{user:s}=_s(),t=Zt();return mt({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 st({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 csn(s){const{user:t}=_s(),n=Zt();return mt({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 oHt(){const{user:s}=_s();return st({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 asn({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 lHt(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 usn(){const{user:s}=_s(),{toast:t}=Bi(),{data:n,isLoading:r}=isn(),{data:a}=oHt(),i=osn(),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=(v,y)=>u(b=>({...b,[v]:y})),g=async v=>{if(s){c(!0);try{const y=await lHt(s.id,v,"logo");f("logo_url",y),t({title:"Logo uploaded"})}catch(y){t({title:"Upload failed",description:y.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(v){t({title:"Could not save",description:v.message,variant:"destructive"})}};return e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(yd,{className:"h-5 w-5"}),"Brand Kit"]}),e.jsx(Vn,{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(Le,{className:"space-y-6",children:r?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Ct,{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($e,{variant:"secondary",className:"gap-1",children:[e.jsx(jc,{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:v=>f("brand_color",v.target.value)}),e.jsx(pe,{value:d.brand_color,placeholder:(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:v=>f("brand_color",v.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:v=>f("accent_color",v.target.value)}),e.jsx(pe,{value:d.accent_color,placeholder:(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:v=>f("accent_color",v.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($e,{variant:"secondary",className:"gap-1",children:[e.jsx(jc,{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:v=>{var y;return((y=v.target.files)==null?void 0:y[0])&&g(v.target.files[0])}}),e.jsxs($,{type:"button",variant:"outline",disabled:o||m,onClick:()=>{var v;return(v=l.current)==null?void 0:v.click()},children:[o?e.jsx(Ct,{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:v=>f("tagline",v.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:v=>f("preferred_font",v.target.value)}),e.jsx("datalist",{id:"brand-font-options",children:dsn.map(v=>e.jsx("option",{value:v},v))})]}),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:v=>f("license_number",v.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:v=>f("license_state",v.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:v=>f("website_url",v.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(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save brand kit"]})]})})]})}const bBe="id, name, address, notes, created_at, locked_style, share_token, share_enabled, share_headline, share_message, share_views";function Dkr(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 hsn(){var o,c,d;const{user:s}=_s(),t=Zt(),n=st({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 Fkr(){return st({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 Okr(){const{user:s}=_s(),t=Zt(),n=st({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(bBe).eq("user_id",s.id).order("created_at",{ascending:!1});if(c)throw c;return o??[]}}),r=mt({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(bBe).single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:["staging-projects"]})}),a=mt({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=mt({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=mt({mutationFn:async o=>{const{id:c,...d}=o,{data:u,error:h}=await q.from("staging_projects").update(d).eq("id",c).select(bBe).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 zkr(){return mt({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 Bkr(s){const{user:t}=_s(),n=Zt(),r=st({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=mt({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=mt({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=mt({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 $kr(){const s=Zt();return mt({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 Ukr(s){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=n,r.readAsDataURL(s)})}function msn(){try{return window.open("","_blank")}catch{return null}}function fsn(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 psn(s){try{s&&!s.closed&&s.close()}catch{}}async function gsn(s,t){if(s instanceof jae)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 xsn(){var i;const s=hsn(),[t,n]=j.useState(!1);if(s.isLoading)return null;const r=s.unlimited&&s.unlimitedReason==="plan",a=async()=>{if(t)return;const l=msn();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");fsn(l,o.url)}catch(o){psn(l);const c=await gsn(o,"We could not open your billing portal. Contact support and we will sort it out.");console.error("[staging-portal]",c,o),ne.error(c)}finally{n(!1)}};return e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-5 w-5"}),"Staging Studio Billing"]}),e.jsx(Vn,{children:"Manage the plan and credits that power your AI photo staging"})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx($e,{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(Ct,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}):e.jsx(jv,{className:"mr-1.5 h-3.5 w-3.5"}),"Manage billing"]}),e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(br,{to:"/apps/staging-studio/credits",children:["Credits & history ",e.jsx(Ir,{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 Q1t=["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"],ysn=5*1024*1024;function vsn({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(!Q1t.includes(g.type)){ne.error("Please upload a PNG, JPG, SVG or WebP file");return}if(g.size>ysn){ne.error("Please choose a logo under 5MB");return}d(!0);try{const x=(g.name.split(".").pop()||"png").toLowerCase(),v=`${s}/brokerage-logo-${Date.now()}.${x}`,{error:y}=await q.storage.from("card-logos").upload(v,g,{cacheControl:"3600",upsert:!0,contentType:g.type});if(y)throw y;const{data:b}=q.storage.from("card-logos").getPublicUrl(v),w=b.publicUrl;r&&await q.from("profiles").update({brokerage_logo_url:w}).eq("id",s),n(w),ne.success("Brokerage logo uploaded")}catch(x){ne.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 v;g.preventDefault(),h(!1);const x=(v=g.dataTransfer.files)==null?void 0:v[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(wi,{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(Ct,{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(qn,{className:"h-4 w-4 text-muted-foreground"})})]})]}),e.jsx("input",{ref:o,type:"file",accept:Q1t.join(","),className:"hidden",onChange:g=>{var v;const x=(v=g.target.files)==null?void 0:v[0];x&&m(x),g.target.value=""}})]})}const bsn=()=>{const{user:s}=_s(),{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($e,{className:"bg-green-500",children:"Active"});switch(l==null?void 0:l.status){case"active":return e.jsx($e,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx($e,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx($e,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx($e,{variant:"secondary",children:"Canceled"});default:return e.jsx($e,{variant:"outline",children:"No Subscription"})}};return n?e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(jv,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Le,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(jv,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(Vn,{children:"Manage your subscription and billing"})]}),e.jsxs(Le,{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(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ir,{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."})]})]})},_sn=()=>{const{user:s}=_s(),t=Zn(),{toast:n}=Bi(),[r]=Nc(),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}=t7t(),[m,f]=j.useState(!1),[g,x]=j.useState(""),[v,y]=j.useState(null),[b,w]=j.useState(!1),[S,A]=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),[Z,X]=j.useState(!1),[ae,le]=j.useState(!1),[re,te]=j.useState({newPassword:"",confirmPassword:""});j.useEffect(()=>{s&&J()},[s]),j.useEffect(()=>{i&&s&&setTimeout(()=>{var Ne;(Ne=document.getElementById("change-password-section"))==null||Ne.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const J=async()=>{var Ne,Be,Se,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 Ve=((Ne=Ce.brokerages)==null?void 0:Ne.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:((Be=Ce.years_experience)==null?void 0:Be.toString())||"",brokerage_name:Ce.brokerage_id?Ve: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),y(Ce.brokerage_logo_url||null)}else console.warn("No profile found for user"),R({name:((Se=s.user_metadata)==null?void 0:Se.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:Ve}=q.storage.from("avatars").getPublicUrl(`${s.id}/${ze[0].name}`);x(Ve.publicUrl)}}catch(Ce){console.error("Error loading profile:",Ce),n({title:"Error",description:Ce.message||"Failed to load profile",variant:"destructive"})}},ce=Ne=>{var Ae;const Be=(Ae=Ne.target.files)==null?void 0:Ae[0];if(!Be)return;const Se=new FileReader;Se.onloadend=()=>{I(Se.result),A(!0)},Se.readAsDataURL(Be),Ne.target.value=""},ve=async Ne=>{if(s){w(!0);try{const{data:Be}=await q.storage.from("avatars").list(`${s.id}`),Se=(Be??[]).filter(ht=>/^avatar[.-]/i.test(ht.name));Se.length>0&&await q.storage.from("avatars").remove(Se.map(ht=>`${s.id}/${ht.name}`));const Ce=`${s.id}/avatar.jpg`,{error:qe}=await q.storage.from("avatars").upload(Ce,Ne,{upsert:!0,contentType:"image/jpeg"});if(qe)throw qe;const{data:ze}=q.storage.from("avatars").getPublicUrl(Ce),Ve=ze.publicUrl;x(`${Ve}?t=${Date.now()}`),await q.from("profiles").update({avatar_url:Ve}).eq("id",s.id),n({title:"Success",description:"Profile photo updated successfully"})}catch(Be){console.error("Error uploading avatar:",Be),n({title:"Error",description:Be.message||"Failed to upload photo",variant:"destructive"})}finally{w(!1)}}},fe=async()=>{if(!P.name.trim()||!P.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}f(!0);try{const Ne=P.email.trim().toLowerCase(),Be=((s==null?void 0:s.email)||"").toLowerCase(),Se=!!Ne&&Ne!==Be;if(Se){const{data:Ce,error:qe}=await q.functions.invoke("update-own-email",{body:{newEmail:Ne}}),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:Ne,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:Se?"Profile updated. Your login email is now "+Ne:"Profile updated successfully"})}catch(Ne){console.error("Error updating profile:",Ne),n({title:"Error",description:Ne.message||"Failed to update profile",variant:"destructive"})}finally{f(!1)}},ue=async()=>{if(!re.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(re.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(re.newPassword!==re.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}f(!0);try{const{error:Ne}=await q.auth.updateUser({password:re.newPassword});if(Ne)throw Ne;n({title:"Success",description:"Password updated successfully"}),te({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(Ne){console.error("Error updating password:",Ne),n({title:"Error",description:Ne.message||"Failed to update password",variant:"destructive"})}finally{f(!1)}},be=[P.name,P.email,P.phone,P.title,P.bio,P.areas_served,P.brokerage_name,g],Ee=be.filter(Ne=>Ne.trim()).length,ke=Math.round(Ee/be.length*100),Ie=P.name.split(" ").filter(Boolean).map(Ne=>Ne[0]).join("").toUpperCase().slice(0,2)||"U",Fe=Ne=>{var Be;(Be=document.getElementById(Ne))==null||Be.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(Ii,{src:g}),e.jsx(za,{children:Ie})]}),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 Ne;return(Ne=document.getElementById("avatar-upload"))==null?void 0:Ne.click()},disabled:b,"aria-label":"Change profile photo",children:b?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(jx,{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:[ke,"%"]})]}),e.jsx("div",{className:"profile-progress","aria-label":`Profile ${ke}% complete`,children:e.jsx("span",{style:{width:`${ke}%`}})}),e.jsx("p",{children:ke===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(rP,{className:"h-4 w-4"})," Profile details"]}),e.jsxs($,{variant:"ghost",onClick:()=>Fe("profile-brand"),children:[e.jsx(yd,{className:"h-4 w-4"})," Brand & signature"]}),e.jsxs($,{variant:"ghost",onClick:()=>Fe("change-password-section"),children:[e.jsx(Rm,{className:"h-4 w-4"})," Account security"]}),e.jsxs($,{variant:"ghost",onClick:()=>Fe("profile-notifications"),children:[e.jsx(YS,{className:"h-4 w-4"})," Notifications"]}),e.jsxs($,{variant:"ghost",onClick:()=>Fe("profile-billing"),children:[e.jsx(Gq,{className:"h-4 w-4"})," Billing"]})]}),e.jsxs($,{className:"profile-save",onClick:fe,disabled:m,children:[m?e.jsx(Ct,{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(je,{id:"profile-details",children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Personal Information"}),e.jsx(Vn,{children:"Update your profile details"})]}),e.jsxs(Le,{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:Ne=>R({...P,name:Ne.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:Ne=>R({...P,email:Ne.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:Ne=>R({...P,phone:Ne.target.value}),placeholder:"e.g., +14155551234",maxLength:20}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used for SMS lead notifications from your website — if you have a local authority site"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Job Title"}),e.jsx(pe,{id:"title",value:P.title,onChange:Ne=>R({...P,title:Ne.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:Ne=>R({...P,bio:Ne.target.value}),placeholder:"A short description about yourself",maxLength:500,className:"min-h-[120px] resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(pe,{id:"areas_served",value:P.areas_served,onChange:Ne=>R({...P,areas_served:Ne.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:Ne=>R({...P,years_experience:Ne.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:Ne=>R({...P,brokerage_name:Ne.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(vsn,{userId:s.id,value:v,onChange:y,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:Ne=>R({...P,linkedin_url:Ne.target.value}),placeholder:"LinkedIn URL"}),e.jsx(pe,{value:P.instagram_url,onChange:Ne=>R({...P,instagram_url:Ne.target.value}),placeholder:"Instagram URL"}),e.jsx(pe,{value:P.facebook_url,onChange:Ne=>R({...P,facebook_url:Ne.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:Ne=>R({...P,google_business_url:Ne.target.value}),placeholder:"Google Business Profile URL"}),e.jsx(pe,{value:P.zillow_profile_url,onChange:Ne=>R({...P,zillow_profile_url:Ne.target.value}),placeholder:"Zillow agent profile URL"}),e.jsx(pe,{value:P.realtor_profile_url,onChange:Ne=>R({...P,realtor_profile_url:Ne.target.value}),placeholder:"Realtor.com profile URL"}),e.jsx(pe,{value:P.specialties,onChange:Ne=>R({...P,specialties:Ne.target.value}),placeholder:"Specialties (e.g. Waterfront homes, Acreage & farms, First-time buyers)"})]})]}),e.jsxs($,{onClick:fe,disabled:m,className:"profile-inline-save",children:[e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(je,{id:"profile-brand",children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(_f,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(Vn,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Le,{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(jn,{checked:P.use_email_signature,onCheckedChange:Ne=>R({...P,use_email_signature:Ne})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Signature"}),e.jsx(kk,{content:P.email_signature,onChange:Ne=>R({...P,email_signature:Ne}),placeholder:"Paste your Gmail signature here or create one...",minHeight:"120px",compact:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tip: Copy your signature from Gmail Settings and paste it here — images and formatting will be preserved."})]}),e.jsxs($,{onClick:fe,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(usn,{})}),e.jsxs(je,{id:"change-password-section",children:[e.jsxs(St,{children:[e.jsx(Et,{children:a||l?"Set Your Password":"Change Password"}),e.jsx(Vn,{children:a||l?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Le,{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:re.newPassword,onChange:Ne=>te({...re,newPassword:Ne.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:re.confirmPassword,onChange:Ne=>te({...re,confirmPassword:Ne.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(je,{id:"profile-notifications",children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[c?e.jsx(zy,{className:"h-5 w-5"}):e.jsx(KS,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(Vn,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Le,{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(jn,{checked:c,onCheckedChange:Ne=>{Ne?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(rsn,{})}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[U?e.jsx(WI,{className:"h-5 w-5"}):e.jsx(pn,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(Vn,{children:"Manage your email subscription settings"})]}),e.jsxs(Le,{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(jn,{checked:!U,onCheckedChange:async Ne=>{G(!0);try{const{error:Be}=await q.from("profiles").update({digest_opt_out:!Ne}).eq("id",s==null?void 0:s.id);if(Be)throw Be;W(!Ne),n({title:Ne?"Subscribed":"Unsubscribed",description:Ne?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(Be){n({title:"Error",description:Be.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:Z?"You won't receive event invite emails (weekly digest is unaffected)":"Get invited to LevelUp live trainings and special events"})]}),e.jsx(jn,{checked:!Z,onCheckedChange:async Ne=>{le(!0);try{const{error:Be}=await q.from("profiles").update({event_invite_opt_out:!Ne}).eq("id",s==null?void 0:s.id);if(Be)throw Be;X(!Ne),n({title:Ne?"Subscribed":"Unsubscribed",description:Ne?"You will now receive event invite emails":"You will no longer receive event invite emails"})}catch(Be){n({title:"Error",description:Be.message||"Failed to update preference",variant:"destructive"})}finally{le(!1)}},disabled:ae})]})]})]}),e.jsx("div",{className:"profile-embedded-section",children:e.jsx(JWs,{})}),e.jsx("div",{id:"profile-billing",className:"profile-embedded-section",children:e.jsx(bsn,{})}),e.jsx("div",{className:"profile-embedded-section",children:e.jsx(xsn,{})})]})]})]}),e.jsx(Gnt,{open:S,onClose:()=>A(!1),imageSrc:E,onCropComplete:ve,aspectRatio:1})]})})};var wsn=Object.defineProperty,jsn=(s,t)=>wsn(s,"name",{value:t,configurable:!0}),Nsn=j.forwardRef(jsn(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")),ksn=Nsn;const Ssn=ksn;function Csn(){const{user:s}=_s(),t=Zt(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),{data:l,isLoading:o}=st({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=mt({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:v}=await q.from("profiles").update({calendar_token:x}).eq("id",s==null?void 0:s.id);if(v)throw v;return x},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),ne.success("Calendar subscription URL generated!")},onError:g=>{ne.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),ne.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(Os,{open:a,onOpenChange:i,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"gap-2",children:[e.jsx(Ea,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Ea,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(Er,{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(Ct,{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(ma,{className:"h-4 w-4 text-green-500"}):e.jsx(Za,{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(Ir,{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(Ir,{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(Ir,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const Asn={first_timer:ei,regular:EE,dedicated:Im,veteran:Kl,streak_master:sh,century:Kl},Esn={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 J1t(s){return s===1?e.jsx(Kl,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(EE,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(Im,{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 cHt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=_s(),{data:i,isLoading:l}=FUt(t?5:10,n),{data:o}=OUt(a==null?void 0:a.id),{data:c}=BUt(a==null?void 0:a.id),{data:d}=zUt(a==null?void 0:a.id);return l?e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Kl,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((u,h)=>e.jsx(xn,{className:"h-12 w-full"},h))})})]}):e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Kl,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsxs(Le,{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($e,{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(sh,{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=Asn[u.badge_type]||ei;return e.jsxs($e,{variant:"outline",className:`text-xs ${Esn[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($e,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(pa,{defaultValue:"points",className:"w-full",children:[e.jsxs(ga,{className:"w-full mb-3",children:[e.jsx(Xt,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(Xt,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(Qt,{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:J1t(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(Qt,{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:J1t(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 Tsn(){const s=Zn(),{user:t,isAdmin:n}=_s(),r=Zt(),[a,i]=j.useState(!1),[l,o]=j.useState(!1),{data:c,isLoading:d}=st({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}=st({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}=st({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=mt({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?ne.success("Successfully registered! You'll receive a Zoom confirmation email."):ne.success("Successfully registered for the event!")},onError:E=>{ne.error("Failed to register: "+E.message)}}),f=mt({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"]}),ne.success("Registration cancelled and removed from Zoom")},onError:E=>{ne.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},v=E=>E.capacity?((h==null?void 0:h[E.id])||0)>=E.capacity:!1,y=(c==null?void 0:c.filter(E=>i8(E.event_date)!=="ended"))||[],b=(c==null?void 0:c.filter(E=>i8(E.event_date)==="ended"))||[],w=y.filter(E=>i8(E.event_date)==="live").length,S=y.filter(E=>g(E.id)).length,A=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.":y.length>0?`Next up: ${y[0].title}`:"No upcoming events scheduled — replays are below."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Csn,{}),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(Nd,{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:y.length,icon:Ea},{label:"You're registered",value:S,icon:ma},{label:"Live now",value:w,icon:bb},{label:"Past events",value:b.length,icon:Cw}].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))}):y.length===0?e.jsx(je,{className:"rounded-2xl border-dashed py-12 text-center",children:e.jsxs(Le,{className:"space-y-2",children:[e.jsx(Ea,{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:y.map(E=>{const I=i8(E.event_date),P=tnt(E.event_date),R=I==="live",D=I==="starting_soon";return e.jsxs(je,{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(bb,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(ca,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),E.image_url&&e.jsxs(Ssn,{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(St,{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(Ea,{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(ma,{className:"h-3 w-3"}),"Registered"]})]}),e.jsx(Et,{className:"line-clamp-2 pt-1",children:E.title}),E.description&&e.jsx(Vn,{className:"line-clamp-2",children:E.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Le,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ea,{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(ca,{className:"h-4 w-4"}),ose(new Date(E.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Yn,{className:"h-4 w-4"}),(h==null?void 0:h[E.id])||0," registered",E.capacity&&` / ${E.capacity} spots`]})]}),e.jsx(gEe,{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(mr,{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(Ir,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx($,{className:"w-full",onClick:()=>m.mutate(E.id),disabled:m.isPending||v(E),children:v(E)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(ma,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},E.id)})}),b.length>0&&e.jsxs(je,{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(Cw,{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(wl,{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:A.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(ef,{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(cHt,{showUserStats:!0})})]})]})})}const _Be=[{value:"all",label:"All Roles",icon:Yn},{value:"newest",label:"Newest Members",icon:ca},{value:"brokerage_manager",label:"Brokerage Managers",icon:nee},{value:"admin",label:"Admins",icon:Tf}];function Msn({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var Ie,Fe;const{user:i,isAdmin:l,isBrokerageManager:o}=_s(),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,f]=j.useState([]),[g,x]=j.useState([]),[v,y]=j.useState(""),[b,w]=j.useState(""),[S,A]=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({}),Z=l||o;j.useEffect(()=>{s&&i&&(l?X():ae())},[s,i,l]),j.useEffect(()=>{s||(f([]),x([]),y(""),w(""),A(""),O("agents"),W("all"))},[s]);const X=async()=>{if(i){I(!0);try{const{data:Ne,error:Be}=await q.from("brokerages").select("id, name").order("name");if(Be)throw Be;const Se=1e3,Ae={};let Ce=0,qe=!0;for(;qe;){const{data:ht,error:Qe}=await q.from("profiles").select("brokerage_id").range(Ce*Se,(Ce+1)*Se-1);if(Qe)throw Qe;ht==null||ht.forEach(at=>{at.brokerage_id&&(Ae[at.brokerage_id]=(Ae[at.brokerage_id]||0)+1)}),qe=(ht==null?void 0:ht.length)===Se,Ce++}h((Ne==null?void 0:Ne.map(ht=>({...ht,agent_count:Ae[ht.id]||0})))||[]);const ze=[];for(Ce=0,qe=!0;qe;){const{data:ht,error:Qe}=await q.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Ce*Se,(Ce+1)*Se-1);if(Qe)throw Qe;ht&&ze.push(...ht),qe=(ht==null?void 0:ht.length)===Se,Ce++}const Ve={};for(Ce=0,qe=!0;qe;){const{data:ht,error:Qe}=await q.from("user_roles").select("user_id, role").range(Ce*Se,(Ce+1)*Se-1);if(Qe)throw Qe;ht==null||ht.forEach(at=>{Ve[at.user_id]||(Ve[at.user_id]=[]),Ve[at.user_id].push(at.role)}),qe=(ht==null?void 0:ht.length)===Se,Ce++}G(Ve),d(ze.map(ht=>{var Qe;return{id:ht.id,name:ht.name,email:ht.email,brokerage_name:((Qe=ht.brokerages)==null?void 0:Qe.name)||"No Brokerage",roles:Ve[ht.id]||[],created_at:ht.created_at}}))}catch(Ne){console.error("Error loading data:",Ne),ne.error("Failed to load agents and brokerages")}finally{I(!1)}}},ae=async()=>{if(i){I(!0);try{const{data:Ne}=await q.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(Ne!=null&&Ne.brokerage_id)){ne.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Be,error:Se}=await q.from("profiles").select("id, name, email").eq("brokerage_id",Ne.brokerage_id).neq("id",i.id).order("name");if(Se)throw Se;d(Be||[])}catch(Ne){console.error("Error loading agents:",Ne),ne.error("Failed to load agents")}finally{I(!1)}}},le=c.filter(Ne=>{var Se;const Be=Ne.name.toLowerCase().includes(v.toLowerCase())||Ne.email.toLowerCase().includes(v.toLowerCase())||((Se=Ne.brokerage_name)==null?void 0:Se.toLowerCase().includes(v.toLowerCase()));if(l&&U!=="all"&&U!=="newest"){const Ae=V[Ne.id]||[];return Be&&Ae.includes(U)}return Be}).sort((Ne,Be)=>U==="newest"?(Be.created_at||"").localeCompare(Ne.created_at||""):0),re=u.filter(Ne=>Ne.name.toLowerCase().includes(b.toLowerCase())),te=()=>{m.length===le.length?f([]):f(le.map(Ne=>Ne.id))},J=()=>{g.length===re.length?x([]):x(re.map(Ne=>Ne.id))},ce=Ne=>{if(!Z){f([Ne]);return}f(Be=>Be.includes(Ne)?Be.filter(Se=>Se!==Ne):[...Be,Ne])},ve=Ne=>{x(Be=>Be.includes(Ne)?Be.filter(Se=>Se!==Ne):[...Be,Ne])},fe=async()=>{if(!(m.length>0||g.length>0)){ne.error("Please select at least one agent or brokerage to share with");return}R(!0);try{const{data:Be,error:Se}=await q.functions.invoke("send-share-notification",{body:{recipientIds:m,brokerageIds:g,resourceType:n,resourceId:r,resourceTitle:a,message:S.trim()||void 0}});if(Se)throw Se;const Ae=(Be==null?void 0:Be.sharesCreated)||m.length;ne.success(`Shared with ${Ae} agent${Ae!==1?"s":""}`),t(!1)}catch(Be){console.error("Error sharing resource:",Be),ne.error("Failed to share resource")}finally{R(!1)}},ue=Ne=>Ne.split(" ").map(Be=>Be[0]).join("").toUpperCase().slice(0,2),be=Ne=>{const Be=V[Ne]||[];return Be.includes("admin")?e.jsx($e,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Be.includes("brokerage_manager")?e.jsx($e,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},Ee=m.length+g.length,ke=U!=="all"&&U!=="newest"?le.length:null;return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{className:"flex-shrink-0",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(Er,{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(pa,{value:D,onValueChange:O,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(ga,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(Xt,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),m.length>0&&e.jsx($e,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:m.length})]}),e.jsxs(Xt,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(wi,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),g.length>0&&e.jsx($e,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:g.length})]})]}),e.jsxs(Qt,{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:v,onChange:Ne=>y(Ne.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:U,onValueChange:W,children:[e.jsxs(us,{className:"w-[180px]",children:[e.jsx(Sw,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(fs,{placeholder:"Filter by role"})]}),e.jsx(hs,{children:_Be.map(Ne=>e.jsx(Ge,{value:Ne.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne.icon,{className:"h-4 w-4"}),e.jsx("span",{children:Ne.label})]})},Ne.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:le.length===0,children:[e.jsx(Yn,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===le.length&&le.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[ke!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[ke," ",(Ie=_Be.find(Ne=>Ne.value===U))==null?void 0:Ie.label]}),e.jsxs("span",{className:"font-medium",children:[m.length," selected"]})]})]}),e.jsx(go,{className:"h-[300px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):le.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Yn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:U!=="all"?`No ${(Fe=_Be.find(Ne=>Ne.value===U))==null?void 0:Fe.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:le.map(Ne=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(Ne.id)?"bg-accent":""}`,onClick:()=>ce(Ne.id),children:[e.jsx(ai,{checked:m.includes(Ne.id),onCheckedChange:()=>ce(Ne.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(Ne.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:Ne.name}),be(Ne.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ne.email,Ne.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",Ne.brokerage_name]})]})]})]},Ne.id))})})]}),e.jsxs(Qt,{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:Ne=>w(Ne.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:re.length===0,children:[e.jsx(wi,{className:"h-3.5 w-3.5 mr-1.5"}),g.length===re.length&&re.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(go,{className:"h-[250px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):re.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(wi,{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:re.map(Ne=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${g.includes(Ne.id)?"bg-accent":""}`,onClick:()=>ve(Ne.id),children:[e.jsx(ai,{checked:g.includes(Ne.id),onCheckedChange:()=>ve(Ne.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(wi,{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:Ne.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ne.agent_count," agent",Ne.agent_count!==1?"s":""]})]})]},Ne.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:v,onChange:Ne=>y(Ne.target.value),className:"pl-9"})]}),Z&&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:le.length===0,children:[e.jsx(Yn,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===le.length&&le.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[m.length," selected"]})]}),e.jsx(go,{className:"h-[300px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):le.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Yn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:le.map(Ne=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(Ne.id)?"bg-accent":""}`,onClick:()=>ce(Ne.id),children:[e.jsx(ai,{checked:m.includes(Ne.id),onCheckedChange:()=>ce(Ne.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(Ne.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:Ne.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ne.email})]})]},Ne.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:Ne=>A(Ne.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:fe,disabled:Ee===0||P,children:P?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function mK({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=j.useState(!1),{user:c}=_s();return c?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(Hd,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(Msn,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function Psn(){const{eventId:s}=Wi(),t=Zn(),{user:n}=_s(),[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:A}=await q.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(A||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),ne.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),ne.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;ne.success("Successfully cancelled registration"),l(null),c(A=>A-1)}else{const{data:S,error:A}=await q.functions.invoke("zoom-register",{body:{event_id:r.id}});if(A)throw A;ne.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),ne.error(i?"Failed to cancel registration":"Failed to register for event")}finally{m(!1)}}},x=w=>{var S,A,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]:(A=w.split("v=")[1])==null?void 0:A.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 v=R4(new Date(r.event_date)),y=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(Va,{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"}),v&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx($e,{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(mK,{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(ef,{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(je,{children:e.jsxs(Le,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ea,{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:ose(new Date(r.event_date))})]})]}),r.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Yn,{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(Wl,{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:[!v&&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(Ir,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:g,disabled:h,children:[h?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx($,{className:"w-full gap-2",onClick:g,disabled:h||(y??!1),children:h?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):y?"Event Full":"Register Now"})}),v&&i&&e.jsxs($,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(r.zoom_link,"_blank"),children:[e.jsx(Ir,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const Isn=[{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 Lsn(){const{isAdmin:s}=_s(),t=Isn.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(aP,{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 LTe=[{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:pn,color:"bg-emerald-500/15 text-emerald-600"},{id:"social-content",title:"Create Social Content",blurb:"Reels, posts and captions",icon:gm,color:"bg-rose-500/15 text-rose-600"},{id:"open-house",title:"Host an Open House",blurb:"Promote, sign in and follow up",icon:WN,color:"bg-sky-500/15 text-sky-600"},{id:"new-business",title:"Generate New Business",blurb:"Leads, expireds and by-owner sellers",icon:Zl,color:"bg-amber-500/15 text-amber-600"},{id:"brand",title:"Build My Brand",blurb:"Your card, site, reviews and presence",icon:yd,color:"bg-teal-500/15 text-teal-600"}];LTe.reduce((s,t)=>({...s,[t.id]:t}),{});const Rsn=[{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"}],dHt=[{id:"scheduler",name:"LevelUp Scheduler",description:"Share your booking link, sync Google Calendar and let clients book you",icon:Su,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:fa,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:jv,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:vb,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:Qr,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:_x,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:wn,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:pn,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:nf,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:Zr,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:_f,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:Uq,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:XN,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:nf,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:Gl,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:vb,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:wn,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:Jq,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"]}],e_t=dHt.reduce((s,t)=>({...s,[t.id]:t}),{}),Dsn={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"]}},Fsn={AgentReview:"Replaced by the new built-in Reviews app"};function Osn(s){return Dsn[s]??{goals:[],categories:[],keywords:[]}}const Wnt=[{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:WN,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:Yn,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"}]}],Y7=Wnt.reduce((s,t)=>({...s,[t.id]:t}),{});function zsn({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 Bsn({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(jc,{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(A0,{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 u7({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(Bsn,{item:a,isFavorite:t(a),onOpen:n,onToggleFavorite:r},a.key))})}const $sn="bg-primary/10 text-primary";function lie(){const{user:s,isAdmin:t}=_s(),n=bC(),r=Zn(),{hasAccess:a}=pLe(),{isFeatureEnabled:i}=Aae(),[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),[v,y]=j.useState([]),[b,w]=j.useState(""),S=j.useCallback(async()=>{if(s!=null&&s.id)try{const[{data:G},{data:Z},{data:X},{data:ae},{data:le},{data:re},{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(be=>be.tag);x((le||[]).some(be=>be.is_active&&be.mls_provider_id&&!be.no_mls_mode)),h(new Set((X||[]).map(be=>be.app_id))),f(new Set((ae||[]).map(be=>be.tool_id)));const ce=(Z||[]).filter(be=>be.app_id==="newsletter_studio"?!1:!be.required_tags||be.required_tags.length===0?!0:be.required_tags.some(Ee=>J.includes(Ee)));o(ce.sort((be,Ee)=>be.name==="LevelUp Members Portal"?-1:Ee.name==="LevelUp Members Portal"?1:0));const ve=new Set,fe=[];for(const be of re||[])if(!(!be.app_id||ve.has(be.app_id))&&(ve.add(be.app_id),fe.push({appId:be.app_id,name:be.app_name,at:be.launched_at}),fe.length>=8))break;y(fe);const ue=te==null?void 0:te.name;w(ue?ue.trim().split(" ")[0]:"")}catch(G){console.error("Error loading app catalog:",G),ne.error("Failed to load apps")}finally{d(!1)}},[s==null?void 0:s.id]);j.useEffect(()=>{S()},[S]);const A=j.useMemo(()=>{const G=le=>{if(!n.isRestricted)return null;const re=gCs(le);return re&&!n.hasFeature(re)?re:null},Z=dHt.filter(le=>!(le.adminOnly&&!t||le.requiresLeadSiteMLS&&!g&&!t||le.requiresWeeklyReels&&!a||le.featureFlag&&!i(le.featureFlag)&&!t)).map(le=>({key:`tool:${le.id}`,kind:"tool",id:le.id,name:le.name,description:le.description,icon:le.icon,color:le.color,isNew:le.isNew,beta:le.beta,popular:le.popular,goals:le.goals,categories:le.categories,keywords:le.keywords,lockedFeature:G(le.id),tool:le})),X={AgentReview:"marketing_studio",SigFlow:"marketing_studio",Staging_Studio:"marketing_studio",social_autopilot:"social",newsletter_studio:"newsletter"},ae=l.map(le=>{const re=Osn(le.app_id),te=X[le.app_id];return{key:`app:${le.app_id}`,kind:"app",id:le.app_id,name:le.name,description:le.description,icon:le.icon,color:$sn,goals:re.goals,categories:re.categories,keywords:re.keywords,lockedFeature:n.isRestricted&&te&&!n.hasFeature(te)?te:null,deprecated:!!Fsn[le.app_id],tile:le}});return[...Z,...ae]},[l,t,g,a,i,n.isRestricted,n.features]),E=j.useCallback(G=>{var Z;return G.kind==="tool"?m.has(G.id):u.has(((Z=G.tile)==null?void 0:Z.id)??"")},[m,u]),I=j.useMemo(()=>A.filter(E),[A,E]),P=j.useMemo(()=>{const G=new Map(A.map(Z=>[Z.id,Z]));return v.map(Z=>G.get(Z.appId)).filter(Boolean)},[A,v]),R=j.useMemo(()=>A.filter(G=>G.kind==="app"),[A]),D=j.useCallback(async(G,Z)=>{try{await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:G,app_name:Z,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 Z=window.open("about:blank","_blank");try{const{data:ae,error:le}=await q.auth.getSession();if(le||!ae.session){Z==null||Z.close(),ne.error("Session expired. Please refresh the page and try again.");return}await D(G.app_id,G.name);const{data:re,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;re!=null&&re.redirect_url?Z&&!Z.closed?(Z.location.href=re.redirect_url,(X=Z.focus)==null||X.call(Z)):window.location.assign(re.redirect_url):(Z==null||Z.close(),ne.error("Launch link unavailable"))}catch(ae){Z==null||Z.close(),console.error("Error launching app:",ae),ne.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 Z=E(G),X=G.kind==="tool"?"user_tool_favorites":"user_favorites",ae=G.kind==="tool"?"tool_id":"app_id",le=G.kind==="tool"?G.id:(te=G.tile)==null?void 0:te.id;if(!le)return;const re=G.kind==="tool"?f:h;re(J=>{const ce=new Set(J);return Z?ce.delete(le):ce.add(le),ce});try{if(Z){const{error:J}=await q.from(X).delete().eq("user_id",s.id).eq(ae,le);if(J)throw J}else{const{error:J}=await q.from(X).insert({user_id:s.id,[ae]:le});if(J)throw J}}catch(J){console.error("Error toggling favorite:",J),ne.error("Failed to update favorites"),re(ce=>{const ve=new Set(ce);return Z?ve.add(le):ve.delete(le),ve})}},[E,s==null?void 0:s.id]),V=j.useCallback((G,Z=A)=>{const X=G.trim().toLowerCase();if(!X)return Z;const ae=X.split(/\s+/);return Z.filter(le=>{if(le.deprecated)return!1;const re=[le.name,le.description,...le.keywords,...le.categories,...le.goals].join(" ").toLowerCase();return ae.every(te=>re.includes(te))||re.includes(X)})},[A]);return{loading:c,items:A,favoriteItems:I,recentItems:P,connectedItems:R,recent:v,firstName:b,isFavorite:E,toggleFavorite:W,openItem:U,search:V,reload:S}}function wBe(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 H6e(s){const t=Y7[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 G6e(){const{user:s}=_s(),[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(wBe))}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:v}=await q.from("workflow_runs").insert({user_id:s.id,workflow_id:m,run_name:f.trim()||((g=Y7[m])==null?void 0:g.title)||"Untitled"}).select("*").single();if(v)throw v;const y=wBe(x);return n(b=>[y,...b]),y}catch(x){return console.error("Error starting workflow:",x),ne.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(v=>v.map(y=>y.id===m?wBe({...y,...g}):y));const{error:x}=await q.from("workflow_runs").update(g).eq("id",m);x&&(console.error("Error updating workflow run:",x),ne.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 v=Y7[m.workflow_id],y=v?v.steps.every(b=>x[b.key]):!1;await o(m.id,{step_state:x,status:y?"completed":"in_progress",completed_at:y?new Date().toISOString():null}),y&&m.status!=="completed"&&ne.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),ne.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 Usn(){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 qsn(){const s=Zn(),{items:t,firstName:n,recentItems:r,favoriteItems:a,isFavorite:i,toggleFavorite:l,openItem:o,search:c}=lie(),{isAdmin:d}=_s(),{activeRuns:u}=G6e(),h=d?u:[],[m,f]=j.useState(""),g=j.useMemo(()=>m.trim()?c(m).slice(0,8):[],[m,c]),x=j.useMemo(()=>{const y=new Set(r.map(S=>S.id)),b=[],w=S=>{for(const A of S){if(b.length>=4)break;b.some(E=>E.key===A.key)||b.push(A)}};return w(a.filter(S=>!y.has(S.id))),w(t.filter(S=>S.isNew&&!y.has(S.id))),w(t.filter(S=>S.popular&&!y.has(S.id))),b},[t,a,r]),v=y=>s(`/apps/browse?goal=${y.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:[Usn(),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:y=>f(y.target.value),onKeyDown:y=>{y.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(y=>{const b=typeof y.icon=="string"?null:y.icon;return e.jsxs("button",{type:"button",onClick:()=>o(y),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",y.color),children:b?e.jsx(b,{className:"h-5 w-5"}):y.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:y.name}),e.jsx("span",{className:"block text-sm text-muted-foreground truncate",children:y.description})]})]},y.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:LTe.map(y=>e.jsx(zsn,{goal:y,onSelect:v},y.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(ca,{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(y=>{const b=Y7[y.workflow_id],w=H6e(y);return e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${y.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:y.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(Qa,{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}%`}})})]},y.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(y=>{const b=typeof y.icon=="string"?null:y.icon;return e.jsxs("button",{type:"button",onClick:()=>o(y),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",y.color),children:b?e.jsx(b,{className:"h-5 w-5"}):y.icon}),e.jsx("span",{className:"block font-medium text-sm text-foreground truncate",children:y.name}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Open again"})]},y.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(wn,{className:"h-4 w-4 text-primary"})," Recommended for you"]}),e.jsx("div",{className:"space-y-3",children:x.map(y=>{const b=typeof y.icon=="string"?null:y.icon;return e.jsxs("button",{type:"button",onClick:()=>o(y),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",y.color),children:b?e.jsx(b,{className:"h-5 w-5"}):y.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:y.name}),e.jsx("span",{className:"block text-sm text-muted-foreground line-clamp-2",children:y.description})]})]},y.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(u7,{items:a.slice(0,6),isFavorite:i,onOpen:o,onToggleFavorite:l})]})]})}function uHt({workflow:s,activeRun:t,onStart:n,onResume:r}){const a=s.icon,i=t?H6e(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(Vr,{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(Qa,{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(Qa,{className:"h-4 w-4 ml-1"})]})})]})}function hHt({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(Os,{open:!!s,onOpenChange:c=>!c&&t(),children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx($s,{children:s==null?void 0:s.title}),e.jsxs(Er,{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(Nr,{children:[e.jsx($,{variant:"outline",onClick:t,disabled:i,children:"Cancel"}),e.jsx($,{onClick:o,disabled:i,children:i?"Starting…":"Start workflow"})]})]})})}function Vsn(){const s=Zn(),[t,n]=Nc(),{items:r,isFavorite:a,toggleFavorite:i,openItem:l,search:o}=lie(),{isAdmin:c}=_s(),{activeRuns:d,startRun:u}=G6e(),h=t.get("goal"),m=t.get("category")??null,[f,g]=j.useState(t.get("q")??""),[x,v]=j.useState(null);j.useEffect(()=>{g(t.get("q")??"")},[t]);const y=(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:LTe.map(E=>({goal:E,apps:r.filter(I=>I.goals.includes(E.id))})).filter(E=>E.apps.length>0),[r,h,m,f]),A=h?LTe.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),y("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"}),Rsn.map(E=>e.jsx("button",{type:"button",onClick:()=>y("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))]})}),A&&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:()=>y("goal",null),className:"text-sm font-medium px-3 py-1.5 rounded-full bg-primary/10 text-primary",children:[A.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:Wnt.map(E=>e.jsx(uHt,{workflow:E,activeRun:d.find(I=>I.workflow_id===E.id),onStart:v,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(u7,{items:I,isFavorite:a,onOpen:l,onToggleFavorite:i})]},E.id)):w.length>0?e.jsx(u7,{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(hHt,{workflow:x,onClose:()=>v(null),onStart:async(E,I)=>{const P=await u(E.id,I);v(null),P&&s(`/apps/workflows/${P.id}`)}})]})}function Hsn(){const s=Zn(),{favoriteItems:t,recentItems:n,connectedItems:r,isFavorite:a,toggleFavorite:i,openItem:l}=lie(),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(A0,{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(A0,{className:"h-4 w-4 text-primary"})," Favorites"]}),e.jsx(u7,{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(ca,{className:"h-4 w-4 text-muted-foreground"})," Recently used"]}),e.jsx(u7,{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(Dj,{className:"h-4 w-4 text-muted-foreground"})," Activated for your account"]}),e.jsx(u7,{items:r,isFavorite:a,onOpen:l,onToggleFavorite:i})]})]})}function Gsn(){const{connectedItems:s,isFavorite:t,toggleFavorite:n,openItem:r}=lie();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(nu,{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(u7,{items:s,isFavorite:t,onOpen:r,onToggleFavorite:n})]})}function Wsn(){const s=Zn(),{activeRuns:t,completedRuns:n,startRun:r,reopenRun:a,deleteRun:i}=G6e(),[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=Y7[c.workflow_id],u=H6e(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:Wnt.map(c=>e.jsx(uHt,{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(Vr,{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=Y7[c.workflow_id])==null?void 0:d.title})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>a(c),children:[e.jsx(Sx,{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(qn,{className:"h-4 w-4 text-muted-foreground"})})]},c.id)})})]}),e.jsx(hHt,{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 Ksn(){const{runId:s}=Wi(),t=Zn(),{runs:n,loading:r,setStep:a,renameRun:i,reopenRun:l,deleteRun:o}=G6e(),{items:c,openItem:d}=lie(),[u,h]=j.useState(!1),[m,f]=j.useState(""),g=j.useMemo(()=>n.find(w=>w.id===s),[n,s]),x=g?Y7[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 v=H6e(g),y=x.icon,b=w=>{if(!w)return;const S=c.find(E=>E.kind==="tool"&&E.id===w);if(S){d(S);return}const A=e_t[w];A&&t(A.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(Va,{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(y,{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(pi,{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:[v.touched," of ",v.total," steps done"]}),e.jsxs("span",{children:[v.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:`${v.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(Vr,{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 A=g.step_state[w.key],E=w.toolId?e_t[w.toolId]:void 0,I=A==="done",P=A==="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(ma,{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(Ir,{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(ma,{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(ZJ,{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(qn,{className:"h-4 w-4 mr-1"})," Delete this workflow"]})})]})}const Ysn=()=>{const{isAdmin:s}=_s();return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Lsn,{}),e.jsxs(mG,{children:[e.jsx(rs,{index:!0,element:e.jsx(qsn,{})}),e.jsx(rs,{path:"browse",element:e.jsx(Vsn,{})}),e.jsx(rs,{path:"my-apps",element:e.jsx(Hsn,{})}),e.jsx(rs,{path:"connected",element:e.jsx(Gsn,{})}),s&&e.jsx(rs,{path:"workflows",element:e.jsx(Wsn,{})}),s&&e.jsx(rs,{path:"workflows/:runId",element:e.jsx(Ksn,{})}),e.jsx(rs,{path:"*",element:e.jsx(eu,{to:"/apps",replace:!0})})]})]})})},Zsn=()=>{var w;const s=Zn(),{isAdmin:t}=_s(),[n,r]=j.useState(""),[a,i]=j.useState("all"),[l,o]=j.useState("all"),[c,d]=j.useState("grid"),{data:u=[]}=st({queryKey:["template-categories"],queryFn:async()=>{const{data:S,error:A}=await q.from("template_categories").select("*").order("name");if(A)throw A;return S}}),{data:h=[]}=st({queryKey:["template-types"],queryFn:async()=>{const{data:S,error:A}=await q.from("template_types").select("*").order("name");if(A)throw A;return S}}),{data:m=[],isLoading:f}=st({queryKey:["canva-templates",t],queryFn:async()=>{const{data:S,error:A}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(A)throw A;const{data: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:le,error:re}=await G().range(X,X+1e3-1);if(re)throw re;if(!le||le.length===0||(ae.push(...le),le.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(Z=>{W.set(Z.resource_id,(W.get(Z.resource_id)||0)+1)}),(S||[]).map(G=>({...G,links:(E||[]).filter(Z=>Z.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 A=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 A&&E&&I}),x=()=>{r(""),i("all"),o("all")},v=n||a!=="all"||l!=="all",y=(w=[...m].sort((S,A)=>new Date(A.publish_date||A.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(ei,{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(je,{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===y&&e.jsx($e,{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(Le,{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:Fte(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:[v&&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(Xf,{className:"h-4 w-4"})}),e.jsx($,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(E0,{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,A)=>e.jsx(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx(xn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(xn,{className:"h-5 w-3/4 mb-2"}),e.jsx(xn,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xn,{className:"h-5 w-16"}),e.jsx(xn,{className:"h-5 w-20"})]})]})},A))}),!f&&g.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:v?"No templates match your filters":"No templates available yet"}),v&&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(je,{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===y&&e.jsx($e,{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($e,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(Sd,{className:"h-3 w-3"}),S.links.length]})})]}),e.jsxs(Le,{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:Fte(S.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[S.category&&e.jsx($e,{variant:"secondary",className:"text-xs",children:S.category.name}),S.type&&e.jsx($e,{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($y,{className:"h-3.5 w-3.5"}),S.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ah,{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(Ta,{className:"h-3.5 w-3.5"}),S.viewsCount]})]}),e.jsxs($,{size:"sm",className:"w-full gap-2",onClick:A=>{A.stopPropagation(),b(S.id)},children:[e.jsx(Ir,{className:"h-4 w-4"}),"View Template"]})]})]},S.id))})]})})},Xsn=()=>{const{templateId:s}=Wi(),t=Zn(),{user:n,isAdmin:r}=_s(),{toast:a}=Bi(),i=Zt(),{trackEngagement:l}=dK(),[o,c]=j.useState(""),{data:d,isLoading:u}=st({queryKey:["template-detail",s],queryFn:async()=>{const{data:S,error:A}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(A)throw A;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=[]}=st({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:S,error:A}=await q.from("resource_kit_templates").select("kit_id, resource_kits:kit_id(id, name, featured_image_url)").eq("template_id",s);if(A)throw A;return(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=[]}=st({queryKey:["template-likes",s],queryFn:async()=>{const{data:S,error:A}=await q.from("template_likes").select("*").eq("template_id",s);if(A)throw A;return S},enabled:!!s}),{data:f=[]}=st({queryKey:["template-comments",s],queryFn:async()=>{const{data:S,error:A}=await q.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(A)throw A;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=mt({mutationFn:async S=>{const{error:A}=await q.from("template_comments").insert({template_id:s,user_id:n.id,content:S});if(A)throw A},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=mt({mutationFn:async S=>{const{error:A}=await q.from("template_comments").delete().eq("id",S);if(A)throw A},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),v=mt({mutationFn:async()=>{const S=m.find(A=>A.user_id===(n==null?void 0:n.id));if(S){const{error:A}=await q.from("template_likes").delete().eq("id",S.id);if(A)throw A}else{const{error:A}=await q.from("template_likes").insert({template_id:s,user_id:n.id});if(A)throw A}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),y=m.some(S=>S.user_id===(n==null?void 0:n.id)),b=S=>S.split(" ").map(A=>A[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(br,{to:"/templates",children:[e.jsx(Va,{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($e,{variant:"secondary",children:d.category.name}),d.type&&e.jsx($e,{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(br,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(pi,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(mK,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs($,{variant:y?"default":"outline",className:"gap-2 rounded-full",onClick:()=>v.mutate(),disabled:!n||v.isPending,children:[e.jsx($y,{className:`h-4 w-4 ${y?"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(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Sd,{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(Ir,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),d.video_url&&e.jsx(je,{children:e.jsx(Le,{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(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Qr,{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(Qr,{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(ji,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),h.length>0&&e.jsx(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ym,{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(ym,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:S.name})]},S.id))})]})}),e.jsx(Vc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ah,{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(Zr,{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(je,{children:e.jsx(Le,{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(je,{children:e.jsx(Le,{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:hu(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(qn,{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(Sd,{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(br,{to:"/templates",children:"Back to Templates"})})]})})},t_t=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=j6e(s);return e.jsxs(je,{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(wn,{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($e,{className:"shadow-sm",children:"Featured"}),t&&e.jsxs($e,{variant:"secondary",className:"shadow-sm",children:[e.jsx(Vr,{className:"mr-1 h-3 w-3"})," Enrolled"]})]})]}),e.jsxs(Le,{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(ca,{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(Wc,{className:"h-3.5 w-3.5"}),"Starts ",th(s.kickoff_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Yn,{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":Ng(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 ",ase(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${th(s.charge_at)}`:""]}):null]}),e.jsx($,{asChild:!0,size:"sm",children:e.jsxs(br,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(Qa,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},Qsn=()=>{const{data:s=[],isLoading:t}=TUt(),{data:n=[]}=Jst(),r=new Set(n.filter(l=>AG(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(xn,{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(t_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(je,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(wn,{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(t_t,{program:l,enrolled:!1},l.id))})]})]})]})})},Jsn=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},enn=({url:s,headline:t,posterUrl:n})=>{const[r,a]=j.useState(!1),i=(s||"").trim();if(!i)return null;const l=Jsn(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(ef,{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 tnn=Object.defineProperty,cie=(s,t)=>tnn(s,"name",{value:t,configurable:!0}),Knt="Collapsible",[snn,mHt]=ep(Knt),[nnn,Ynt]=snn(Knt),rnn=j.forwardRef(cie(function(t,n){const{__scopeCollapsible:r,open:a,defaultOpen:i,disabled:l,onOpenChange:o,...c}=t,[d,u]=dy({prop:a,defaultProp:i??!1,onChange:o,caller:Knt});return e.jsx(nnn,{scope:r,disabled:l,contentId:cy(),open:d,onOpenToggle:j.useCallback(()=>u(h=>!h),[u]),children:e.jsx(Ei.div,{"data-state":W6e(d),"data-disabled":l?"":void 0,...c,ref:n})})},"Collapsible")),ann="CollapsibleTrigger",fHt=j.forwardRef(cie(function(t,n){const{__scopeCollapsible:r,...a}=t,i=Ynt(ann,r);return e.jsx(Ei.button,{type:"button","aria-controls":i.open?i.contentId:void 0,"aria-expanded":i.open||!1,"data-state":W6e(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...a,ref:n,onClick:Ra(t.onClick,i.onOpenToggle)})},"CollapsibleTrigger")),pHt="CollapsibleContent",gHt=j.forwardRef(cie(function(t,n){const{forceMount:r,...a}=t,i=Ynt(pHt,t.__scopeCollapsible);return e.jsx(my,{present:r||i.open,children:({present:l})=>e.jsx(inn,{...a,ref:n,present:l})})},"CollapsibleContent")),inn=j.forwardRef(cie(function(t,n){const{__scopeCollapsible:r,present:a,children:i,...l}=t,o=Ynt(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,v=o.open||c,y=j.useRef(v),b=j.useRef(void 0);return j.useEffect(()=>{const w=requestAnimationFrame(()=>y.current=!1);return()=>cancelAnimationFrame(w)},[]),Af(()=>{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,y.current||(w.style.transitionDuration=b.current.transitionDuration,w.style.animationName=b.current.animationName),d(a)}},[o.open,a]),e.jsx(Ei.div,{"data-state":W6e(o.open),"data-disabled":o.disabled?"":void 0,id:o.contentId,hidden:!v,...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:v&&i})},"CollapsibleContentImpl"));function W6e(s){return s?"open":"closed"}cie(W6e,"getState");var xHt=rnn,onn=fHt,lnn=gHt,cnn=Object.defineProperty,f2=(s,t)=>cnn(s,"name",{value:t,configurable:!0}),o3="Accordion",dnn=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[Znt,unn,hnn]=SB(o3),[K6e,qkr]=ep(o3,[hnn,mHt]),Xnt=mHt(),mnn=j.forwardRef(f2(function(t,n){const{type:r,...a}=t,i=a,l=a;return e.jsx(Znt.Provider,{scope:t.__scopeAccordion,children:r==="multiple"?e.jsx(xnn,{...l,ref:n}):e.jsx(gnn,{...i,ref:n})})},"Accordion")),[yHt,fnn]=K6e(o3),[vHt,pnn]=K6e(o3,{collapsible:!1}),gnn=j.forwardRef(f2(function(t,n){const{value:r,defaultValue:a,onValueChange:i=f2(()=>{},"onValueChange"),collapsible:l=!1,...o}=t,[c,d]=dy({prop:r,defaultProp:a??"",onChange:i,caller:o3});return e.jsx(yHt,{scope:t.__scopeAccordion,value:j.useMemo(()=>c?[c]:[],[c]),onItemOpen:d,onItemClose:j.useCallback(()=>l&&d(""),[l,d]),children:e.jsx(vHt,{scope:t.__scopeAccordion,collapsible:l,children:e.jsx(bHt,{...o,ref:n})})})},"AccordionImplSingle")),xnn=j.forwardRef(f2(function(t,n){const{value:r,defaultValue:a,onValueChange:i=f2(()=>{},"onValueChange"),...l}=t,[o,c]=dy({prop:r,defaultProp:a??[],onChange:i,caller:o3}),d=j.useCallback(h=>c((m=[])=>[...m,h]),[c]),u=j.useCallback(h=>c((m=[])=>m.filter(f=>f!==h)),[c]);return e.jsx(yHt,{scope:t.__scopeAccordion,value:o,onItemOpen:d,onItemClose:u,children:e.jsx(vHt,{scope:t.__scopeAccordion,collapsible:!0,children:e.jsx(bHt,{...l,ref:n})})})},"AccordionImplMultiple")),[ynn,Y6e]=K6e(o3),bHt=j.forwardRef(f2(function(t,n){const{__scopeAccordion:r,disabled:a,dir:i,orientation:l="vertical",...o}=t,c=j.useRef(null),d=Vo(c,n),u=unn(r),m=a3(i)==="ltr",f=Ra(t.onKeyDown,g=>{var R;if(!dnn.includes(g.key))return;const x=g.target,v=u().filter(D=>{var O;return!((O=D.ref.current)!=null&&O.disabled)}),y=v.findIndex(D=>D.ref.current===x),b=v.length;if(y===-1)return;g.preventDefault();let w=y;const S=0,A=b-1,E=f2(()=>{w=y+1,w>A&&(w=S)},"moveNext"),I=f2(()=>{w=y-1,w{m?o.onItemOpen(a):o.onItemClose(a)}})})},"AccordionItem")),_nn="AccordionHeader",wnn=j.forwardRef(f2(function(t,n){const{__scopeAccordion:r,...a}=t,i=Y6e(o3,r),l=Qnt(_nn,r);return e.jsx(Ei.h3,{"data-orientation":i.orientation,"data-state":Jnt(l.open),"data-disabled":l.disabled?"":void 0,...a,ref:n})},"AccordionHeader")),s_t="AccordionTrigger",jnn=j.forwardRef(f2(function(t,n){const{__scopeAccordion:r,...a}=t,i=Y6e(o3,r),l=Qnt(s_t,r),o=pnn(s_t,r),c=Xnt(r);return e.jsx(Znt.ItemSlot,{scope:r,children:e.jsx(onn,{"aria-disabled":l.open&&!o.collapsible||void 0,"data-orientation":i.orientation,id:l.triggerId,...c,...a,ref:n})})},"AccordionTrigger")),Nnn="AccordionContent",knn=j.forwardRef(f2(function(t,n){const{__scopeAccordion:r,...a}=t,i=Y6e(o3,r),l=Qnt(Nnn,r),o=Xnt(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 Jnt(s){return s?"open":"closed"}f2(Jnt,"getState");var Snn=mnn,Cnn=bnn,Ann=wnn,_Ht=jnn,wHt=knn;const BB=Snn,c6=j.forwardRef(({className:s,...t},n)=>e.jsx(Cnn,{ref:n,className:Pt("border-b",s),...t}));c6.displayName="AccordionItem";const d6=j.forwardRef(({className:s,children:t,...n},r)=>e.jsx(Ann,{className:"flex",children:e.jsxs(_Ht,{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(wl,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));d6.displayName=_Ht.displayName;const u6=j.forwardRef(({className:s,children:t,...n},r)=>e.jsx(wHt,{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})}));u6.displayName=wHt.displayName;const Enn=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=BGs(s),a=$Gs(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(YS,{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(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):i?e.jsx(ma,{className:"mr-2 h-4 w-4"}):e.jsx(YS,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},Tnn=()=>{const{slug:s}=Wi(),{data:t,isLoading:n}=Qst(s),{data:r}=MUt(t==null?void 0:t.id),{data:a}=ent(t==null?void 0:t.id),i=AG(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(xn,{className:"h-64 w-full rounded-xl"}),e.jsx(xn,{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(br,{to:"/programs",children:"Back to Programs"})})]})});const f=typeof r=="number"&&r<=0&&!i,{notOpenYet:g,closed:x,opensLabel:v}=j6e(t),y=!i&&(f||x||g),b=i?"Open your program":g?`Enrollment opens ${th(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(Dl,{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(enn,{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($e,{variant:"secondary",children:[t.duration_weeks,"-week program"]}),typeof r=="number"&&!i&&e.jsx($e,{variant:r<=10?"destructive":"outline",children:r>0?`${r} of ${t.capacity} seats left`:"Full"}),i&&e.jsxs($e,{children:[e.jsx(Vr,{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":Ng(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 ",ase(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:th(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(jv,{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:[OGe(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:th(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:!y,size:"lg",disabled:y,children:y?e.jsx("span",{children:b}):e.jsxs(br,{to:w,children:[b,e.jsx(Qa,{className:"ml-2 h-4 w-4"})]})}),e.jsx($,{asChild:!0,variant:"ghost",size:"lg",children:e.jsx(br,{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(Wc,{className:"h-3.5 w-3.5"}),"Enrollment opens ",v]}),e.jsx(Enn,{programId:t.id,opensLabel:v})]})]})]}),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,A)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(Vr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("p",{className:"text-sm",children:S})]},A))})]}),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,A)=>e.jsx(je,{className:"border-border/60",children:e.jsxs(Le,{className:"space-y-2 p-5",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-primary",children:["Phase ",A+1]}),e.jsx("h3",{className:"font-semibold",children:S.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:S.detail})]})},A))})]}),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,A)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-sm",children:[e.jsx(wn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),S]},A))})]}),(d.length>0||u.length>0)&&e.jsxs("section",{className:"grid gap-6 md:grid-cols-2",children:[d.length>0&&e.jsx(je,{className:"border-border/60",children:e.jsxs(Le,{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,A)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Vr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),S]},A))})]})}),u.length>0&&e.jsx(je,{className:"border-border/60",children:e.jsxs(Le,{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,A)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(ca,{className:"mt-0.5 h-4 w-4 shrink-0"}),S]},A))})]})})]}),h.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Questions"}),e.jsx(BB,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((S,A)=>e.jsxs(c6,{value:`faq-${A}`,children:[e.jsx(d6,{className:"text-left text-sm font-medium",children:S.q}),e.jsx(u6,{className:"text-sm text-muted-foreground",children:S.a})]},A))})]}),e.jsxs("section",{className:"rounded-2xl border border-border/60 bg-muted/40 p-6 text-center md:p-10",children:[e.jsx(fa,{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:!y,size:"lg",disabled:y,children:y?e.jsx("span",{children:b}):e.jsxs(br,{to:w,children:[b,e.jsx(Qa,{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(Yn,{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(Wc,{className:"h-3.5 w-3.5"}),"Enrollment opens ",v]}):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(Wc,{className:"h-3.5 w-3.5"}),"Enrollment closes ",th(t.enrollment_close_at)]}):null)]})]})]})},yde=["Your business","Your content","Your goals","Reserve your seat"],Mnn=()=>{const{slug:s}=Wi(),t=Zn(),[n,r]=Nc(),{user:a}=_s(),{data:i,isLoading:l}=Qst(s),{data:o}=MUt(i==null?void 0:i.id),{data:c,refetch:d}=ent(i==null?void 0:i.id),{data:u}=PUt(i==null?void 0:i.id),h=xGs(),m=yGs(),f=CGs(),g=AGs(),[x,v]=j.useState(0),[y,b]=j.useState(!1),[w,S]=j.useState(!1),[A,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({}),Z=j.useRef(!1),X=(ze,Ve)=>{W.current={...W.current,[ze]:Ve},G(W.current)};j.useEffect(()=>{Z.current||(u?(W.current={...u},G(W.current),Z.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,le=j.useMemo(()=>ise(i),[i]),re=ze=>gGs(le,ze),te=ze=>obt(le,ze)?e.jsx("span",{className:"text-destructive",children:" *"}):null,J=(ze,Ve)=>{const ht={...W.current.extra||{},[ze]:Ve};X("extra",ht)},ce=ze=>le.custom.filter((Ve,ht)=>ht%3===ze),ve=ze=>{const Ve=ce(ze);if(!Ve.length)return null;const ht=V.extra||{};return e.jsx("div",{className:"space-y-4",children:Ve.map(Qe=>e.jsxs("div",{className:"space-y-2",children:[Qe.type==="checkbox"?e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(ai,{id:Qe.id,checked:!!ht[Qe.id],onCheckedChange:at=>J(Qe.id,!!at)}),e.jsxs(ee,{htmlFor:Qe.id,className:"text-sm font-normal leading-relaxed",children:[Qe.label,Qe.required&&e.jsx("span",{className:"text-destructive",children:" *"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ee,{htmlFor:Qe.id,children:[Qe.label,Qe.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),Qe.type==="long_text"?e.jsx(Rs,{id:Qe.id,rows:3,value:ht[Qe.id]||"",onChange:at=>J(Qe.id,at.target.value)}):Qe.type==="select"?e.jsxs(ms,{value:ht[Qe.id]||"",onValueChange:at=>J(Qe.id,at),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsx(hs,{children:(Qe.options||[]).map(at=>e.jsx(Ge,{value:at,children:at},at))})]}):e.jsx(pe,{id:Qe.id,value:ht[Qe.id]||"",onChange:at=>J(Qe.id,at.target.value)})]}),Qe.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Qe.help})]},Qe.id))})},fe=ze=>{const Ve=W.current,ht=Ke=>Ke==null||Ke===""||Ke===!1,Qe=Xst.find(Ke=>Ke.step===ze&&obt(le,Ke.key)&&ht(Ke.key==="timezone"?Ve.timezone||(i==null?void 0:i.timezone):Ve[Ke.key]));if(Qe)return Qe.label;const at=Ve.extra||{},rt=ce(ze).find(Ke=>Ke.required&&ht(at[Ke.id]));return rt?rt.label:null},ue=()=>{if(x<=2){const ze=fe(x);if(ze)return ne.error(`Please answer: ${ze}`)}v(ze=>ze+1)},be=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 Ve=await f.mutateAsync({enrollmentId:ze,code:R});U(Ve),D(""),await d(),ne.success(`Code applied — you save ${Ng(Ve.discount_cents,i.currency)}`)}catch(ze){ne.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){ne.error(ze.message||"Could not remove the code")}},ke=n.get("setup"),Ie=n.get("session_id"),Fe=j.useRef(!1);j.useEffect(()=>{ke!=="success"||!Ie||!(c!=null&&c.id)||Fe.current||(Fe.current=!0,S(!0),(async()=>{const{data:ze,error:Ve}=await q.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:Ie}});if(S(!1),Ve||ze!=null&&ze.error||(ze==null?void 0:ze.success)===!1){ne.error((ze==null?void 0:ze.error)||(Ve==null?void 0:Ve.message)||"We could not confirm your card");return}await d(),n.delete("setup"),n.delete("session_id"),r(n,{replace:!0}),ne.success("Your seat is confirmed")})())},[ke,Ie,c==null?void 0:c.id]),j.useEffect(()=>{ke==="cancelled"&&ne.info("Checkout cancelled — your seat is held for a short while.")},[ke]);const Ne=j.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Be=async()=>{if(i){if(!A||i.payment_mode!=="free"&&!I){ne.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:Ve,error:ht}=await q.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:ze}});if(ht||Ve!=null&&Ve.error)throw new Error((Ve==null?void 0:Ve.error)||(ht==null?void 0:ht.message));if(Ve!=null&&Ve.free){await d(),ne.success("You're in"),t(`/programs/${i.slug}/workspace`);return}Ve!=null&&Ve.url&&(window.location.href=Ve.url)}catch(ze){ne.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(xn,{className:"h-10 w-1/2"}),e.jsx(xn,{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(br,{to:"/programs",children:"Back to Programs"})})]})});if(AG(c)&&Ne&&ke!=="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(Vr,{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 ${th(c==null?void 0:c.charge_scheduled_at)||"the program start date"}.`}),e.jsx($,{asChild:!0,size:"lg",children:e.jsx(br,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const Se=typeof o=="number"&&o<=0,{notOpenYet:Ae,closed:Ce,opensLabel:qe}=j6e(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(br,{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(br,{to:`/programs/${i.slug}`,children:[e.jsx(Va,{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?`${OGe(i.price_cents,i.currency,i.duration_weeks)}. Your card is saved today and charged once on ${th(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:yde[x]}),e.jsxs("span",{children:["Step ",x+1," of ",yde.length]})]}),e.jsx(Yi,{value:(x+1)/yde.length*100})]}),w&&e.jsx(je,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Le,{className:"flex items-center gap-3 p-4 text-sm",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin text-primary"}),"Confirming your card with Stripe…"]})}),e.jsx(je,{children:e.jsxs(Le,{className:"space-y-5 p-6",children:[x===0&&le.intro&&e.jsx("p",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm text-muted-foreground",children:le.intro}),x===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[re("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)})]}),re("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)})]}),re("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)})]}),re("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)})]})]}),re("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:[re("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))})]})]}),re("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)})]})]}),ve(0)]}),x===1&&e.jsxs(e.Fragment,{children:[re("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:[re("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))})]})]}),re("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))})]})]})]}),re("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)})]}),re("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)})]}),ve(1)]}),x===2&&e.jsxs(e.Fragment,{children:[re("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)})]}),re("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)})]}),re("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))})]})]}),ve(2),re("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:Ng(O.original_cents,i.currency)}),Ng(ae,i.currency)]}):Ng(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:OGe(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(Cp,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:O.code})," applied — you save ",Ng(O.discount_cents,i.currency)]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:Ee,disabled:g.isPending,children:[e.jsx(mr,{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(),be())}}),e.jsx($,{variant:"outline",onClick:be,disabled:!R.trim()||f.isPending||m.isPending,children:f.isPending||m.isPending?e.jsx(Ct,{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(jv,{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:th(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:A,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 — ${Ng(ae,i.currency)} for the ${ase(i.duration_weeks)} — on ${th(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 — ${Ng(ae,i.currency)} for the ${ase(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(Rm,{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:()=>v(ze=>Math.max(0,ze-1)),disabled:x===0||y,children:[e.jsx(Va,{className:"mr-1.5 h-4 w-4"})," Back"]}),xString(s).padStart(2,"0"),NBe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",Pnn=({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:${NBe(new Date)}`,`DTSTART:${NBe(d)}`,`DTEND:${NBe(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:jBe(i.hours)},{label:"Minutes",value:jBe(i.minutes)},{label:"Seconds",value:jBe(i.seconds)}];return e.jsxs(je,{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(Le,{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($e,{className:"gap-1.5",children:[e.jsx(wn,{className:"h-3.5 w-3.5"})," Your seat is confirmed"]}),e.jsxs($e,{variant:"outline",className:"gap-1.5",children:[e.jsx(ca,{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(vv,{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(Vr,{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))})]})]})},kBe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",Inn=(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:${kBe(new Date)}`,`DTSTART:${kBe(n)}`,`DTEND:${kBe(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)},Lnn={pdf:Qr,document:KN,checklist:Sv,template_link:o2,video:nf,external:nu},Rnn=()=>{var ce;const{slug:s}=Wi(),[t]=Nc(),{isAdmin:n}=_s(),r=n?t.get("as"):null,a=t.get("name")||"this member",i=n&&(t.get("preview")==="1"||!!r),{data:l,isLoading:o}=Qst(s),{data:c}=ent(l==null?void 0:l.id),{data:d,isLoading:u}=vGs(l==null?void 0:l.id,r),h=bGs(l==null?void 0:l.id),m=_Gs(l==null?void 0:l.id),f=wGs(l==null?void 0:l.id),g=jGs(l==null?void 0:l.id),{data:x}=PUt(l==null?void 0:l.id),v=!!(l!=null&&l.kickoff_at)&&new Date(l.kickoff_at).getTime()>Date.now(),[y,b]=j.useState(!1),[w,S]=j.useState({title:"",instagram_url:""}),[A,E]=j.useState({}),[I,P]=j.useState(null),R=j.useMemo(()=>{if(!(l!=null&&l.kickoff_at))return 1;const ve=Math.floor((Date.now()-new Date(l.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(ve/7)+1,1),l.duration_weeks)},[l]),D=new Set(((d==null?void 0:d.completions)||[]).map(ve=>ve.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(ve=>ve.week_number===R).length,V=((d==null?void 0:d.videoLogs)||[]).length,G=(l==null?void 0:l.weekly_video_goal)||3,Z=j.useMemo(()=>{const ve=new Map;((d==null?void 0:d.videoLogs)||[]).forEach(ue=>ve.set(ue.week_number,(ve.get(ue.week_number)||0)+1));let fe=0;for(let ue=R;ue>=1;ue--)if((ve.get(ue)||0)>=G)fe++;else if(ue!==R)break;return fe},[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(xn,{className:"h-28 w-full rounded-xl"}),e.jsx(xn,{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(br,{to:"/programs",children:"Back to Programs"})})]})});if(!AG(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(br,{to:`/programs/${l.slug}`,children:"View the program"})})]})});const X=((d==null?void 0:d.events)||[]).filter(ve=>new Date(ve.starts_at)>=new Date),ae=((d==null?void 0:d.events)||[]).filter(ve=>new Date(ve.starts_at)ve.is_pinned),te=[...(d==null?void 0:d.myResources)||[],...(d==null?void 0:d.resources)||[]].reduce((ve,fe)=>{const ue=fe.user_id?`Just for you · ${fe.category}`:fe.category;return(ve[ue]||(ve[ue]=[])).push(fe),ve},{}),J=((d==null?void 0:d.progress)||[]).find(ve=>ve.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||!AG(c))&&e.jsx(je,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Le,{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(br,{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($e,{variant:"secondary",children:["Week ",R," of ",l.duration_weeks]}),(c==null?void 0:c.status)==="scheduled_for_charge"&&c.charge_scheduled_at&&e.jsxs($e,{variant:"outline",children:["Billing ",th(c.charge_scheduled_at)]}),(c==null?void 0:c.status)==="payment_failed"&&e.jsx($e,{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})]}),v&&e.jsx(Pnn,{program:l,intakeComplete:!!x}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(je,{className:"neon-topline",children:e.jsxs(Le,{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(ph,{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(je,{className:"neon-topline",children:e.jsxs(Le,{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(nf,{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(je,{className:"neon-topline",children:e.jsxs(Le,{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(sh,{className:"h-3.5 w-3.5 text-primary"})," Streak"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[Z," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(je,{className:"neon-topline",children:e.jsxs(Le,{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(Zl,{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(Os,{open:y,onOpenChange:b,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(cn,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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:ve=>S(fe=>({...fe,title:ve.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:ve=>S(fe=>({...fe,instagram_url:ve.target.value}))})]})]}),e.jsx(Nr,{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(ef,{className:"mr-1.5 h-4 w-4"})," Join next session"]})})]}),le.length>0&&e.jsx(je,{className:"border-primary/30 bg-primary/5",children:e.jsx(Le,{className:"space-y-3 p-5",children:le.map(ve=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(gm,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ve.title}),ve.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ve.body})]})]},ve.id))})}),e.jsxs(pa,{defaultValue:"roadmap",children:[e.jsxs(ga,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Xt,{value:"roadmap",children:"Roadmap"}),e.jsx(Xt,{value:"lessons",children:"Lessons"}),e.jsx(Xt,{value:"checkin",children:"Weekly check-in"}),e.jsx(Xt,{value:"events",children:"Sessions"}),e.jsx(Xt,{value:"resources",children:"Resources"}),e.jsx(Xt,{value:"profile",children:"Profile review"})]}),e.jsxs(Qt,{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(ve=>{const fe=ve.release_at&&new Date(ve.release_at)>new Date;return e.jsx(je,{className:fe?"opacity-60":ve.week_number===R?"border-primary/50":"",children:e.jsxs(Le,{className:"space-y-2 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($e,{variant:"outline",children:["Week ",ve.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:ve.phase}),ve.week_number===R&&e.jsx($e,{children:"Current"}),fe&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(ca,{className:"h-3 w-3"})," Unlocks ",th(ve.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:ve.title}),ve.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ve.learning_goal}),!fe&&Array.isArray(ve.tasks)&&ve.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:ve.tasks.map((ue,be)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Vr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof ue=="string"?ue:ue.label]},be))})]})},ve.id)})]}),e.jsxs(Qt,{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(ve=>{const fe=IUt(ve.video_url),ue=I===ve.id;return e.jsx(je,{children:e.jsxs(Le,{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(ve.id),onCheckedChange:be=>h.mutate({lessonId:ve.id,done:!!be}),"aria-label":`Mark ${ve.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:ve.title}),ve.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ve.summary}),ve.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",ve.action_assignment]})]}),ve.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(ca,{className:"h-3 w-3"})," ",ve.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[ve.video_url&&(fe||_ee(ve.video_url))&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>P(ue?null:ve.id),children:[e.jsx(ef,{className:"mr-1.5 h-3.5 w-3.5"})," ",ue?"Close":"Watch"]}),ve.video_url&&!fe&&!_ee(ve.video_url)&&e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ve.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(ef,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),ve.worksheet_url&&e.jsx($,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:ve.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(ji,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),ue&&fe&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:fe,title:ve.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),ue&&!fe&&_ee(ve.video_url)&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60 bg-black",children:e.jsx("video",{src:ve.video_url,controls:!0,autoPlay:!0,className:"aspect-video w-full"})})]})},ve.id)})]}),e.jsx(Qt,{value:"checkin",className:"mt-6",children:e.jsx(je,{children:e.jsxs(Le,{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(([ve,fe])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:ve,children:fe}),e.jsx(pe,{id:ve,type:"number",min:0,defaultValue:J[ve]??"",onChange:ue=>E(be=>({...be,[ve]:Number(ue.target.value)}))})]},ve))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([ve,fe])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:ve,children:fe}),e.jsx(Rs,{id:ve,rows:2,defaultValue:J[ve]??"",onChange:ue=>E(be=>({...be,[ve]:ue.target.value}))})]},ve)),e.jsx($,{onClick:()=>f.mutate({week_number:R,goal_videos:G,...A}),children:"Save check-in"})]})})}),e.jsxs(Qt,{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(ve=>e.jsx(je,{className:"border-primary/30",children:e.jsxs(Le,{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($e,{variant:"secondary",className:"capitalize",children:String(ve.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Wc,{className:"h-3 w-3"})," ",th(ve.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:ve.title}),ve.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",ve.speaker]}),ve.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:ve.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>g.mutate({eventId:ve.id,optIn:!0}),children:"Remind me"}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>Inn(ve,l.name),children:[e.jsx(Wc,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),ve.meeting_link&&e.jsx($,{size:"sm",asChild:!0,children:e.jsxs("a",{href:ve.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(Ir,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},ve.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(ve=>e.jsx(je,{children:e.jsxs(Le,{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:ve.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:th(ve.starts_at,!0)})]}),ve.replay_url?e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ve.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(ef,{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"})]})},ve.id))]})]}),e.jsxs(Qt,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(te).length===0&&e.jsx(je,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx(Qr,{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(([ve,fe])=>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:ve}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[fe.length," item",fe.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:fe.map(ue=>{const be=tie(ue),Ee=Lnn[ue.resource_kind]||Qr;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>be&&wee(ue),onKeyDown:ke=>{be&&(ke.key==="Enter"||ke.key===" ")&&(ke.preventDefault(),wee(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($e,{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(Ir,{className:"h-3.5 w-3.5"})," Open"]}),ue.file_path&&e.jsxs("button",{type:"button",onClick:ke=>{ke.stopPropagation(),wee(ue,"download")},className:"inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-primary",children:[e.jsx(ji,{className:"h-3.5 w-3.5"})," Download"]})]})]},ue.id)})})]},ve))]}),e.jsx(Qt,{value:"profile",className:"mt-6",children:e.jsx(je,{children:e.jsxs(Le,{className:"space-y-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ef,{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(([ve,fe])=>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:ve.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[fe,"/10"]})]}),e.jsx(Yi,{value:Number(fe)*10,className:"h-1.5"})]},ve))}),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((ve,fe)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Im,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof ve=="string"?ve:ve.label]},fe))})]}),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(ji,{className:"mr-1.5 h-4 w-4"})," Download full report"]})})]})]})})})]})]})})})},hi=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})}));hi.displayName="Table";const mi=j.forwardRef(({className:s,...t},n)=>e.jsx("thead",{ref:n,className:Pt("[&_tr]:border-b",s),...t}));mi.displayName="TableHeader";const fi=j.forwardRef(({className:s,...t},n)=>e.jsx("tbody",{ref:n,className:Pt("[&_tr:last-child]:border-0",s),...t}));fi.displayName="TableBody";const Dnn=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}));Dnn.displayName="TableFooter";const An=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}));An.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 Fnn=j.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:Pt("mt-4 text-sm text-muted-foreground",s),...t}));Fnn.displayName="TableCaption";const vde=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())}`},bde=s=>s?new Date(s).toISOString():null,SBe=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:vde(s.enrollment_open_at),enrollment_close_at:vde(s.enrollment_close_at),kickoff_at:vde(s.kickoff_at),charge_at:vde(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),Onn=({program:s,onSaved:t})=>{const[n,r]=j.useState(()=>SBe(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(SBe(s)),i(!1)},[s.id,s.updated_at]);const m=(v,y)=>{r(b=>({...b,[v]:y})),i(!0)},f=async(v,y)=>{if(!v.type.startsWith("image/")){ne.error("Please choose an image file");return}if(v.size>8*1024*1024){ne.error("Image must be under 8MB");return}d(y);try{const b=v.name.split(".").pop()||"jpg",w=`programs/${s.id}/${y}-${Date.now()}.${b}`,{error:S}=await q.storage.from("event-images").upload(w,v,{cacheControl:"31536000",upsert:!0});if(S)throw S;const{data:A}=q.storage.from("event-images").getPublicUrl(w);m(y==="cover"?"cover_image_url":"hero_image_url",A.publicUrl),ne.success(`${y==="cover"?"Cover":"Hero"} image uploaded — remember to save`)}catch(b){ne.error(b.message||"Upload failed")}finally{d(null)}},g=async()=>{if(!n.name.trim())return ne.error("Program name is required");if(!n.slug.trim())return ne.error("Slug is required");o(!0);try{const v={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:bde(n.enrollment_open_at),enrollment_close_at:bde(n.enrollment_close_at),kickoff_at:bde(n.kickoff_at),charge_at:bde(n.charge_at),status:n.status,is_public:n.is_public,is_featured:n.is_featured,sort_order:Math.round(n.sort_order)},{error:y}=await q.from("programs").update(v).eq("id",s.id);if(y)throw y;ne.success("Program saved"),i(!1),t()}catch(v){ne.error(v.message||"Could not save the program")}finally{o(!1)}},x=({kind:v,label:y,hint:b})=>{const w=v==="cover"?n.cover_image_url:n.hero_image_url,S=v==="cover"?u:h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:y}),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:`${y} preview`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>m(v==="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 ${y}`,children:e.jsx(mr,{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(kv,{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:A=>{var I;const E=(I=A.target.files)==null?void 0:I[0];E&&f(E,v),A.target.value=""}}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var A;return(A=S.current)==null?void 0:A.click()},disabled:c===v,children:[c===v?e.jsx(Ct,{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:A=>m(v==="cover"?"cover_image_url":"hero_image_url",A.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(SBe(s)),i(!1)},children:"Discard"}),e.jsxs($,{onClick:g,disabled:l||!a,children:[l?e.jsx(Ct,{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(je,{children:e.jsxs(Le,{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:v=>m("name",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Slug (public URL)"}),e.jsx(pe,{value:n.slug,onChange:v=>m("slug",v.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:v=>m("subtitle",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:n.tagline,onChange:v=>m("tagline",v.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:v=>m("short_description",v.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:v=>m("description",v.target.value)})]})]})}),e.jsx(je,{children:e.jsxs(Le,{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:v=>m("promo_video_url",v.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:v=>m("promo_video_headline",v.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:v=>m("accent_color",v.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:v=>m("sort_order",Number(v.target.value))})]})]})]})}),e.jsx(je,{children:e.jsxs(Le,{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:v=>m("price_cents",Math.round(Number(v.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:v=>m("capacity",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Billing mode"}),e.jsxs(ms,{value:n.payment_mode,onValueChange:v=>m("payment_mode",v),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:v=>m("charge_at",v.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:v=>m("payment_grace_days",Number(v.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:v=>m("currency",v.target.value)})]})]})]})}),e.jsx(je,{children:e.jsxs(Le,{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:v=>m("enrollment_open_at",v.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:v=>m("enrollment_close_at",v.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:v=>m("kickoff_at",v.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:v=>m("duration_weeks",Number(v.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:v=>m("weekly_video_goal",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Timezone"}),e.jsx(pe,{value:n.timezone,onChange:v=>m("timezone",v.target.value)})]})]})]})}),e.jsx(je,{children:e.jsxs(Le,{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:v=>m("status",v),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(jn,{checked:n.is_featured,onCheckedChange:v=>m("is_featured",v)})]}),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(jn,{checked:n.is_public,onCheckedChange:v=>m("is_public",v)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs($,{onClick:g,disabled:l||!a,size:"lg",children:[l?e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},n_t={title:"",description:"",category:"Personal",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},znn=({programId:s,userId:t,memberName:n})=>{const{data:r=[],isLoading:a}=FGs(s,t),i=OGs(s,t),l=zGs(),[o,c]=j.useState(!1),[d,u]=j.useState({...n_t}),[h,m]=j.useState(!1),f=j.useRef(null),g=()=>{u({...n_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)},v=async b=>{if(!(!b||!s||!t)){if(b.size>50*1024*1024)return ne.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:A}=await q.storage.from(uK).upload(S,b,{contentType:b.type||"application/pdf",upsert:!1});if(A)throw A;u(E=>({...E,file_path:S,url:"",title:E.title||b.name.replace(/\.[^.]+$/,""),resource_kind:b.type==="application/pdf"?"pdf":E.resource_kind})),ne.success("File uploaded")}catch(w){ne.error(w.message||"Upload failed")}finally{m(!1),f.current&&(f.current.value="")}}},y=async()=>{if(!d.title.trim())return ne.error("Give the resource a title");if(!d.file_path&&!d.url.trim())return ne.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(jc,{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(cn,{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(je,{className:"border-dashed",children:e.jsx(Le,{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(je,{className:"border-border/60",children:e.jsxs(Le,{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($e,{variant:"secondary",children:b.category}),e.jsx($e,{variant:"outline",className:"capitalize",children:b.resource_kind.replace("_"," ")}),b.status!=="published"&&e.jsx($e,{variant:"outline",className:"capitalize",children:b.status})]}),b.description&&e.jsx("p",{className:"max-w-xl text-sm text-muted-foreground",children:b.description}),tie(b)&&e.jsxs("button",{type:"button",onClick:()=>wee(b),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Ir,{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(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await mo(`Remove "${b.title}"?`)&&l.mutate(b)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})]})},b.id))}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx($s,{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:LUt.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(Ct,{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 v((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(Nr,{children:[e.jsx($,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:y,disabled:i.isPending||h,children:[i.isPending&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save"]})]})]})})]})},Bnn=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var G,Z,X,ae,le,re,te,J,ce,ve;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),v=j.useRef(null),{data:y,isLoading:b,refetch:w}=st({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[fe,ue,be,Ee,ke,Ie,Fe,Ne]=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:fe.data||[],videos:ue.data||[],completions:be.data||[],badges:Ee.data||[],intake:ke.data,attendance:Ie.data||[],lessonCount:(Fe.data||[]).length,analysis:Ne.data}}});j.useEffect(()=>{var fe;h(((fe=y==null?void 0:y.analysis)==null?void 0:fe.member_notes)||"")},[(G=y==null?void 0:y.analysis)==null?void 0:G.id]);const S=j.useMemo(()=>{var be;const fe=ise(s),ue=((be=y==null?void 0:y.intake)==null?void 0:be.extra)||{};return fe.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,y==null?void 0:y.intake]),A=async fe=>i?q.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...fe},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},E=async fe=>{if(fe.type!=="application/pdf")return ne.error("Please choose a PDF file");if(fe.size>25*1024*1024)return ne.error("PDF must be under 25MB");x(!0);try{const ue=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:be}=await q.storage.from("event-images").upload(ue,fe,{contentType:"application/pdf",upsert:!0});if(be)throw be;const{data:Ee}=q.storage.from("event-images").getPublicUrl(ue),{error:ke}=await A({report_url:Ee.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(ke)throw ke;ne.success("Profile review uploaded"),await w()}catch(ue){ne.error(ue.message||"Upload failed")}finally{x(!1)}},I=async()=>{const{error:fe}=await A({report_url:null,status:"in_review"});if(fe)return ne.error(fe.message);ne.success("Review removed"),await w()},P=async()=>{f(!0);const{error:fe}=await A({member_notes:u});if(f(!1),fe)return ne.error(fe.message);ne.success("Review notes saved"),await w()},R=async()=>{if(!t)return;d(!0);const{error:fe}=await q.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),fe)return ne.error(fe.message);ne.success("Notes saved"),a()},D=((y==null?void 0:y.videos)||[]).filter(fe=>fe.posted).length,O=(s.weekly_video_goal||0)*(s.duration_weeks||0),U=y!=null&&y.lessonCount?Math.round(((y==null?void 0:y.completions.length)||0)/y.lessonCount*100):0,W=O?Math.min(100,Math.round(D/O*100)):0,V=((y==null?void 0:y.attendance)||[]).filter(fe=>fe.attended).length;return e.jsx(Vy,{open:n,onOpenChange:r,children:e.jsxs(uy,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(I0,{className:"mb-4",children:[e.jsxs(L0,{children:[((Z=t==null?void 0:t.profile)==null?void 0:Z.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)||((le=t==null?void 0:t.profile)==null?void 0:le.email)||"this member")}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"mr-2 h-4 w-4"}),"Open their dashboard"]})})]}),t?b?e.jsx(xn,{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(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx($e,{className:"mt-1 capitalize",children:String(t.status).replace(/_/g," ")}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[Ng(t.amount_cents,t.currency)," ·"," ",t.charged_at?`Charged ${th(t.charged_at)}`:`Charge ${th(t.charge_scheduled_at)||"not set"}`]})]})}),e.jsx(je,{children:e.jsxs(Le,{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:th(t.last_activity_at,!0)||"No activity yet"}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Enrolled ",th(t.created_at)]})]})})]}),e.jsx(je,{children:e.jsxs(Le,{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:[(y==null?void 0:y.completions.length)||0," / ",(y==null?void 0:y.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: "}),(y==null?void 0:y.badges.length)||0]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Weeks reported: "}),(y==null?void 0:y.weekly.length)||0]})]})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Weekly progress"}),((y==null?void 0:y.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:y.weekly.map(fe=>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 ",fe.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[fe.videos_posted,"/",fe.goal_videos||s.weekly_video_goal," posted ·"," ",fe.stories_posted," stories"]})]}),fe.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",fe.biggest_win]}),fe.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",fe.biggest_challenge]})]},fe.id))})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Video log"}),((y==null?void 0:y.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:y.videos.slice(0,25).map(fe=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(fa,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:fe.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",fe.week_number," · ",th(fe.posted_at)]}),fe.instagram_url&&e.jsx("a",{href:fe.instagram_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Open post",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})]},fe.id))})]})}),(y==null?void 0:y.intake)&&e.jsx(je,{children:e.jsxs(Le,{className:"space-y-1 p-5 text-sm",children:[e.jsx("p",{className:"mb-2 text-sm font-semibold",children:"Intake answers"}),[["Full name",y.intake.full_name],["Email",y.intake.email],["Phone",y.intake.phone],["Instagram",y.intake.instagram_handle],["City / market",y.intake.city],["Areas served",y.intake.service_areas],["Years in real estate",y.intake.years_experience],["Specialty",y.intake.specialty],["Target audience",y.intake.target_audience],["On camera",y.intake.video_comfort],["Posts today",y.intake.posting_frequency],["Content style",y.intake.content_style],["Interests",y.intake.personal_interests],["#1 goal",y.intake.primary_goal],["Topics to avoid",y.intake.topics_to_avoid],["Time zone",y.intake.timezone]].filter(([,fe])=>!!fe).map(([fe,ue])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[fe,": "]}),ue]},fe)),S.map(({label:fe,value:ue})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[fe,": "]}),ue]},fe)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",y.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(je,{children:e.jsx(Le,{className:"p-5",children:e.jsx(znn,{programId:s.id,userId:i,memberName:(re=t==null?void 0:t.profile)==null?void 0:re.name})})}),e.jsx(je,{children:e.jsxs(Le,{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=y==null?void 0:y.analysis)==null?void 0:te.status)&&e.jsx($e,{variant:"secondary",className:"capitalize",children:String(y.analysis.status).replace(/_/g," ")})]}),(J=y==null?void 0:y.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(Qr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:"Review uploaded"}),e.jsxs("a",{href:y.analysis.report_url,target:"_blank",rel:"noreferrer",className:"ml-auto inline-flex items-center gap-1 text-primary hover:underline",children:["View ",e.jsx(Ir,{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:v,type:"file",accept:"application/pdf",className:"hidden",onChange:fe=>{var be;const ue=(be=fe.target.files)==null?void 0:be[0];ue&&E(ue),fe.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{var fe;return(fe=v.current)==null?void 0:fe.click()},disabled:g,children:[e.jsx(ni,{className:"mr-1.5 h-3.5 w-3.5"}),g?"Uploading…":(ce=y==null?void 0:y.analysis)!=null&&ce.report_url?"Replace PDF":"Upload PDF"]}),((ve=y==null?void 0:y.analysis)==null?void 0:ve.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:fe=>h(fe.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(je,{children:e.jsxs(Le,{className:"space-y-3 p-5",children:[e.jsx(ee,{children:"Coach notes (internal)"}),e.jsx(Rs,{rows:4,value:l,onChange:fe=>o(fe.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{size:"sm",onClick:R,disabled:c,children:"Save notes"})})]})})]}):null]})})},r_t={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},a_t=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},$nn=({program:s})=>{const{data:t=[],isLoading:n}=NGs(s.id),r=kGs(s.id),a=SGs(),[i,l]=j.useState(!1),[o,c]=j.useState({...r_t}),d=()=>{c({...r_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:a_t(g.starts_at),expires_at:a_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 ne.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,v=Math.max(s.price_cents-Math.min(x,s.price_cents),0);return{off:g.percent_off!=null?`${Number(g.percent_off)}% off`:`${Ng(g.amount_off_cents||0,s.currency)} off`,final:Ng(v,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(je,{children:e.jsxs(Le,{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 ",Ng(s.price_cents,s.currency)," charge."]})]}),e.jsxs(Os,{open:i,onOpenChange:l,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:d,children:[e.jsx(cn,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(Fs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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(jn,{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:[Ng(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Ng(h.final,s.currency)})," ","(",Ng(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(Nr,{children:e.jsxs($,{onClick:m,disabled:r.isPending,children:[r.isPending&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save changes":"Create code"]})})]})]})]})}),n?e.jsx(xn,{className:"h-40 w-full rounded-xl"}):t.length===0?e.jsx(je,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Cp,{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(je,{children:e.jsx(Le,{className:"overflow-x-auto p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:t.map(g=>{const x=f(g);return e.jsxs(An,{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),ne.success("Code copied")},children:e.jsx(Za,{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(Aw,{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 ${th(g.starts_at)}`:"Anytime",g.expires_at?` · until ${th(g.expires_at)}`:""]}),e.jsx(wt,{children:e.jsx($e,{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 mo(`Delete ${g.code}?`)&&a.mutate(g.id)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},g.id)})})]})})})]})},t5=({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(Vr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}):e.jsx(Al,{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})]})]}),Unn=({program:s})=>{var c,d;const{data:t,isLoading:n}=st({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}=j6e(s),l=`/programs/${s.slug}`,o=[{icon:wn,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:Yq,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:jv,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 ${Ng(s.price_cents,s.currency)} charge runs on ${th(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${Ng(s.price_cents,s.currency)} once at checkout.`},{icon:pn,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:Uq,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(je,{children:e.jsxs(Le,{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(Ir,{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(Ir,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})}),(s.status!=="published"||r||a)&&e.jsx(je,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Le,{className:"flex items-start gap-3 p-5 text-sm",children:[e.jsx(Al,{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(je,{children:e.jsxs(Le,{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(Ir,{className:"ml-1 h-3 w-3"})]})})]})]},u.title))})]})}),e.jsx(je,{children:e.jsxs(Le,{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(xn,{className:"mt-4 h-64 w-full rounded-lg"}):e.jsxs("div",{className:"mt-2",children:[e.jsx(t5,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(t5,{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(t5,{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(t5,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":Ng(s.price_cents,s.currency)}),e.jsx(t5,{ok:!!s.kickoff_at&&(s.payment_mode==="free"||!!s.charge_at),label:"Kickoff and charge dates",detail:`Kickoff ${th(s.kickoff_at)||"not set"} · charge ${th(s.charge_at)||"not set"}`}),e.jsx(t5,{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(t5,{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(t5,{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(t5,{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 ${th(t.events[0].starts_at)}`:""}`}),e.jsx(t5,{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(je,{children:e.jsx(Le,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:Wc,label:"Weeks",value:t.weeks.length},{icon:Qr,label:"Lessons",value:t.lessons.length},{icon:Qr,label:"Resources",value:t.resources.length},{icon:Wc,label:"Events",value:t.events.length},{icon:gm,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($e,{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."})]})},qnn=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],Vnn={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},Hnn=({program:s,onSaved:t})=>{const[n,r]=j.useState(()=>ise(s)),[a,i]=j.useState(!1),[l,o]=j.useState(!1);j.useEffect(()=>{r(ise(s)),i(!1)},[s.id,s.updated_at]);const c=v=>{r(y=>({...y,...v})),i(!0)},d=(v,y)=>{const b=y?n.hidden.filter(S=>S!==v):[...new Set([...n.hidden,v])],w=y?n.required:n.required.filter(S=>S!==v);c({hidden:b,required:w})},u=(v,y)=>{c({required:y?[...new Set([...n.required,v])]:n.required.filter(b=>b!==v)})},h=()=>{const v={id:`q_${Date.now().toString(36)}`,label:"",type:"short_text",required:!1,options:[]};c({custom:[...n.custom,v]})},m=(v,y)=>c({custom:n.custom.map(b=>b.id===v?{...b,...y}:b)}),f=v=>c({custom:n.custom.filter(y=>y.id!==v)}),g=(v,y)=>{const b=[...n.custom],w=v+y;w<0||w>=b.length||([b[v],b[w]]=[b[w],b[v]],c({custom:b}))},x=async()=>{if(n.custom.find(w=>!w.label.trim()))return ne.error("Every custom question needs a label");o(!0);const y={...s.sales_copy||{},intake:n},{error:b}=await q.from("programs").update({sales_copy:y}).eq("id",s.id);if(o(!1),b)return ne.error(b.message);i(!1),ne.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(Ir,{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(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-sm",children:"Intro message"})}),e.jsx(Le,{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:v=>c({intro:v.target.value})})})]}),[0,1,2].map(v=>e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-sm",children:qnn[v]})}),e.jsxs(Le,{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"})]}),Xst.filter(y=>y.step===v).map(y=>{const b=!n.hidden.includes(y.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:y.label}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(jn,{checked:b,onCheckedChange:w=>d(y.key,w),"aria-label":`Show ${y.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(jn,{checked:n.required.includes(y.key),disabled:!b,onCheckedChange:w=>u(y.key,w),"aria-label":`Require ${y.label}`})})]},y.key)})]})]},v)),e.jsxs(je,{children:[e.jsxs(St,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(Et,{className:"text-sm",children:["Custom questions"," ",e.jsx($e,{variant:"secondary",className:"ml-1",children:n.custom.length})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:h,children:[e.jsx(cn,{className:"mr-1.5 h-3.5 w-3.5"})," Add question"]})]}),e.jsxs(Le,{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((v,y)=>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(y,-1),"aria-label":"Move up",children:e.jsx(zg,{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:v.label,placeholder:"What is your biggest content roadblock?",onChange:b=>m(v.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:v.type,onValueChange:b=>m(v.id,{type:b}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(Vnn).map(([b,w])=>e.jsx(Ge,{value:b,children:w},b))})]})]})]}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>f(v.id),"aria-label":"Delete question",children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]}),v.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:(v.options||[]).join(` `),onChange:b=>m(v.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:v.help||"",onChange:b=>m(v.id,{help:b.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(jn,{checked:!!v.required,onCheckedChange:b=>m(v.id,{required:b}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},v.id))]})]})]})},y1=xHt,v1=fHt,b1=gHt,Gnn=[wx,Qr,ph],Wnn=["Business profile","Content style","Goals & consent"],Knn=({fieldKey:s})=>s.includes("phone")?e.jsx(Da,{className:"h-3.5 w-3.5"}):s.includes("email")?e.jsx(pn,{className:"h-3.5 w-3.5"}):s.includes("instagram")?e.jsx(Ef,{className:"h-3.5 w-3.5"}):s.includes("city")||s.includes("area")?e.jsx(ui,{className:"h-3.5 w-3.5"}):s.includes("timezone")?e.jsx(ca,{className:"h-3.5 w-3.5"}):s.includes("consent")?s.includes("true")?e.jsx(Vr,{className:"h-3.5 w-3.5"}):e.jsx(ju,{className:"h-3.5 w-3.5"}):e.jsx(sl,{className:"h-3.5 w-3.5"}),i_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(Vr,{className:"h-3.5 w-3.5"})," Yes"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-muted-foreground",children:[e.jsx(ju,{className:"h-3.5 w-3.5"})," No"]}):String(s),Ynn=({program:s})=>{const[t,n]=j.useState(""),[r,a]=j.useState(new Set),{data:i=[],isLoading:l}=st({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=ise(s),c=Xst.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(xn,{className:"h-96 w-full rounded-xl"}):i.length===0?e.jsx(je,{className:"border-dashed",children:e.jsxs(Le,{className:"p-12 text-center text-sm text-muted-foreground",children:[e.jsx(Qr,{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=th(h.created_at,!0);return e.jsx(je,{className:"overflow-hidden",children:e.jsxs(y1,{open:m,onOpenChange:()=>u(h.id),children:[e.jsx(v1,{asChild:!0,children:e.jsxs(St,{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(Et,{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(wl,{className:`h-4 w-4 transition-transform ${m?"rotate-180":""}`})})]})]})}),e.jsx(b1,{children:e.jsxs(Le,{className:"space-y-5 p-5",children:[[0,1,2].map(g=>{const x=c.filter(y=>y.step===g),v=Gnn[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(v,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:Wnn[g]})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:x.map(y=>{const b=h[y.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(Knn,{fieldKey:y.key}),y.label]}),e.jsx("p",{className:"text-sm font-medium",children:i_t(b,y.key)})]},y.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(Qr,{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 v;const x=(v=h.extra)==null?void 0:v[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:i_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(Ea,{className:"h-3.5 w-3.5"}),"Submitted ",f,h.timezone&&e.jsxs("span",{className:"ml-2",children:["· Timezone: ",h.timezone]})]})]})})]})},h.id)})})]})},Znn=[{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"}],Xnn=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},o_t={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},Qnn=({programId:s})=>{const{data:t=[],isLoading:n}=EGs(s),r=TGs(s),a=MGs(),[i,l]=j.useState(!1),[o,c]=j.useState({...o_t}),d=()=>{c({...o_t}),l(!0)},u=v=>{c({id:v.id,title:v.title,description:v.description||"",event_kind:v.event_kind,starts_at:Xnn(v.starts_at),duration_minutes:v.duration_minutes,speaker:v.speaker||"",meeting_link:v.meeting_link||"",replay_url:v.replay_url||"",is_published:v.is_published}),l(!0)},h=async()=>{if(!o.title.trim())return ne.error("Give the session a title");if(!o.starts_at)return ne.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(v=>new Date(v.starts_at).getTime()>=m),g=t.filter(v=>new Date(v.starts_at).getTime()e.jsx(je,{className:"border-border/60",children:e.jsxs(Le,{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($e,{variant:"secondary",className:"capitalize",children:v.event_kind.replace("_"," ")}),!v.is_published&&e.jsx($e,{variant:"outline",children:"Hidden"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[th(v.starts_at,!0)," · ",v.duration_minutes," min",v.speaker?` · ${v.speaker}`:""]}),v.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:v.description}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[v.meeting_link?e.jsxs(e.Fragment,{children:[e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{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(v.meeting_link),ne.success("Join link copied")},children:[e.jsx(Za,{className:"h-3 w-3"})," Copy"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"No meeting link yet"}),v.replay_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(fa,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>u(v),children:e.jsx(pi,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"outline",size:"sm",onClick:async()=>{await mo(`Remove "${v.title}"?`)&&a.mutate(v.id)},children:e.jsx(qn,{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(cn,{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(je,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Su,{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(v=>e.jsx(x,{e:v},v.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(v=>e.jsx(x,{e:v},v.id))]})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Fs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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:v=>c({...o,title:v.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:v=>c({...o,event_kind:v}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Znn.map(v=>e.jsx(Ge,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Host / speaker"}),e.jsx(pe,{value:o.speaker,onChange:v=>c({...o,speaker:v.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:v=>c({...o,starts_at:v.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:v=>c({...o,duration_minutes:v.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:v=>c({...o,meeting_link:v.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:v=>c({...o,replay_url:v.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:v=>c({...o,description:v.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(jn,{checked:o.is_published,onCheckedChange:v=>c({...o,is_published:v})})]})]}),e.jsx(Nr,{children:e.jsxs($,{onClick:h,disabled:r.isPending,children:[r.isPending&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save session":"Add session"]})})]})})]})},l_t={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},Jnn=({programId:s})=>{const{data:t,isLoading:n}=PGs(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],{data:i=[]}=RUt(s),l=IGs(s),o=LGs(),[c,d]=j.useState(!1),[u,h]=j.useState({...l_t}),[m,f]=j.useState(!1),g=j.useRef(null),x=async A=>{if(g.current&&(g.current.value=""),!!A){if(!A.type.startsWith("video/"))return ne.error("Please choose a video file");if(A.size>500*1024*1024)return ne.error("Video must be under 500MB");f(!0);try{const E=A.name.split(".").pop()||"mp4",I=`lessons/${crypto.randomUUID()}.${E}`,{error:P}=await q.storage.from("program-assets").upload(I,A,{contentType:A.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})),ne.success("Video uploaded")}catch(E){ne.error((E==null?void 0:E.message)||"Upload failed")}finally{f(!1)}}},v=()=>{h({...l_t,sort_order:r.length}),d(!0)},y=A=>{h({id:A.id,title:A.title,summary:A.summary||"",week_id:A.week_id||"none",duration_minutes:A.duration_minutes??"",video_url:A.video_url||"",worksheet_url:A.worksheet_url||"",action_assignment:A.action_assignment||"",status:A.status,sort_order:A.sort_order}),d(!0)},b=async()=>{if(!u.title.trim())return ne.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=A=>{const E=a.find(I=>I.id===A);return E?`Week ${E.week_number}`:"Unassigned"},S=IUt(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:v,children:[e.jsx(cn,{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(je,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(nf,{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(A=>e.jsx(je,{className:"border-border/60",children:e.jsxs(Le,{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:A.title}),e.jsx($e,{variant:"secondary",children:w(A.week_id)}),A.status!=="published"&&e.jsx($e,{variant:"outline",className:"capitalize",children:A.status}),A.duration_minutes?e.jsxs("span",{className:"text-xs text-muted-foreground",children:[A.duration_minutes," min"]}):null]}),A.summary&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:A.summary}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[A.video_url?e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:A.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-3 w-3"})," Video"]}):e.jsx("span",{className:"text-muted-foreground",children:"No video link"}),A.worksheet_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:A.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-3 w-3"})," Worksheet"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>y(A),children:e.jsx(pi,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"outline",size:"sm",onClick:async()=>{await mo(`Remove "${A.title}"?`)&&o.mutate(A.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})},A.id))}),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Fs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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:A=>h({...u,title:A.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:A=>h({...u,video_url:A.target.value})}),e.jsxs($,{type:"button",variant:"outline",className:"shrink-0",disabled:m,onClick:()=>{var A;return(A=g.current)==null?void 0:A.click()},children:[m?e.jsx(Ct,{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:A=>{var E;return x((E=A.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&&!_ee(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&&_ee(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:A=>h({...u,week_id:A}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"Unassigned (library)"}),a.map(A=>e.jsxs(Ge,{value:A.id,children:["Week ",A.week_number," — ",A.title]},A.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:A=>h({...u,duration_minutes:A.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:u.status,onValueChange:A=>h({...u,status:A}),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:A=>h({...u,sort_order:A.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Summary"}),e.jsx(Rs,{rows:3,value:u.summary,onChange:A=>h({...u,summary:A.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:A=>{const E=i.find(P=>P.id===A),I=E?tie(E):null;I?h({...u,worksheet_url:I}):ne.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(A=>e.jsx(Ge,{value:A.id,children:A.title},A.id))})]}),e.jsx(pe,{placeholder:"Or paste a link",value:u.worksheet_url,onChange:A=>h({...u,worksheet_url:A.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(Ir,{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:A=>h({...u,action_assignment:A.target.value})})]})]}),e.jsx(Nr,{children:e.jsxs($,{onClick:b,disabled:l.isPending,children:[l.isPending&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}),u.id?"Save video":"Add video"]})})]})})]})},c_t={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},ern=({programId:s})=>{const{data:t=[],isLoading:n}=RUt(s),r=RGs(s),a=DGs(),[i,l]=j.useState(!1),[o,c]=j.useState({...c_t}),[d,u]=j.useState(!1),h=j.useRef(null),m=Array.from(new Set(t.map(y=>y.category))).filter(Boolean),f=()=>{c({...c_t,sort_order:t.length}),l(!0)},g=y=>{c({id:y.id,title:y.title,description:y.description||"",category:y.category||"Resources",resource_kind:y.resource_kind,url:y.url||"",file_path:y.file_path||"",status:y.status,sort_order:y.sort_order}),l(!0)},x=async y=>{if(!(!y||!s)){if(y.size>50*1024*1024)return ne.error("File must be under 50MB");u(!0);try{const b=y.name.split(".").pop()||"pdf",w=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${b}`,{error:S}=await q.storage.from(uK).upload(w,y,{contentType:y.type||"application/pdf",upsert:!1});if(S)throw S;c(A=>({...A,file_path:w,url:"",title:A.title||y.name.replace(/\.[^.]+$/,""),resource_kind:y.type==="application/pdf"?"pdf":A.resource_kind})),ne.success("File uploaded")}catch(b){ne.error(b.message||"Upload failed")}finally{u(!1),h.current&&(h.current.value="")}}},v=async()=>{if(!o.title.trim())return ne.error("Give the resource a title");if(!o.file_path&&!o.url.trim())return ne.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(cn,{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(je,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Qr,{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(y=>{const b=tie(y);return e.jsx(je,{className:"border-border/60",children:e.jsxs(Le,{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($e,{variant:"secondary",children:y.category}),e.jsx($e,{variant:"outline",className:"capitalize",children:y.resource_kind.replace("_"," ")}),y.status!=="published"&&e.jsx($e,{variant:"outline",className:"capitalize",children:y.status})]}),y.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:y.description}),b&&e.jsxs("button",{type:"button",onClick:()=>wee(y),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Ir,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(y),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await mo(`Remove "${y.title}"?`)&&a.mutate(y)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})]})},y.id)})}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx($s,{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:y=>c({...o,title:y.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:y=>c({...o,description:y.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:y=>c({...o,category:y.target.value}),placeholder:"Getting started",list:"program-resource-categories"}),e.jsx("datalist",{id:"program-resource-categories",children:m.map(y=>e.jsx("option",{value:y},y))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ms,{value:o.resource_kind,onValueChange:y=>c({...o,resource_kind:y}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:LUt.map(y=>e.jsx(Ge,{value:y.value,children:y.label},y.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:y=>{var b;return x((b=y.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 y;return(y=h.current)==null?void 0:y.click()},disabled:d,children:[d?e.jsx(Ct,{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:y=>c({...o,url:y.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:y=>c({...o,status:y}),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:y=>c({...o,sort_order:y.target.value})})]})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:r.isPending||d,children:[r.isPending&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},trn=({programId:s})=>{const{data:t=[],isLoading:n}=UGs(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(xn,{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(je,{children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx(YS,{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(je,{children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx(Yn,{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(je,{children:e.jsx(Le,{className:"flex items-center gap-3 p-4",children:e.jsxs($e,{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),ne.success("Emails copied")},children:[e.jsx(Za,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs($,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(ji,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:t.map(l=>e.jsxs(An,{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:th(l.created_at)})]},l.id))})]})})]})},d_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:""},srn=()=>{const s=Zt(),[t,n]=j.useState(null),[r,a]=j.useState(!1),[i,l]=j.useState({...d_t}),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(null),{data:f=[],isLoading:g}=st({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:v=[]}=st({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:y=[]}=st({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=[]}=st({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;ne.success("Program created"),a(!1),l({...d_t}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(P){ne.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 ne.error(R.message);s.invalidateQueries({queryKey:["admin-programs"]})},A=async(P,R)=>{const{error:D}=await q.from("program_enrollments").update(R).eq("id",P);if(D)return ne.error(D.message);ne.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 ne.error((R==null?void 0:R.error)||(D==null?void 0:D.message));ne.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(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(jv,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(Os,{open:r,onOpenChange:a,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(cn,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(Fs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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(Nr,{children:e.jsxs($,{onClick:w,disabled:o||!i.name,children:[o&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"})," Create"]})})]})]})]})]}),g?e.jsx(xn,{className:"h-40 w-full rounded-xl"}):f.length===0?e.jsx(je,{className:"border-dashed",children:e.jsx(Le,{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($e,{variant:"secondary",className:"ml-2 capitalize",children:P.status})]},P.id))}),x&&e.jsxs(pa,{defaultValue:"overview",children:[e.jsxs(ga,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Xt,{value:"overview",children:"Overview"}),e.jsx(Xt,{value:"details",children:"Details & pricing"}),e.jsx(Xt,{value:"sessions",children:"Live sessions"}),e.jsx(Xt,{value:"videos",children:"On-demand videos"}),e.jsx(Xt,{value:"resources",children:"Resources"}),e.jsx(Xt,{value:"intake-form",children:"Intake form"}),e.jsx(Xt,{value:"discounts",children:"Discount codes"}),e.jsx(Xt,{value:"experience",children:"Enrollee experience"}),e.jsx(Xt,{value:"interest",children:"Interest list"}),e.jsxs(Xt,{value:"enrollments",children:["Enrollments (",v.length,")"]}),e.jsxs(Xt,{value:"intake",children:["Intake (",y.length,")"]}),e.jsx(Xt,{value:"audit",children:"Audit"})]}),e.jsxs(Qt,{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(je,{children:e.jsxs(Le,{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:[v.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(je,{children:e.jsxs(Le,{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:v.filter(P=>P.status==="paid").length})]})}),e.jsx(je,{children:e.jsxs(Le,{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:v.filter(P=>P.status==="payment_failed").length})]})}),e.jsx(je,{children:e.jsxs(Le,{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:Ng(v.filter(P=>["scheduled_for_charge","paid","completed"].includes(P.status)).reduce((P,R)=>P+(R.amount_cents||0),0),x.currency)})]})})]}),e.jsx(je,{children:e.jsxs(Le,{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(jn,{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(jn,{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:Ng(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:th(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:th(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(Qt,{value:"details",className:"mt-6",children:e.jsx(Onn,{program:x,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Qt,{value:"sessions",className:"mt-6",children:e.jsx(Qnn,{programId:x.id})}),e.jsx(Qt,{value:"videos",className:"mt-6",children:e.jsx(Jnn,{programId:x.id})}),e.jsx(Qt,{value:"resources",className:"mt-6",children:e.jsx(ern,{programId:x.id})}),e.jsx(Qt,{value:"discounts",className:"mt-6",children:e.jsx($nn,{program:x})}),e.jsx(Qt,{value:"intake-form",className:"mt-6",children:e.jsx(Hnn,{program:x,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Qt,{value:"experience",className:"mt-6",children:e.jsx(Unn,{program:x})}),e.jsx(Qt,{value:"interest",className:"mt-6",children:e.jsx(trn,{programId:x.id})}),e.jsx(Qt,{value:"enrollments",className:"mt-6",children:e.jsx(je,{children:e.jsx(Le,{className:"overflow-x-auto p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:[v.length===0&&e.jsx(An,{children:e.jsxs(wt,{colSpan:6,className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(Yn,{className:"mx-auto mb-2 h-5 w-5"}),"No enrollments yet"]})}),v.map(P=>{var R,D;return e.jsxs(An,{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($e,{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:th(P.charge_scheduled_at)||"—"}),e.jsx(wt,{className:"text-sm",children:Ng(P.amount_cents,P.currency)}),e.jsx(wt,{children:e.jsx(jn,{checked:P.access_override,onCheckedChange:O=>A(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(co,{className:"mr-1.5 h-3.5 w-3.5"})," Charge now"]}),!["canceled","refunded"].includes(P.status)&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>A(P.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},P.id)})]})]})})})}),e.jsx(Qt,{value:"intake",className:"mt-6",children:e.jsx(Ynn,{program:x})}),e.jsx(Qt,{value:"audit",className:"mt-6",children:e.jsx(je,{children:e.jsxs(Le,{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($e,{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:th(P.created_at,!0)})]},P.id))]})})})]}),x&&e.jsx(Bnn,{program:x,enrollment:h,open:!!h,onOpenChange:P=>!P&&m(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},nrn=()=>{const{user:s}=_s(),[t,n]=j.useState(""),[r,a]=j.useState("all"),{data:i=[]}=st({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}=st({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(y=>({...y,resources:(g==null?void 0:g.filter(b=>b.video_id===y.id))||[]}))}}),{data:c=[]}=st({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(pa,{value:r,onValueChange:a,children:e.jsxs(ga,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(Xt,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(m=>e.jsx(Xt,{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(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(fa,{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(br,{to:`/academy/${m.id}`,children:e.jsxs(je,{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(fa,{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(Ou,{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(ca,{className:"h-3 w-3"}),m.duration]})]}),e.jsxs(St,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(Et,{className:"text-lg line-clamp-2",children:m.title})}),m.category&&e.jsx($e,{variant:"secondary",className:"w-fit",children:m.category.name})]}),e.jsxs(Le,{className:"pt-0",children:[m.description&&e.jsx(Vn,{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($y,{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(Qr,{className:"h-4 w-4"}),m.resources.length]})]})]})]})},m.id))})]})})};function jHt({resourceType:s,resourceId:t}){const{data:n=[]}=st({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(yd,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(r=>e.jsx(br,{to:`/templates/${r.id}`,children:e.jsxs($e,{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(yd,{className:"h-3 w-3"}),r.name]})},r.id))})]})}const rrn=(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},arn=()=>{const{videoId:s}=Wi();Zn();const{user:t,isAdmin:n}=_s(),{toast:r}=Bi(),a=Zt(),{trackEngagement:i}=dK(),[l,o]=j.useState(""),{data:c,isLoading:d}=st({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:A}=await q.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...w,resources:A||[]}},enabled:!!s});j.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:u=[]}=st({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=[]}=st({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 A=[...new Set(w.map(P=>P.user_id))],{data:E}=await q.from("profiles").select("id, name").in("id",A),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=mt({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=mt({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=mt({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)),v=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"📁"}},y=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(br,{to:"/academy",children:[e.jsx(Va,{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:rrn(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(fa,{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(Ir,{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($e,{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(br,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(pi,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(mK,{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($y,{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(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Qr,{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:v(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(ji,{className:"h-4 w-4 text-muted-foreground"})]},w.id))})]})}),e.jsx(jHt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(Vc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ah,{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(Zr,{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(je,{children:e.jsx(Le,{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(je,{children:e.jsx(Le,{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:hu(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(qn,{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(fa,{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(br,{to:"/academy",children:"Back to Academy"})})]})})},N$="https://dashboard.relevelup.com",irn=(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},orn=[{icon:ef,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:Qp,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:Yn,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}=st({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?irn(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:N$,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(wn,{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:N$,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($e,{className:"bg-[#406E71]/20 text-[#7ec0c3] border-[#406E71]/40 hover:bg-[#406E71]/30",children:[e.jsx(ef,{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(By,{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:N$,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(Qa,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:N$,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:orn.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(Vr,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:N$,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(Qa,{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:N$,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function crn(){const s=Zn(),[t,n]=j.useState(""),{data:r,isLoading:a}=st({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}=st({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}=st({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}=st({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(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx(xn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(xn,{className:"h-5 w-3/4 mb-2"}),e.jsx(xn,{className:"h-4 w-full mb-4"}),e.jsx(xn,{className:"h-4 w-2/3"})]})},g))}):(c==null?void 0:c.length)===0?e.jsxs(je,{className:"p-12 text-center",children:[e.jsx(ym,{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),v=h(f.id);return e.jsxs(je,{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(ym,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(Le,{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:Fte(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(Qr,{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($y,{className:"h-3.5 w-3.5"}),x]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ah,{className:"h-3.5 w-3.5"}),v]})]})]})]})]},f.id)})})]})})}const drn=()=>{const{kitId:s}=Wi(),{user:t,isAdmin:n}=_s(),{toast:r}=Bi(),a=Zt(),{trackEngagement:i}=dK(),[l,o]=j.useState(""),{data:c,isLoading:d}=st({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:A}=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:A||[],links:E||[]}},enabled:!!s});j.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:u=[]}=st({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=[]}=st({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 A=[...new Set(w.map(P=>P.user_id))],{data:E}=await q.from("profiles").select("id, name").in("id",A),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=mt({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=mt({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=mt({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)),v=w=>w.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),y=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(br,{to:"/toolbox",children:[e.jsx(Va,{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(br,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(pi,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(mK,{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($y,{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(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Qr,{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(Qr,{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:y(w.file_size)})]})]}),e.jsx(ji,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},w.id))})]})}),c.links&&c.links.length>0&&e.jsx(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Ir,{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(Ir,{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(jHt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(Vc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ah,{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(Zr,{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(je,{children:e.jsx(Le,{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(je,{children:e.jsx(Le,{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:hu(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(qn,{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(ym,{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(br,{to:"/toolbox",children:"Back to Toolbox"})})]})})},urn=()=>{const s=Zn(),[t,n]=j.useState(""),[r,a]=j.useState("grid"),{data:i=[],isLoading:l}=st({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 v=new Map;return g==null||g.forEach(b=>{v.set(b.swag_id,(v.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:v.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(Xf,{className:"h-4 w-4"})}),e.jsx($,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(E0,{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(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx(xn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(xn,{className:"h-5 w-3/4 mb-2"}),e.jsx(xn,{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(je,{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($e,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(Sd,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(Le,{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($y,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ah,{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(Ir,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var Cc=function(){return Cc=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(Vrn,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:m,onNextClick:f})}function Hrn(s){var t,n=tp(),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:SHt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(u_t,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(u_t,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(h_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(h_t,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function Grn(s){var t=tp(),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 Wrn(s,t,n){for(var r=n?dT(new Date):w1(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Am(r,i);a.push(l)}return a}function Krn(){var s=tp(),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=Wrn(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 Yrn(){var s,t=tp(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:Krn;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function Zrn(s){var t=tp(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var ert=j.createContext(void 0);function Xrn(s){if(!die(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(ert.Provider,{value:t,children:s.children})}return e.jsx(Qrn,{initialProps:s.initialProps,children:s.children})}function Qrn(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 v=r?NHt([],r):[];if(u.selected){var y=v.findIndex(function(b){return sf(d,b)});v.splice(y,1)}else v.push(d);(f=t.onSelect)===null||f===void 0||f.call(t,v,d,u,h)}}},o={disabled:[]};r&&o.disabled.push(function(d){var u=i&&r.length>i-1,h=r.some(function(m){return sf(m,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(ert.Provider,{value:c,children:n})}function trt(){var s=j.useContext(ert);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function Jrn(s,t){var n=t||{},r=n.from,a=n.to;return r&&a?sf(a,s)&&sf(r,s)?void 0:sf(a,s)?{from:a,to:void 0}:sf(r,s)?void 0:L4(r,s)?{from:s,to:a}:{from:r,to:s}:a?L4(s,a)?{from:a,to:s}:{from:s,to:a}:r?nC(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var srt=j.createContext(void 0);function ean(s){if(!uie(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(srt.Provider,{value:t,children:s.children})}return e.jsx(tan,{initialProps:s.initialProps,children:s.children})}function tan(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 v,y;(v=t.onDayClick)===null||v===void 0||v.call(t,f,g,x);var b=Jrn(f,r);(y=t.onSelect)===null||y===void 0||y.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],sf(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:W4e(i,o-1),before:Am(i,o-1)}),i&&l&&u.disabled.push({after:i,before:Am(i,o-1)}),!i&&l&&u.disabled.push({after:W4e(l,o-1),before:Am(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:Am(i,-c+1)}),u.disabled.push({after:Am(i,c-1)})),i&&l){var h=db(l,i)+1,m=c-h;u.disabled.push({before:W4e(i,m)}),u.disabled.push({after:Am(l,m)})}!i&&l&&(u.disabled.push({before:Am(l,-c+1)}),u.disabled.push({after:Am(l,c-1)}))}return e.jsx(srt.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function nrt(){var s=j.useContext(srt);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function p3e(s){return Array.isArray(s)?NHt([],s):s!==void 0?[s]:[]}function san(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=p3e(a)}),t}var pC;(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"})(pC||(pC={}));var nan=pC.Selected,J3=pC.Disabled,ran=pC.Hidden,aan=pC.Today,CBe=pC.RangeEnd,ABe=pC.RangeMiddle,EBe=pC.RangeStart,ian=pC.Outside;function oan(s,t,n){var r,a=(r={},r[nan]=p3e(s.selected),r[J3]=p3e(s.disabled),r[ran]=p3e(s.hidden),r[aan]=[s.today],r[CBe]=[],r[ABe]=[],r[EBe]=[],r[ian]=[],r);return s.fromDate&&a[J3].push({before:s.fromDate}),s.toDate&&a[J3].push({after:s.toDate}),die(s)?a[J3]=a[J3].concat(t.modifiers[J3]):uie(s)&&(a[J3]=a[J3].concat(n.modifiers[J3]),a[EBe]=n.modifiers[EBe],a[ABe]=n.modifiers[ABe],a[CBe]=n.modifiers[CBe]),a}var EHt=j.createContext(void 0);function lan(s){var t=tp(),n=trt(),r=nrt(),a=oan(t,n,r),i=san(t.modifiers),l=Cc(Cc({},a),i);return e.jsx(EHt.Provider,{value:l,children:s.children})}function THt(){var s=j.useContext(EHt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function can(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function dan(s){return!!(s&&typeof s=="object"&&"from"in s)}function uan(s){return!!(s&&typeof s=="object"&&"after"in s)}function han(s){return!!(s&&typeof s=="object"&&"before"in s)}function man(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function fan(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=db(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=db(s,r)>=0&&db(a,s)>=0;return l}return a?sf(a,s):r?sf(r,s):!1}function pan(s){return ptt(s)}function gan(s){return Array.isArray(s)&&s.every(ptt)}function xan(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if(pan(n))return sf(s,n);if(gan(n))return n.includes(s);if(dan(n))return fan(s,n);if(man(n))return n.dayOfWeek.includes(s.getDay());if(can(n)){var r=db(n.before,s),a=db(n.after,s),i=r>0,l=a<0,o=L4(n.before,n.after);return o?l&&i:i||l}return uan(n)?db(s,n.after)>0:han(n)?db(n.before,s)>0:typeof n=="function"?n(s):!1})}function rrt(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return xan(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!Dae(s,n)&&(a.outside=!0),a}function yan(s,t){for(var n=Zm(s[0]),r=uw(s[s.length-1]),a,i,l=n;l<=r;){var o=rrt(l,t),c=!o.disabled&&!o.hidden;if(!c){l=Am(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=Am(l,1)}return i||a}var van=365;function MHt(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:Am,week:s8,month:Av,year:qMs,startOfWeek:function(v){return a.ISOWeek?dT(v):w1(v,{locale:h,weekStartsOn:c})},endOfWeek:function(v){return a.ISOWeek?yzt(v):TLe(v,{locale:h,weekStartsOn:c})}},f=m[n](s,r==="after"?1:-1);r==="before"&&d?f=VMs([d,f]):r==="after"&&u&&(f=HMs([u,f]));var g=!0;if(i){var x=rrt(f,i);g=!x.disabled&&!x.hidden}return g?f:o.count>van?o.lastFocused:MHt(f,{moveBy:n,direction:r,context:a,modifiers:i,retry:Cc(Cc({},o),{count:o.count+1})})}var PHt=j.createContext(void 0);function ban(s){var t=hie(),n=THt(),r=j.useState(),a=r[0],i=r[1],l=j.useState(),o=l[0],c=l[1],d=yan(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},m=function(v){i(v)},f=tp(),g=function(v,y){if(a){var b=MHt(a,{moveBy:v,direction:y,context:f,modifiers:n});sf(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(PHt.Provider,{value:x,children:s.children})}function art(){var s=j.useContext(PHt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function _an(s,t){var n=THt(),r=rrt(s,n,t);return r}var irt=j.createContext(void 0);function wan(s){if(!Z6e(s.initialProps)){var t={selected:void 0};return e.jsx(irt.Provider,{value:t,children:s.children})}return e.jsx(jan,{initialProps:s.initialProps,children:s.children})}function jan(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(irt.Provider,{value:a,children:n})}function IHt(){var s=j.useContext(irt);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function Nan(s,t){var n=tp(),r=IHt(),a=trt(),i=nrt(),l=art(),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,v=l.focusYearAfter,y=l.focusStartOfWeek,b=l.focusEndOfWeek,w=function(X){var ae,le,re,te;Z6e(n)?(ae=r.onDayClick)===null||ae===void 0||ae.call(r,s,t,X):die(n)?(le=a.onDayClick)===null||le===void 0||le.call(a,s,t,X):uie(n)?(re=i.onDayClick)===null||re===void 0||re.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)},A=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?v():g();break;case"Home":X.preventDefault(),X.stopPropagation(),y();break;case"End":X.preventDefault(),X.stopPropagation(),b();break}(ae=n.onDayKeyDown)===null||ae===void 0||ae.call(n,s,t,X)},Z={onClick:w,onFocus:S,onBlur:A,onKeyDown:G,onKeyUp:V,onMouseEnter:E,onMouseLeave:I,onPointerEnter:P,onPointerLeave:R,onTouchCancel:D,onTouchEnd:O,onTouchMove:U,onTouchStart:W};return Z}function kan(){var s=tp(),t=IHt(),n=trt(),r=nrt(),a=Z6e(s)?t.selected:die(s)?n.selected:uie(s)?r.selected:void 0;return a}function San(s){return Object.values(pC).includes(s)}function Can(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(San(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function Aan(s,t){var n=Cc({},s.styles.day);return Object.keys(t).forEach(function(r){var a;n=Cc(Cc({},n),(a=s.modifiersStyles)===null||a===void 0?void 0:a[r])}),n}function Ean(s,t,n){var r,a,i,l=tp(),o=art(),c=_an(s,t),d=Nan(s,c),u=kan(),h=!!(l.onDayClick||l.mode!=="default");j.useEffect(function(){var E;c.outside||o.focusedDay&&h&&sf(o.focusedDay,s)&&((E=n.current)===null||E===void 0||E.focus())},[o.focusedDay,s,n,h,c.outside]);var m=Can(l,c).join(" "),f=Aan(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:Zrn,v=e.jsx(x,{date:s,displayMonth:t,activeModifiers:c}),y={style:f,className:m,children:v,role:"gridcell"},b=o.focusTarget&&sf(o.focusTarget,s)&&!c.outside,w=o.focusedDay&&sf(o.focusedDay,s),S=Cc(Cc(Cc({},y),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=w||b?0:-1,r)),d),A={isButton:h,isHidden:g,activeModifiers:c,selectedDays:u,buttonProps:S,divProps:y};return A}function Tan(s){var t=j.useRef(null),n=Ean(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(RTe,Cc({name:"day",ref:t},n.buttonProps)):e.jsx("div",Cc({},n.divProps))}function Man(s){var t=s.number,n=s.dates,r=tp(),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(RTe,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:m,children:u})}function Pan(s){var t,n,r=tp(),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:Tan,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:Man,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})},ZPs(h))})]})}function m_t(s,t,n){for(var r=n!=null&&n.ISOWeek?yzt(t):TLe(t,n),a=n!=null&&n.ISOWeek?dT(s):w1(s,n),i=db(r,a),l=[],o=0;o<=i;o++)l.push(Am(a,o));var c=l.reduce(function(d,u){var h=n!=null&&n.ISOWeek?xtt(u):vtt(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 Ian(s,t){var n=m_t(Zm(s),uw(s),t);if(t!=null&&t.useFixedWeeks){var r=QPs(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=s8(i,6-r),o=m_t(s8(i,1),l,t);n.push.apply(n,o)}}return n}function Lan(s){var t,n,r,a=tp(),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=Ian(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:Yrn,v=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:Pan,y=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:Grn;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(v,{displayMonth:s.displayMonth,dates:b.dates,weekNumber:b.weekNumber},b.weekNumber)})}),e.jsx(y,{displayMonth:s.displayMonth})]})}function Ran(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Dan=Ran()?j.useLayoutEffect:j.useEffect,TBe=!1,Fan=0;function f_t(){return"react-day-picker-".concat(++Fan)}function Oan(s){var t,n=s??(TBe?f_t():null),r=j.useState(n),a=r[0],i=r[1];return Dan(function(){a===null&&i(f_t())},[]),j.useEffect(function(){TBe===!1&&(TBe=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function zan(s){var t,n,r=tp(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=hie().displayMonths,d=Oan(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=Cc(Cc({},m),l.caption_start)),g&&(h.push(i.caption_end),m=Cc(Cc({},m),l.caption_end)),x&&(h.push(i.caption_between),m=Cc(Cc({},m),l.caption_between));var v=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:Hrn;return e.jsxs("div",{className:h.join(" "),style:m,children:[e.jsx(v,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(Lan,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function Ban(s){var t=tp(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function $an(s){var t,n,r=s.initialProps,a=tp(),i=art(),l=hie(),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=Cc(Cc({},a.styles.root),a.style),m=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,x){var v;return Cc(Cc({},g),(v={},v[x]=r[x],v))},{}),f=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:Ban;return e.jsx("div",Cc({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(zan,{displayIndex:x,displayMonth:g},x)})})}))}function Uan(s){var t=s.children,n=hrn(s,["children"]);return e.jsx(Mrn,{initialProps:n,children:e.jsx($rn,{children:e.jsx(wan,{initialProps:n,children:e.jsx(Xrn,{initialProps:n,children:e.jsx(ean,{initialProps:n,children:e.jsx(lan,{children:e.jsx(ban,{children:t})})})})})})})}function qan(s){return e.jsx(Uan,Cc({},s,{children:e.jsx($an,{initialProps:s})}))}function A2({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(qan,{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(dG({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(dG({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(kd,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(Di,{className:"h-4 w-4"})},...r})}A2.displayName="Calendar";var Van=Object.defineProperty,h6=(s,t)=>Van(s,"name",{value:t,configurable:!0}),ort="Popover",[LHt,Vkr]=ep(ort,[n3]),lrt=n3(),[Han,fK]=LHt(ort),Gan=h6(s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=lrt(t),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=dy({prop:r,defaultProp:a??!1,onChange:i,caller:ort});return e.jsx(bae,{...o,children:e.jsx(Han,{scope:t,contentId:cy(),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"),Wan="PopoverTrigger",Kan=j.forwardRef(h6(function(t,n){const{__scopePopover:r,...a}=t,i=fK(Wan,r),l=lrt(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":crt(i.open),...a,ref:o,onClick:Ra(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:e.jsx(_ae,{asChild:!0,...l,children:c})},"PopoverTrigger")),RHt="PopoverPortal",[Yan,Zan]=LHt(RHt,{forceMount:void 0}),Xan=h6(s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=fK(RHt,t);return e.jsx(Yan,{scope:t,forceMount:n,children:e.jsx(my,{present:n||i.open,children:e.jsx(fae,{asChild:!0,container:a,children:r})})})},"PopoverPortal"),wse="PopoverContent",Qan=j.forwardRef(h6(function(t,n){const r=Zan(wse,t.__scopePopover),{forceMount:a=r.forceMount,...i}=t,l=fK(wse,t.__scopePopover);return e.jsx(my,{present:a||l.open,children:l.modal?e.jsx(ein,{...i,ref:n}):e.jsx(tin,{...i,ref:n})})},"PopoverContent")),Jan=hC("PopoverContent.RemoveScroll"),ein=j.forwardRef(h6(function(t,n){const r=fK(wse,t.__scopePopover),a=j.useRef(null),i=Vo(n,a),l=j.useRef(!1);return j.useEffect(()=>{const o=a.current;if(o)return UIe(o)},[]),e.jsx(gae,{as:Jan,allowPinchZoom:!0,children:e.jsx(DHt,{...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")),tin=j.forwardRef(h6(function(t,n){const r=fK(wse,t.__scopePopover),a=j.useRef(!1),i=j.useRef(!1);return e.jsx(DHt,{...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")),DHt=j.forwardRef(h6(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=fK(wse,r),g=lrt(r);return BW(),e.jsx(BIe,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:i,onUnmountAutoFocus:l,children:e.jsx(CB,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:h,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:u,onDismiss:()=>f.onOpenChange(!1),deferPointerDownOutside:!0,children:e.jsx(wae,{"data-state":crt(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 crt(s){return s?"open":"closed"}h6(crt,"getState");var sin=Gan,nin=Kan,rin=Xan,FHt=Qan;const Gd=sin,Wd=nin,Dd=j.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(rin,{children:e.jsx(FHt,{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})}));Dd.displayName=FHt.displayName;async function jse(s){if(s instanceof jae)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 ain=AB("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"}}),Nse=j.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:Pt(ain({variant:t}),s),...n}));Nse.displayName="Alert";const iin=j.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:Pt("mb-1 font-medium leading-none tracking-tight",s),...t}));iin.displayName="AlertTitle";const kse=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Pt("text-sm [&_p]:leading-relaxed",s),...t}));kse.displayName="AlertDescription";function oin({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=Zt(),{user:c}=_s(),d=(c==null?void 0:c.id)??null,[u,h]=j.useState(a),[m,f]=j.useState([]),[g,x]=j.useState(null),[v,y]=j.useState("now"),[b,w]=j.useState(xyt(Nyt(new Date),1)),[S,A]=j.useState("12"),[E,I]=j.useState("00"),[P,R]=j.useState("PM");j.useEffect(()=>{if(s){h(a),y("now"),f([]);const fe=xyt(Nyt(new Date),1);w(fe);const ue=fe.getHours();A(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 fe=parseInt(S);const ue=parseInt(E);return P==="PM"&&fe!==12&&(fe+=12),P==="AM"&&fe===12&&(fe=0),Azt(Czt(b,fe),ue)},{data:O,isLoading:U}=st({queryKey:["social-accounts-for-post",d],queryFn:async()=>{const{data:{user:fe}}=await q.auth.getUser();if(!fe)return[];const{data:ue,error:be}=await q.from("social_accounts").select("*").eq("user_id",fe.id).eq("is_active",!0).order("platform",{ascending:!0});if(be)throw be;return console.log("Fetched social accounts for posting:",ue),ue},enabled:s,staleTime:0}),W=mt({mutationFn:async({accountId:fe,platform:ue})=>{x(fe);const{data:be,error:Ee}=await q.functions.invoke("social-post",{body:{platform:ue,accountId:fe,imageUrl:n,caption:u}});if(Ee)throw new Error(await jse(Ee));if(be!=null&&be.error)throw new Error(be.error);return be},onSuccess:fe=>{const ue=fe.platform==="facebook"?"Facebook":fe.platform==="instagram"?"Instagram":fe.platform==="linkedin"?"LinkedIn":"Google Business";ne.success(`Posted to ${ue}!`)},onError:fe=>{ne.error(`Failed to post: ${fe.message}`)},onSettled:()=>{x(null)}}),V=mt({mutationFn:async({accountId:fe,platform:ue,scheduledFor:be})=>{const{data:{user:Ee}}=await q.auth.getUser();if(!Ee)throw new Error("Not authenticated");const{error:ke}=await q.from("scheduled_posts").insert({user_id:Ee.id,social_account_id:fe,platform:ue,image_url:n,caption:u,swag_item_id:i||null,reel_id:l||null,scheduled_for:be.toISOString(),status:"scheduled"});if(ke)throw ke;return{platform:ue}},onSuccess:fe=>{const ue=fe.platform==="facebook"?"Facebook":fe.platform==="instagram"?"Instagram":"LinkedIn";ne.success(`Post scheduled for ${ue}!`)},onError:fe=>{ne.error(`Failed to schedule: ${fe.message}`)}}),G=async()=>{if(m.length===0){ne.error("Please select at least one account");return}if(v==="schedule"){const fe=D();if(!fe||fe<=new Date){ne.error("Please select a future date and time");return}for(const ue of m){const be=O==null?void 0:O.find(Ee=>Ee.id===ue);be&&await V.mutateAsync({accountId:ue,platform:be.platform,scheduledFor:fe})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),ne.success(`${m.length} post(s) scheduled for ${Js(fe,"PPp")}`)}else for(const fe of m){const ue=O==null?void 0:O.find(be=>be.id===fe);ue&&await W.mutateAsync({accountId:fe,platform:ue.platform})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),h(""),f([]),t(!1)},Z=fe=>{f(ue=>ue.includes(fe)?ue.filter(be=>be!==fe):[...ue,fe])},X=(O==null?void 0:O.filter(fe=>fe.platform==="facebook"))||[],ae=(O==null?void 0:O.filter(fe=>fe.platform==="instagram"))||[],le=(O==null?void 0:O.filter(fe=>fe.platform==="linkedin"))||[],re=(O==null?void 0:O.filter(fe=>fe.platform==="google_business"))||[],te=((O==null?void 0:O.length)||0)>0,J=W.isPending||V.isPending,ce=Array.from({length:12},(fe,ue)=>String(ue+1)),ve=["00","15","30","45"];return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Create Social Post"}),e.jsx(Er,{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:fe=>h(fe.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:()=>y("now"),className:Pt("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",v==="now"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Post Now"}),e.jsx("button",{type:"button",onClick:()=>y("schedule"),className:Pt("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",v==="schedule"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Schedule"})]})]}),v==="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(ca,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("justify-start text-left font-normal flex-1",!b&&"text-muted-foreground"),children:[e.jsx(Ea,{className:"mr-2 h-4 w-4"}),b?Js(b,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Dd,{className:"w-auto p-0",align:"start",children:e.jsx(A2,{mode:"single",selected:b,onSelect:w,disabled:fe=>fee.jsx(Ge,{value:fe,children:fe},fe))})]}),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:ve.map(fe=>e.jsx(Ge,{value:fe,children:fe},fe))})]}),e.jsxs(ms,{value:P,onValueChange:fe=>R(fe),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 ",Js(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(Ct,{className:"h-6 w-6 animate-spin"})}),!U&&!te&&e.jsxs(Nse,{children:[e.jsx(vl,{className:"h-4 w-4"}),e.jsxs(kse,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(br,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(Nd,{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(Zp,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),X.map(fe=>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(fe.id),onCheckedChange:()=>Z(fe.id),disabled:g===fe.id}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Ii,{src:fe.profile_picture_url||""}),e.jsx(za,{children:e.jsx(Zp,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:fe.page_name||fe.platform_username}),g===fe.id&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]},fe.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(Ef,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),ae.map(fe=>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(fe.id),onCheckedChange:()=>Z(fe.id),disabled:g===fe.id}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Ii,{src:fe.profile_picture_url||""}),e.jsx(za,{children:e.jsx(Ef,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",fe.platform_username]}),g===fe.id&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]},fe.id))]}),le.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(ly,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),le.map(fe=>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(fe.id),onCheckedChange:()=>Z(fe.id),disabled:g===fe.id}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Ii,{src:fe.profile_picture_url||""}),e.jsx(za,{children:e.jsx(ly,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:fe.platform_username}),g===fe.id&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]},fe.id))]}),re.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ui,{className:"h-4 w-4 text-red-600"})," Google Business"]}),re.map(fe=>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(fe.id),onCheckedChange:()=>Z(fe.id),disabled:g===fe.id}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Ii,{src:fe.profile_picture_url||""}),e.jsx(za,{children:e.jsx(ui,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:fe.page_name||fe.platform_username}),g===fe.id&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]},fe.id))]})]})]}),e.jsxs(Nr,{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(Ct,{className:"h-4 w-4 animate-spin"}):v==="schedule"?e.jsx(Ea,{className:"h-4 w-4"}):e.jsx(Zr,{className:"h-4 w-4"}),v==="schedule"?`Schedule ${m.length} post${m.length!==1?"s":""}`:`Post to ${m.length} account${m.length!==1?"s":""}`]})]})]})})}function lin(){const{user:s}=_s(),t=(s==null?void 0:s.id)??null,n=Zt(),[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,v]=j.useState("00"),[y,b]=j.useState("PM"),{data:w=[],isLoading:S}=st({queryKey:["scheduled-posts",t],enabled:!!t,queryFn:async()=>{const{data:re,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 re}}),A=w.filter(re=>{if(i!=="all"&&re.status!==i)return!1;if(r&&re.scheduled_for){const te=new Date(re.scheduled_for);if(!sf(te,r))return!1}return!0}),E=w.filter(re=>re.scheduled_for).map(re=>Eg(new Date(re.scheduled_for))),I=mt({mutationFn:async re=>{const{error:te}=await q.from("scheduled_posts").update({caption:re.caption,scheduled_for:re.scheduled_for}).eq("id",re.id);if(te)throw te},onSuccess:()=>{ne.success("Post updated!"),n.invalidateQueries({queryKey:["scheduled-posts",t]}),c(null)},onError:re=>{ne.error(`Failed to update: ${re.message}`)}}),P=mt({mutationFn:async re=>{const{error:te}=await q.from("scheduled_posts").update({status:"cancelled"}).eq("id",re);if(te)throw te},onSuccess:()=>{ne.success("Post cancelled"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:re=>{ne.error(`Failed to cancel: ${re.message}`)}}),R=mt({mutationFn:async re=>{const{error:te}=await q.from("scheduled_posts").delete().eq("id",re);if(te)throw te},onSuccess:()=>{ne.success("Post deleted"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:re=>{ne.error(`Failed to delete: ${re.message}`)}}),D=mt({mutationFn:async re=>{const{data:te,error:J}=await q.functions.invoke("social-post",{body:{platform:re.platform,accountId:re.social_account_id,imageUrl:re.image_url,caption:re.caption}});if(J)throw new Error(await jse(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",re.id),te},onSuccess:re=>{const te=re.platform==="facebook"?"Facebook":re.platform==="instagram"?"Instagram":"LinkedIn";ne.success(`Posted to ${te}!`),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:re=>{ne.error(`Failed to post: ${re.message}`)}}),O=re=>{if(c(re),u(re.caption||""),re.scheduled_for){const te=new Date(re.scheduled_for);m(te);const J=te.getHours();g(String(J>12?J-12:J===0?12:J)),v(String(te.getMinutes()).padStart(2,"0")),b(J>=12?"PM":"AM")}},U=()=>{if(!o||!h)return;let re=parseInt(f);const te=parseInt(x);y==="PM"&&re!==12&&(re+=12),y==="AM"&&re===12&&(re=0);const J=Azt(Czt(h,re),te);I.mutate({id:o.id,caption:d,scheduled_for:J.toISOString()})},W=re=>{switch(re){case"facebook":return e.jsx(Zp,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(Ef,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(ly,{className:"h-4 w-4 text-blue-700"});default:return null}},V=re=>{switch(re){case"scheduled":return e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(ca,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs($e,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(Wl,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs($e,{variant:"destructive",className:"gap-1",children:[e.jsx(ju,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs($e,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(vl,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx($e,{variant:"outline",children:re})}},G=Array.from({length:12},(re,te)=>String(te+1)),Z=["00","15","30","45"],X=w.filter(re=>re.status==="scheduled").length,ae=w.filter(re=>re.status==="posted").length,le=w.filter(re=>re.status==="scheduled"&&re.scheduled_for&&JPs(new Date(re.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(je,{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(je,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:le}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(je,{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(je,{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(je,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Wc,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(A2,{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(Sw,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(re=>e.jsx($,{variant:i===re?"default":"outline",size:"sm",onClick:()=>l(re),className:"capitalize",children:re},re))})]}),S&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!S&&A.length===0&&e.jsxs(je,{className:"p-8 text-center",children:[e.jsx(Ea,{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 ${Js(r,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:A.map(re=>{var te,J;return e.jsx(je,{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:re.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(Le,{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(re.platform),e.jsx("span",{className:"font-medium",children:((te=re.social_accounts)==null?void 0:te.page_name)||((J=re.social_accounts)==null?void 0:J.platform_username)||"Unknown"}),V(re.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[re.status==="scheduled"&&e.jsxs(vk,{children:[e.jsxs(ry,{children:[e.jsx(ay,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>O(re),children:e.jsx(pi,{className:"h-4 w-4"})})}),e.jsx(vx,{children:"Edit post"})]}),e.jsxs(ry,{children:[e.jsx(ay,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>D.mutate(re),disabled:D.isPending,children:D.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"})})}),e.jsx(vx,{children:"Post now"})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Cancel this scheduled post?"}),e.jsx(ic,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Keep"}),e.jsx(Yl,{onClick:()=>P.mutate(re.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(Yl,{onClick:()=>R.mutate(re.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(re.status==="posted"||re.status==="cancelled"||re.status==="failed")&&e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Delete this post?"}),e.jsx(ic,{children:"This will permanently remove this post from your history."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:()=>R.mutate(re.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),re.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:re.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ca,{className:"h-3 w-3"}),re.status==="posted"&&re.posted_at?`Posted ${Js(new Date(re.posted_at),"PPp")}`:re.scheduled_for?`Scheduled for ${Js(new Date(re.scheduled_for),"PPp")}`:"Not scheduled"]}),re.status==="failed"&&re.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",re.error_message]})]})]})},re.id)})})]})]}),e.jsx(Os,{open:!!o,onOpenChange:re=>!re&&c(null),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Edit Scheduled Post"}),e.jsx(Er,{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:re=>u(re.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(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("justify-start text-left font-normal flex-1",!h&&"text-muted-foreground"),children:[e.jsx(Ea,{className:"mr-2 h-4 w-4"}),h?Js(h,"PPP"):"Pick a date"]})}),e.jsx(Dd,{className:"w-auto p-0",align:"start",children:e.jsx(A2,{mode:"single",selected:h,onSelect:m,disabled:re=>ree.jsx(Ge,{value:re,children:re},re))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(ms,{value:x,onValueChange:v,children:[e.jsx(us,{className:"w-[70px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:Z.map(re=>e.jsx(Ge,{value:re,children:re},re))})]}),e.jsxs(ms,{value:y,onValueChange:re=>b(re),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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(null),children:"Cancel"}),e.jsxs($,{onClick:U,disabled:I.isPending,children:[I.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function _de(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 OHt={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 _de=="function"&&_de;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 _de=="function"&&_de,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[v++]=d,f!==64&&(b[v++]=u),g!==64&&(b[v++]=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,v="";for(x=0;x>>=8;return v}function l(f,g,x,v,y,b){var w,S,A=f.file,E=f.compression,I=b!==d.utf8encode,P=o.transformTo("string",b(A.name)),R=o.transformTo("string",d.utf8encode(A.name)),D=A.comment,O=o.transformTo("string",b(D)),U=o.transformTo("string",d.utf8encode(D)),W=R.length!==A.name.length,V=U.length!==D.length,G="",Z="",X="",ae=A.dir,le=A.date,re={crc32:0,compressedSize:0,uncompressedSize:0};g&&!x||(re.crc32=f.crc32,re.compressedSize=f.compressedSize,re.uncompressedSize=f.uncompressedSize);var te=0;g&&(te|=8),I||!W&&!V||(te|=2048);var J=0,ce=0;ae&&(J|=16),y==="UNIX"?(ce=798,J|=function(fe,ue){var be=fe;return fe||(be=ue?16893:33204),(65535&be)<<16}(A.unixPermissions,ae)):(ce=20,J|=function(fe){return 63&(fe||0)}(A.dosPermissions)),w=le.getUTCHours(),w<<=6,w|=le.getUTCMinutes(),w<<=5,w|=le.getUTCSeconds()/2,S=le.getUTCFullYear()-1980,S<<=4,S|=le.getUTCMonth()+1,S<<=5,S|=le.getUTCDate(),W&&(Z=i(1,1)+i(u(P),4)+R,G+="up"+i(Z.length,2)+Z),V&&(X=i(1,1)+i(u(O),4)+U,G+="uc"+i(X.length,2)+X);var ve="";return ve+=` \0`,ve+=i(te,2),ve+=E.magic,ve+=i(w,2),ve+=i(S,2),ve+=i(re.crc32,4),ve+=i(re.compressedSize,4),ve+=i(re.uncompressedSize,4),ve+=i(P.length,2),ve+=i(G.length,2),{fileRecord:h.LOCAL_FILE_HEADER+ve+P+G,dirRecord:h.CENTRAL_FILE_HEADER+i(ce,2)+ve+i(O.length,2)+"\0\0\0\0"+i(J,4)+i(v,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,v){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=x,this.encodeFileName=v,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,v=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-v-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(v){return h.DATA_DESCRIPTOR+i(v.crc32,4)+i(v.compressedSize,4)+i(v.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(v,y){var b=[],w=g._internalType,S=g._outputType,A=g._mimeType;g.on("data",function(E,I){b.push(E),x&&x(I)}).on("error",function(E){b=[],y(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,v,y,b,w,S=g.length,A=0;for(b=0;b>>6:(v<65536?x[w++]=224|v>>>12:(x[w++]=240|v>>>18,x[w++]=128|v>>>12&63),x[w++]=128|v>>>6&63),x[w++]=128|63&v);return x}(f)},a.utf8decode=function(f){return l.nodebuffer?i.transformTo("nodebuffer",f).toString("utf-8"):function(g){var x,v,y,b,w=g.length,S=new Array(2*w);for(x=v=0;x>10&1023,S[v++]=56320|1023&y)}return S.length!==v&&(S.subarray?S=S.subarray(0,v):S.length=v),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 v=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),y=g;v!==g.length&&(l.uint8array?(y=g.subarray(0,v),this.leftOver=g.subarray(v,g.length)):(y=g.slice(0,v),this.leftOver=g.slice(v,g.length))),this.push({data:a.utf8decode(y),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,v){for(var y=0;y>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,v,y=f.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});f.index+4>>6:(f<65536?m[v++]=224|f>>>12:(m[v++]=240|f>>>18,m[v++]=128|f>>>12&63),m[v++]=128|f>>>6&63),m[v++]=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,v=4,y=2,b=8,w=9,S=286,A=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,Z=3,X=4;function ae(Se,Ae){return Se.msg=u[Ae],Ae}function le(Se){return(Se<<1)-(4Se.avail_out&&(Ce=Se.avail_out),Ce!==0&&(l.arraySet(Se.output,Ae.pending_buf,Ae.pending_out,Ce,Se.next_out),Se.next_out+=Ce,Ae.pending_out+=Ce,Se.total_out+=Ce,Se.avail_out-=Ce,Ae.pending-=Ce,Ae.pending===0&&(Ae.pending_out=0))}function J(Se,Ae){o._tr_flush_block(Se,0<=Se.block_start?Se.block_start:-1,Se.strstart-Se.block_start,Ae),Se.block_start=Se.strstart,te(Se.strm)}function ce(Se,Ae){Se.pending_buf[Se.pending++]=Ae}function ve(Se,Ae){Se.pending_buf[Se.pending++]=Ae>>>8&255,Se.pending_buf[Se.pending++]=255&Ae}function fe(Se,Ae){var Ce,qe,ze=Se.max_chain_length,Ve=Se.strstart,ht=Se.prev_length,Qe=Se.nice_match,at=Se.strstart>Se.w_size-O?Se.strstart-(Se.w_size-O):0,rt=Se.window,Ke=Se.w_mask,Je=Se.prev,ft=Se.strstart+D,gt=rt[Ve+ht-1],es=rt[Ve+ht];Se.prev_length>=Se.good_match&&(ze>>=2),Qe>Se.lookahead&&(Qe=Se.lookahead);do if(rt[(Ce=Ae)+ht]===es&&rt[Ce+ht-1]===gt&&rt[Ce]===rt[Ve]&&rt[++Ce]===rt[Ve+1]){Ve+=2,Ce++;do;while(rt[++Ve]===rt[++Ce]&&rt[++Ve]===rt[++Ce]&&rt[++Ve]===rt[++Ce]&&rt[++Ve]===rt[++Ce]&&rt[++Ve]===rt[++Ce]&&rt[++Ve]===rt[++Ce]&&rt[++Ve]===rt[++Ce]&&rt[++Ve]===rt[++Ce]&&Veat&&--ze!=0);return ht<=Se.lookahead?ht:Se.lookahead}function ue(Se){var Ae,Ce,qe,ze,Ve,ht,Qe,at,rt,Ke,Je=Se.w_size;do{if(ze=Se.window_size-Se.lookahead-Se.strstart,Se.strstart>=Je+(Je-O)){for(l.arraySet(Se.window,Se.window,Je,Je,0),Se.match_start-=Je,Se.strstart-=Je,Se.block_start-=Je,Ae=Ce=Se.hash_size;qe=Se.head[--Ae],Se.head[Ae]=Je<=qe?qe-Je:0,--Ce;);for(Ae=Ce=Je;qe=Se.prev[--Ae],Se.prev[Ae]=Je<=qe?qe-Je:0,--Ce;);ze+=Je}if(Se.strm.avail_in===0)break;if(ht=Se.strm,Qe=Se.window,at=Se.strstart+Se.lookahead,rt=ze,Ke=void 0,Ke=ht.avail_in,rt=R)for(Ve=Se.strstart-Se.insert,Se.ins_h=Se.window[Ve],Se.ins_h=(Se.ins_h<=R&&(Se.ins_h=(Se.ins_h<=R)if(qe=o._tr_tally(Se,Se.strstart-Se.match_start,Se.match_length-R),Se.lookahead-=Se.match_length,Se.match_length<=Se.max_lazy_match&&Se.lookahead>=R){for(Se.match_length--;Se.strstart++,Se.ins_h=(Se.ins_h<=R&&(Se.ins_h=(Se.ins_h<=R&&Se.match_length<=Se.prev_length){for(ze=Se.strstart+Se.lookahead-R,qe=o._tr_tally(Se,Se.strstart-1-Se.prev_match,Se.prev_length-R),Se.lookahead-=Se.prev_length-1,Se.prev_length-=2;++Se.strstart<=ze&&(Se.ins_h=(Se.ins_h<Se.pending_buf_size-5&&(Ce=Se.pending_buf_size-5);;){if(Se.lookahead<=1){if(ue(Se),Se.lookahead===0&&Ae===h)return V;if(Se.lookahead===0)break}Se.strstart+=Se.lookahead,Se.lookahead=0;var qe=Se.block_start+Ce;if((Se.strstart===0||Se.strstart>=qe)&&(Se.lookahead=Se.strstart-qe,Se.strstart=qe,J(Se,!1),Se.strm.avail_out===0)||Se.strstart-Se.block_start>=Se.w_size-O&&(J(Se,!1),Se.strm.avail_out===0))return V}return Se.insert=0,Ae===m?(J(Se,!0),Se.strm.avail_out===0?Z:X):(Se.strstart>Se.block_start&&(J(Se,!1),Se.strm.avail_out),V)}),new ke(4,4,8,4,be),new ke(4,5,16,8,be),new ke(4,6,32,32,be),new ke(4,4,16,16,Ee),new ke(8,16,32,32,Ee),new ke(8,16,128,128,Ee),new ke(8,32,128,256,Ee),new ke(32,128,258,1024,Ee),new ke(32,258,258,4096,Ee)],a.deflateInit=function(Se,Ae){return Be(Se,Ae,b,15,8,0)},a.deflateInit2=Be,a.deflateReset=Ne,a.deflateResetKeep=Fe,a.deflateSetHeader=function(Se,Ae){return Se&&Se.state?Se.state.wrap!==2?g:(Se.state.gzhead=Ae,f):g},a.deflate=function(Se,Ae){var Ce,qe,ze,Ve;if(!Se||!Se.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&&(Se.adler=d(Se.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 ht=b+(qe.w_bits-8<<4)<<8;ht|=(2<=qe.strategy||qe.level<2?0:qe.level<6?1:qe.level===6?2:3)<<6,qe.strstart!==0&&(ht|=32),ht+=31-ht%31,qe.status=W,ve(qe,ht),qe.strstart!==0&&(ve(qe,Se.adler>>>16),ve(qe,65535&Se.adler)),Se.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&&(Se.adler=d(Se.adler,qe.pending_buf,qe.pending-ze,ze)),te(Se),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&&(Se.adler=d(Se.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&&(Se.adler=d(Se.adler,qe.pending_buf,qe.pending-ze,ze)),te(Se),ze=qe.pending,qe.pending===qe.pending_buf_size)){Ve=1;break}Ve=qe.gzindexze&&(Se.adler=d(Se.adler,qe.pending_buf,qe.pending-ze,ze)),Ve===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&&(Se.adler=d(Se.adler,qe.pending_buf,qe.pending-ze,ze)),te(Se),ze=qe.pending,qe.pending===qe.pending_buf_size)){Ve=1;break}Ve=qe.gzindexze&&(Se.adler=d(Se.adler,qe.pending_buf,qe.pending-ze,ze)),Ve===0&&(qe.status=103)}else qe.status=103;if(qe.status===103&&(qe.gzhead.hcrc?(qe.pending+2>qe.pending_buf_size&&te(Se),qe.pending+2<=qe.pending_buf_size&&(ce(qe,255&Se.adler),ce(qe,Se.adler>>8&255),Se.adler=0,qe.status=W)):qe.status=W),qe.pending!==0){if(te(Se),Se.avail_out===0)return qe.last_flush=-1,f}else if(Se.avail_in===0&&le(Ae)<=le(Ce)&&Ae!==m)return ae(Se,-5);if(qe.status===666&&Se.avail_in!==0)return ae(Se,-5);if(Se.avail_in!==0||qe.lookahead!==0||Ae!==h&&qe.status!==666){var Qe=qe.strategy===2?function(at,rt){for(var Ke;;){if(at.lookahead===0&&(ue(at),at.lookahead===0)){if(rt===h)return V;break}if(at.match_length=0,Ke=o._tr_tally(at,0,at.window[at.strstart]),at.lookahead--,at.strstart++,Ke&&(J(at,!1),at.strm.avail_out===0))return V}return at.insert=0,rt===m?(J(at,!0),at.strm.avail_out===0?Z:X):at.last_lit&&(J(at,!1),at.strm.avail_out===0)?V:G}(qe,Ae):qe.strategy===3?function(at,rt){for(var Ke,Je,ft,gt,es=at.window;;){if(at.lookahead<=D){if(ue(at),at.lookahead<=D&&rt===h)return V;if(at.lookahead===0)break}if(at.match_length=0,at.lookahead>=R&&0at.lookahead&&(at.match_length=at.lookahead)}if(at.match_length>=R?(Ke=o._tr_tally(at,1,at.match_length-R),at.lookahead-=at.match_length,at.strstart+=at.match_length,at.match_length=0):(Ke=o._tr_tally(at,0,at.window[at.strstart]),at.lookahead--,at.strstart++),Ke&&(J(at,!1),at.strm.avail_out===0))return V}return at.insert=0,rt===m?(J(at,!0),at.strm.avail_out===0?Z:X):at.last_lit&&(J(at,!1),at.strm.avail_out===0)?V:G}(qe,Ae):i[qe.level].func(qe,Ae);if(Qe!==Z&&Qe!==X||(qe.status=666),Qe===V||Qe===Z)return Se.avail_out===0&&(qe.last_flush=-1),f;if(Qe===G&&(Ae===1?o._tr_align(qe):Ae!==5&&(o._tr_stored_block(qe,0,0,!1),Ae===3&&(re(qe.head),qe.lookahead===0&&(qe.strstart=0,qe.block_start=0,qe.insert=0))),te(Se),Se.avail_out===0))return qe.last_flush=-1,f}return Ae!==m?f:qe.wrap<=0?1:(qe.wrap===2?(ce(qe,255&Se.adler),ce(qe,Se.adler>>8&255),ce(qe,Se.adler>>16&255),ce(qe,Se.adler>>24&255),ce(qe,255&Se.total_in),ce(qe,Se.total_in>>8&255),ce(qe,Se.total_in>>16&255),ce(qe,Se.total_in>>24&255)):(ve(qe,Se.adler>>>16),ve(qe,65535&Se.adler)),te(Se),0=Ce.w_size&&(Ve===0&&(re(Ce.head),Ce.strstart=0,Ce.block_start=0,Ce.insert=0),rt=new l.Buf8(Ce.w_size),l.arraySet(rt,Ae,Ke-Ce.w_size,Ce.w_size,0),Ae=rt,Ke=Ce.w_size),ht=Se.avail_in,Qe=Se.next_in,at=Se.input,Se.avail_in=Ke,Se.next_in=0,Se.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=A[(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(v),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 A(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<(Z=X.wsize-X.wnext)&&(Z=G),i.arraySet(X.window,W,V-G,Z,X.wnext),(G-=Z)?(i.arraySet(X.window,W,V-G,G,0),X.wnext=G,X.whave=X.wsize):(X.wnext+=Z,X.wnext===X.wsize&&(X.wnext=0),X.whave>>8&255,V.check=o(V.check,Ve,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,Se=8+(15&(te>>>=4)),V.wbits===0)V.wbits=Se;else if(Se>V.wbits){U.msg="invalid window size",V.mode=30;break}V.dmax=1<>8&1),512&V.flags&&(Ve[0]=255&te,Ve[1]=te>>>8&255,V.check=o(V.check,Ve,2,0)),J=te=0,V.mode=3;case 3:for(;J<32;){if(le===0)break e;le--,te+=G[X++]<>>8&255,Ve[2]=te>>>16&255,Ve[3]=te>>>24&255,V.check=o(V.check,Ve,4,0)),J=te=0,V.mode=4;case 4:for(;J<16;){if(le===0)break e;le--,te+=G[X++]<>8),512&V.flags&&(Ve[0]=255&te,Ve[1]=te>>>8&255,V.check=o(V.check,Ve,2,0)),J=te=0,V.mode=5;case 5:if(1024&V.flags){for(;J<16;){if(le===0)break e;le--,te+=G[X++]<>>8&255,V.check=o(V.check,Ve,2,0)),J=te=0}else V.head&&(V.head.extra=null);V.mode=6;case 6:if(1024&V.flags&&(le<(fe=V.length)&&(fe=le),fe&&(V.head&&(Se=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,fe,Se)),512&V.flags&&(V.check=o(V.check,G,fe,X)),le-=fe,X+=fe,V.length-=fe),V.length))break e;V.length=0,V.mode=7;case 7:if(2048&V.flags){if(le===0)break e;for(fe=0;Se=G[X+fe++],V.head&&Se&&V.length<65536&&(V.head.name+=String.fromCharCode(Se)),Se&&fe>9&1,V.head.done=!0),U.adler=V.check=0,V.mode=12;break;case 10:for(;J<32;){if(le===0)break e;le--,te+=G[X++]<>>=7&J,J-=7&J,V.mode=27;break}for(;J<3;){if(le===0)break e;le--,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(le===0)break e;le--,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(fe=V.length){if(le>>=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[ht[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,Ie=65535&ze,!((Ee=ze>>>24)<=J);){if(le===0)break e;le--,te+=G[X++]<>>=Ee,J-=Ee,V.lens[V.have++]=Ie;else{if(Ie===16){for(qe=Ee+2;J>>=Ee,J-=Ee,V.have===0){U.msg="invalid bit length repeat",V.mode=30;break}Se=V.lens[V.have-1],fe=3+(3&te),te>>>=2,J-=2}else if(Ie===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+fe>V.nlen+V.ndist){U.msg="invalid bit length repeat",V.mode=30;break}for(;fe--;)V.lens[V.have++]=Se}}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<=le&&258<=re){U.next_out=ae,U.avail_out=re,U.next_in=X,U.avail_in=le,V.hold=te,V.bits=J,c(U,ve),ae=U.next_out,Z=U.output,re=U.avail_out,X=U.next_in,G=U.input,le=U.avail_in,te=V.hold,J=V.bits,V.mode===12&&(V.back=-1);break}for(V.back=0;ke=(ze=V.lencode[te&(1<>>16&255,Ie=65535&ze,!((Ee=ze>>>24)<=J);){if(le===0)break e;le--,te+=G[X++]<>Fe)])>>>16&255,Ie=65535&ze,!(Fe+(Ee=ze>>>24)<=J);){if(le===0)break e;le--,te+=G[X++]<>>=Fe,J-=Fe,V.back+=Fe}if(te>>>=Ee,J-=Ee,V.back+=Ee,V.length=Ie,ke===0){V.mode=26;break}if(32&ke){V.back=-1,V.mode=12;break}if(64&ke){U.msg="invalid literal/length code",V.mode=30;break}V.extra=15&ke,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(;ke=(ze=V.distcode[te&(1<>>16&255,Ie=65535&ze,!((Ee=ze>>>24)<=J);){if(le===0)break e;le--,te+=G[X++]<>Fe)])>>>16&255,Ie=65535&ze,!(Fe+(Ee=ze>>>24)<=J);){if(le===0)break e;le--,te+=G[X++]<>>=Fe,J-=Fe,V.back+=Fe}if(te>>>=Ee,J-=Ee,V.back+=Ee,64&ke){U.msg="invalid distance code",V.mode=30;break}V.offset=Ie,V.extra=15&ke,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(re===0)break e;if(fe=ve-re,V.offset>fe){if((fe=V.offset-fe)>V.whave&&V.sane){U.msg="invalid distance too far back",V.mode=30;break}ue=fe>V.wnext?(fe-=V.wnext,V.wsize-fe):V.wnext-fe,fe>V.length&&(fe=V.length),be=V.window}else be=Z,ue=ae-V.offset,fe=V.length;for(reI?(R=ue[be+v[W]],J[ce+v[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++,--ve[U]==0){if(U===G)break;U=h[m+v[W]]}if(Z>>7)]}function ce(ze,Ve){ze.pending_buf[ze.pending++]=255&Ve,ze.pending_buf[ze.pending++]=Ve>>>8&255}function ve(ze,Ve,ht){ze.bi_valid>y-ht?(ze.bi_buf|=Ve<>y-ze.bi_valid,ze.bi_valid+=ht-y):(ze.bi_buf|=Ve<>>=1,ht<<=1,0<--Ve;);return ht>>>1}function be(ze,Ve,ht){var Qe,at,rt=new Array(v+1),Ke=0;for(Qe=1;Qe<=v;Qe++)rt[Qe]=Ke=Ke+ht[Qe-1]<<1;for(at=0;at<=Ve;at++){var Je=ze[2*at+1];Je!==0&&(ze[2*at]=ue(rt[Je]++,Je))}}function Ee(ze){var Ve;for(Ve=0;Ve>1;1<=ht;ht--)Fe(ze,rt,ht);for(at=ft;ht=ze.heap[1],ze.heap[1]=ze.heap[ze.heap_len--],Fe(ze,rt,1),Qe=ze.heap[1],ze.heap[--ze.heap_max]=ht,ze.heap[--ze.heap_max]=Qe,rt[2*at]=rt[2*ht]+rt[2*Qe],ze.depth[at]=(ze.depth[ht]>=ze.depth[Qe]?ze.depth[ht]:ze.depth[Qe])+1,rt[2*ht+1]=rt[2*Qe+1]=at,ze.heap[1]=at++,Fe(ze,rt,1),2<=ze.heap_len;);ze.heap[--ze.heap_max]=ze.heap[1],function(es,Ht){var as,bs,Ut,Ft,is,jt,zs=Ht.dyn_tree,yt=Ht.max_code,gs=Ht.stat_desc.static_tree,Ss=Ht.stat_desc.has_stree,Ds=Ht.stat_desc.extra_bits,Bt=Ht.stat_desc.extra_base,zt=Ht.stat_desc.max_length,vs=0;for(Ft=0;Ft<=v;Ft++)es.bl_count[Ft]=0;for(zs[2*es.heap[es.heap_max]+1]=0,as=es.heap_max+1;as>=7;at>>=1)if(1>&&Je.dyn_ltree[2*ft]!==0)return l;if(Je.dyn_ltree[18]!==0||Je.dyn_ltree[20]!==0||Je.dyn_ltree[26]!==0)return o;for(ft=32;ft>>3,(rt=ze.static_len+3+7>>>3)<=at&&(at=rt)):at=rt=ht+5,ht+4<=at&&Ve!==-1?qe(ze,Ve,ht,Qe):ze.strategy===4||rt===at?(ve(ze,2+(Qe?1:0),3),Ne(ze,O,U)):(ve(ze,4+(Qe?1:0),3),function(Je,ft,gt,es){var Ht;for(ve(Je,ft-257,5),ve(Je,gt-1,5),ve(Je,es-4,4),Ht=0;Ht>>8&255,ze.pending_buf[ze.d_buf+2*ze.last_lit+1]=255&Ve,ze.pending_buf[ze.l_buf+ze.last_lit]=255&ht,ze.last_lit++,Ve===0?ze.dyn_ltree[2*ht]++:(ze.matches++,Ve--,ze.dyn_ltree[2*(V[ht]+h+1)]++,ze.dyn_dtree[2*J(Ve)]++),ze.last_lit===ze.lit_bufsize-1},a._tr_align=function(ze){ve(ze,2,3),fe(ze,w,O),function(Ve){Ve.bi_valid===16?(ce(Ve,Ve.bi_buf),Ve.bi_buf=0,Ve.bi_valid=0):8<=Ve.bi_valid&&(Ve.pending_buf[Ve.pending++]=255&Ve.bi_buf,Ve.bi_buf>>=8,Ve.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,v=Object.getPrototypeOf&&Object.getPrototypeOf(l);v=v&&v.setTimeout?v:l,c={}.toString.call(l.process)==="[object process]"?function(S){process.nextTick(function(){b(S)})}:function(){if(l.postMessage&&!l.importScripts){var S=!0,A=l.onmessage;return l.onmessage=function(){S=!1},l.postMessage("","*"),l.onmessage=A,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 A=x.createElement("script");A.onreadystatechange=function(){b(S),A.onreadystatechange=null,d.removeChild(A),A=null},d.appendChild(A)}):function(S){setTimeout(b,0,S)},v.setImmediate=function(S){typeof S!="function"&&(S=new Function(""+S));for(var A=new Array(arguments.length-1),E=0;E"u"?i===void 0?this:i:self)}).call(this,typeof kp<"u"?kp:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(OHt);var cin=OHt.exports;const zHt=ru(cin);function MBe(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 BHt=({embedded:s=!1,onCompose:t}={})=>{const{isAdmin:n}=_s(),[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,v]=j.useState("images"),[y,b]=j.useState(null),{data:w=[],isLoading:S}=st({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:A=[]}=st({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=[]}=st({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=[]}=st({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,ve)=>ve.localeCompare(ce)),[w]);j.useEffect(()=>{D.length>0&&o==="all"&&c(D[0])},[D,o]);const O=J=>{try{const ce=wtt(J,"yyyy-MM",new Date);return Js(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=A.find(ce=>ce.month===o))==null?void 0:J.canva_link)||null},[o,A]),V=async J=>{try{await navigator.clipboard.writeText(J),ne.success("Caption copied to clipboard!")}catch{ne.error("Failed to copy caption")}},G=async(J,ce)=>{try{const fe=await(await fetch(J)).blob(),ue=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),be=navigator.canShare&&navigator.canShare({files:[new File([fe],"test.jpg",{type:"image/jpeg"})]});if(ue&&be){const Ee=new File([fe],`social-swag-${ce}.jpg`,{type:"image/jpeg"});await navigator.share({files:[Ee],title:"Social Swag Image"}),ne.success("Image ready to save!")}else{const Ee=window.URL.createObjectURL(fe),ke=document.createElement("a");ke.href=Ee,ke.download=`social-swag-${ce}.jpg`,document.body.appendChild(ke),ke.click(),document.body.removeChild(ke),window.URL.revokeObjectURL(Ee),ne.success("Image downloaded!")}}catch(ve){ve.name!=="AbortError"&&ne.error("Failed to download image")}},Z=J=>{u(ce=>{const ve=new Set(ce);return ve.has(J)?ve.delete(J):ve.add(J),ve})},X=()=>{u(new Set(U.map(J=>J.id)))},ae=()=>{u(new Set),m(!1)},le=async()=>{const J=U.filter(ce=>d.has(ce.id));if(J.length===0){ne.error("No images selected");return}g(!0),ne.info(`Preparing ${J.length} images for download...`);try{const ce=new zHt,ve=[...J].sort((ke,Ie)=>ke.sort_order-Ie.sort_order);for(let ke=0;ke{h?Z(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($e,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(wn,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs($e,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Hc,{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(pa,{defaultValue:"gallery",className:"space-y-6",children:[!s&&e.jsxs(ga,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(Xt,{value:"gallery",className:"gap-2",children:[e.jsx(Hc,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Xt,{value:"scheduled",className:"gap-2",children:[e.jsx(Wc,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(Qt,{value:"gallery",className:"space-y-6",children:[P?e.jsx(je,{className:"border rounded-xl",children:e.jsx(Le,{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(br,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(je,{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(Le,{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(Zp,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(Ef,{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(br,{to:"/social-connections",children:[e.jsx(nu,{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:()=>{v("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(Hc,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{v("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(nf,{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(mr,{className:"h-4 w-4"}),"Cancel"]}),d.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs($,{size:"sm",onClick:le,disabled:f,className:"gap-2",children:[e.jsx(ji,{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(ma,{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(je,{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:()=>re(J),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:MBe(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:Js(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(ma,{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(Hc,{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(je,{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:MBe(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($e,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(nf,{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(nf,{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(Os,{open:!!r,onOpenChange:()=>a(null),children:e.jsx(Fs,{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:MBe(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(Ea,{className:"h-4 w-4"}),Js(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(Ea,{className:"h-3.5 w-3.5"}),"Post on ",Js(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(Zr,{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(Za,{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(ji,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(Os,{open:!!i,onOpenChange:()=>l(null),children:e.jsx(Fs,{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(nf,{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(Za,{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(Ir,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(oin,{open:!!y,onOpenChange:J=>!J&&b(null),imageUrl:(y==null?void 0:y.imageUrl)||"",imageId:(y==null?void 0:y.imageId)||"",defaultCaption:(y==null?void 0:y.caption)||"",swagItemId:y==null?void 0:y.imageId})]}),e.jsx(Qt,{value:"scheduled",children:e.jsx(lin,{})})]})]})})},p_t={facebook:{id:"facebook",label:"Facebook Page",icon:Zp,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:Ef,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:ly,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:ui,dot:"bg-emerald-600",chip:"bg-emerald-600/10 text-emerald-700 border-emerald-600/20",captionLimit:1500,supportsVideo:!1,requiresMedia:!1}},F4=s=>p_t[s]??p_t.facebook,din=[{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}],g_t="agent-uploads",uin="social-studio",hin=200*1024*1024,x_t=s=>typeof s=="number"?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"";function min({onSelect:s}){const{user:t}=_s(),n=j.useRef(null),[r,a]=j.useState(!1),{data:i=[]}=st({queryKey:["studio-uploads",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const{data:d,error:u}=await q.from("social_media_assets").select("*").eq("user_id",t.id).order("created_at",{ascending:!1}).limit(60);if(u)throw u;return d??[]}}),{data:l=[]}=st({queryKey:["studio-swag"],queryFn:async()=>{const{data:d,error:u}=await q.from("social_swag_2").select("id, image_url, caption, month").order("month",{ascending:!1}).order("sort_order").limit(120);if(u)throw u;return d??[]}}),{data:o=[]}=st({queryKey:["studio-listings",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const{data:d,error:u}=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(u)throw u;return d??[]}}),c=async d=>{if(!(t!=null&&t.id))return;if(d.size>hin){ne.error("That file is over 200MB. Please pick a smaller one.");return}const u=d.type.startsWith("video/");a(!0);try{const h=d.name.split(".").pop()||(u?"mp4":"jpg"),m=`${uin}/${t.id}/${crypto.randomUUID()}.${h}`,{error:f}=await q.storage.from(g_t).upload(m,d,{cacheControl:"3600",upsert:!1,contentType:d.type});if(f)throw f;const{data:g}=q.storage.from(g_t).getPublicUrl(m),x=g.publicUrl;await q.from("social_media_assets").insert({user_id:t.id,storage_path:m,public_url:x,media_type:u?"video":"image",file_name:d.name,file_size:d.size}),s({mediaUrl:x,mediaType:u?"video":"image",source:"upload"}),ne.success("Media uploaded")}catch(h){console.error(h),ne.error("Upload failed. Please try again.")}finally{a(!1),n.current&&(n.current.value="")}};return e.jsxs(pa,{defaultValue:"upload",className:"space-y-4",children:[e.jsxs(ga,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Xt,{value:"upload",className:"gap-2",children:[e.jsx(ni,{className:"h-4 w-4"}),"Upload"]}),e.jsxs(Xt,{value:"swag",className:"gap-2",children:[e.jsx(wn,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Xt,{value:"listings",className:"gap-2",children:[e.jsx(va,{className:"h-4 w-4"}),"Listings"]})]}),e.jsxs(Qt,{value:"upload",className:"space-y-4",children:[e.jsx("input",{ref:n,type:"file",accept:"image/*,video/*",className:"hidden",onChange:d=>{var u;return((u=d.target.files)==null?void 0:u[0])&&c(d.target.files[0])}}),e.jsx(je,{className:"border-dashed border-2",children:e.jsxs(Le,{className:"p-6 flex flex-col items-center text-center gap-3",children:[e.jsx(Hc,{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 d;return(d=n.current)==null?void 0:d.click()},disabled:r,className:"gap-2",children:[r?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(ni,{className:"h-4 w-4"}),r?"Uploading…":"Choose file"]})]})}),i.length>0&&e.jsx(go,{className:"h-56",children:e.jsx("div",{className:"grid grid-cols-3 gap-2 pr-3",children:i.map(d=>e.jsxs("button",{type:"button",onClick:()=>s({mediaUrl:d.public_url,mediaType:d.media_type,source:"upload"}),className:"relative overflow-hidden rounded-lg border hover:ring-2 hover:ring-primary transition",children:[d.media_type==="video"?e.jsx("video",{src:d.public_url,className:"h-24 w-full object-cover"}):e.jsx("img",{src:d.public_url,alt:d.file_name??"",loading:"lazy",className:"h-24 w-full object-cover"}),d.media_type==="video"&&e.jsx($e,{className:"absolute bottom-1 left-1 text-[10px]",children:"Video"})]},d.id))})})]}),e.jsx(Qt,{value:"swag",children:e.jsx(go,{className:"h-72",children:e.jsx("div",{className:"grid grid-cols-3 gap-2 pr-3",children:l.map(d=>e.jsx("button",{type:"button",onClick:()=>s({mediaUrl:d.image_url,mediaType:"image",caption:d.caption??"",source:"swag",sourceRef:d.id}),className:"overflow-hidden rounded-lg border hover:ring-2 hover:ring-primary transition",children:e.jsx("img",{src:d.image_url,alt:"",loading:"lazy",className:"h-24 w-full object-cover"})},d.id))})})}),e.jsx(Qt,{value:"listings",children:e.jsx(go,{className:"h-72",children:e.jsxs("div",{className:"space-y-3 pr-3",children:[o.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"You don't have any listings yet."}),o.map(d=>{const u=[...d.listing_photos??[]].sort((m,f)=>Number(f.is_primary)-Number(m.is_primary)||m.sort_order-f.sort_order),h=[`${d.property_address??""}`.trim(),`${d.city}, ${d.state}`,x_t(d.price),[d.bedrooms?`${d.bedrooms} bed`:null,d.bathrooms?`${d.bathrooms} bath`:null,d.square_footage?`${d.square_footage.toLocaleString()} sq ft`:null].filter(Boolean).join(" · "),"DM me for a private tour."].filter(Boolean).join(` `);return e.jsx(je,{children:e.jsxs(Le,{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:d.property_address||`${d.city}, ${d.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x_t(d.price)})]}),e.jsx($e,{variant:"secondary",className:"capitalize",children:String(d.status).replace(/_/g," ")})]}),u.length>0?e.jsx("div",{className:"grid grid-cols-4 gap-2",children:u.slice(0,8).map((m,f)=>e.jsx("button",{type:"button",onClick:()=>s({mediaUrl:m.photo_url,mediaType:"image",caption:h,source:"listing",sourceRef:d.id}),className:"overflow-hidden rounded-md border hover:ring-2 hover:ring-primary transition",children:e.jsx("img",{src:m.photo_url,alt:"",loading:"lazy",className:"h-16 w-full object-cover"})},f))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No photos on this listing yet."})]})},d.id)})]})})})]})}function fin({platform:s,accountName:t,avatarUrl:n,caption:r,mediaUrl:a,mediaType:i}){const l=F4(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(je,{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(Ii,{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(Ah,{className:"h-5 w-5"}),e.jsx(Zr,{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($y,{className:"h-4 w-4"})," Like"]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(Ah,{className:"h-4 w-4"})," Comment"]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(WJ,{className:"h-4 w-4"})," Share"]})]})]})]})}function drt(){const{user:s}=_s();return st({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 pin(s){const{user:t}=_s();return st({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 $Ht(){const s=Zt();return()=>{s.invalidateQueries({queryKey:["studio-posts"]}),s.invalidateQueries({queryKey:["studio-accounts"]})}}const gin="America/New_York",UHt="levelup.calendar.timezone";function h7(s){if(!s)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:s}),!0}catch{return!1}}function xin(){try{const s=localStorage.getItem(UHt);if(h7(s))return s}catch{}return null}let g3e=xin();function TT(){return g3e||mie()}function y_t(s){g3e=h7(s)?s:mie();try{localStorage.setItem(UHt,g3e)}catch{}return g3e}function mie(){const s=Intl.DateTimeFormat().resolvedOptions().timeZone;return h7(s)?s:gin}function lL(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 PBe(s,t=new Date){try{return new Intl.DateTimeFormat("en-US",{timeZone:s,hour:"numeric",minute:"2-digit"}).format(t)}catch{return""}}const qHt=[{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 yin(){var r;let s=[];try{s=((r=Intl.supportedValuesOf)==null?void 0:r.call(Intl,"timeZone"))||[]}catch{s=[]}const t=qHt.map(a=>a.value),n=s.filter(a=>!t.includes(a));return[...t,...n]}function vin(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 pK(){const{user:s}=_s(),t=Zt(),n=st({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&&h7(n.data)&&y_t(n.data)},[n.data]);const r=h7(n.data)?n.data:TT()||mie(),a=mt({mutationFn:async i=>{if(!h7(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:vin(s.email,s.id),timezone:i,is_active:!1});if(c)throw c}return y_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"]}),ne.success("Calendar timezone updated")},onError:i=>ne.error(i.message||"Could not update timezone")});return{timezone:r,isLoading:n.isLoading,update:a}}function VHt({open:s,onOpenChange:t}){const{timezone:n,update:r}=pK(),[a,i]=j.useState(n),[l,o]=j.useState("");j.useEffect(()=>{s&&(i(n),o(""))},[s,n]);const c=mie(),d=j.useMemo(()=>{const h=l.trim().toLowerCase();return h?yin().filter(m=>m.toLowerCase().includes(h.replace(/\s+/g,"_"))).slice(0,40):[]},[l]),u=()=>{r.mutate(a,{onSuccess:()=>t(!1)})};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(kN,{className:"h-4 w-4 text-primary"}),"Calendar settings"]}),e.jsx(Er,{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:["· ",PBe(a)," ",lL(a)]})]})]}),c!==a&&e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"w-full justify-start gap-2",onClick:()=>i(c),children:[e.jsx(ui,{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:qHt.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($e,{variant:"secondary",className:"text-[10px]",children:PBe(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:PBe(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(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Save timezone"]})]})]})})}const n4=s=>String(s).padStart(2,"0");function fie(s){return h7(s)?s:TT()}function urt(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 v_t(s,t){const n=urt(s,t);return Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second)-s.getTime()}function DTe(s,t){const n=fie(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-v_t(new Date(u),n));return h=new Date(u-v_t(h,n)),h}function HHt(s,t){const n=fie(t),r=typeof s=="string"?new Date(s):s,a=urt(r,n);return`${a.year}-${n4(a.month)}-${n4(a.day)}T${n4(a.hour)}:${n4(a.minute)}`}function bin(s,t){const n=fie(t),r=typeof s=="string"?new Date(s):s,a=urt(r,n);return`${a.year}-${a.month-1}-${a.day}`}function GHt(s,t,n){const r=typeof s=="string"?new Date(s):s;return new Intl.DateTimeFormat("en-US",{timeZone:fie(t),...n}).format(r)}function WHt(s,t){return GHt(s,t,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function _in(s,t){return GHt(s,t,{hour:"numeric",minute:"2-digit"})}function win(s,t,n,r){const a=fie(n),i=r&&r.includes("T")?r.split("T")[0]:HHt(new Date,a).split("T")[0];let l=`${i}T${n4(s)}:${n4(t)}`;if(DTe(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()}-${n4(u.getUTCMonth()+1)}-${n4(u.getUTCDate())}T${n4(s)}:${n4(t)}`}return l}const wde=s=>s.page_name||s.platform_username||F4(s.platform).label;function jin({seed:s,editingPost:t,onSaved:n,onCancelEdit:r}){const{user:a}=_s(),{data:i=[],isLoading:l}=drt(),{timezone:o}=pK(),[c,d]=j.useState(!1),u=ue=>HHt(ue,o),[h,m]=j.useState(""),[f,g]=j.useState(null),[x,v]=j.useState("text"),[y,b]=j.useState("manual"),[w,S]=j.useState([]),[A,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),v(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 be;if(!t)return;m(t.caption??""),g(((be=t.media_urls)==null?void 0:be[0])??null),v(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]),Z=ue=>{var be;return I&&((be=A[ue])!=null&&be.trim())?A[ue]:h},X=j.useMemo(()=>{const ue=[];return G.forEach(be=>{const Ee=F4(be.platform),ke=Z(be.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.`),ke.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,A,I]),ae=()=>{m(""),g(null),v("text"),b("manual"),S([]),E({}),P(!1),D(!1),U("")},le=ue=>{g(ue.mediaUrl),v(ue.mediaType),b(ue.source),ue.caption&&!h.trim()&&m(ue.caption)},re=ue=>S(be=>be.includes(ue)?be.filter(Ee=>Ee!==ue):[...be,ue]),te=async ue=>{if(a!=null&&a.id){if(ue!=="draft"&&w.length===0){ne.error("Choose at least one account to post to.");return}if(ue!=="draft"&&!h.trim()&&!f){ne.error("Add a caption or media before publishing.");return}if(ue==="schedule"&&!O){ne.error("Pick a date and time to schedule.");return}if(ue!=="draft"&&X.length>0){ne.error(X[0]);return}V(ue);try{const be={user_id:a.id,caption:h.trim()||null,media_type:x,media_urls:f?[f]:[],source:y,status:ue==="draft"?"draft":ue==="schedule"?"scheduled":"publishing",scheduled_for:ue==="schedule"?DTe(O,o).toISOString():null,timezone:o};let Ee=(t==null?void 0:t.id)??null;if(Ee){const{error:ke}=await q.from("social_posts").update(be).eq("id",Ee);if(ke)throw ke;await q.from("social_post_targets").delete().eq("post_id",Ee)}else{const{data:ke,error:Ie}=await q.from("social_posts").insert(be).select("id").single();if(Ie)throw Ie;Ee=ke.id}if(w.length>0){const ke=G.map(Fe=>{var Ne;return{post_id:Ee,user_id:a.id,social_account_id:Fe.id,platform:Fe.platform,caption_override:I&&((Ne=A[Fe.id])!=null&&Ne.trim())?A[Fe.id].trim():null,status:"pending"}}),{error:Ie}=await q.from("social_post_targets").insert(ke);if(Ie)throw Ie}if(ue==="now"){const{data:ke,error:Ie}=await q.functions.invoke("social-publish-post",{body:{post_id:Ee}});if(Ie)throw Ie;const Fe=ke==null?void 0:ke.status;Fe==="failed"?ne.error("Publishing failed. Check the Queue tab for details."):Fe==="partial"?ne.warning("Some accounts failed. Check the Queue tab to retry."):ne.success("Posted to your accounts.")}else ne.success(ue==="draft"?"Draft saved":"Post scheduled");t||ae(),n==null||n()}catch(be){console.error(be),ne.error((be==null?void 0:be.message)??"Something went wrong saving your post.")}finally{V(null)}}},J=(ue,be)=>{D(!0),U(win(ue,be,o,O))},ce=lL(o),ve=mie(),fe=ve!==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(Nse,{children:e.jsxs(kse,{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(mr,{className:"h-4 w-4"})," Cancel"]})]})}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-base",children:"1. Choose your media"})}),e.jsxs(Le,{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),v("text")},children:e.jsx(qn,{className:"h-4 w-4"})})]}),e.jsx(min,{onSelect:le})]})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-base",children:"2. Write your caption"})}),e.jsxs(Le,{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(jn,{id:"per-platform",checked:I,onCheckedChange:P})]})]}),I&&G.length>0&&e.jsxs(pa,{defaultValue:G[0].id,className:"pt-2",children:[e.jsx(ga,{className:"flex-wrap h-auto",children:G.map(ue=>e.jsx(Xt,{value:ue.id,className:"text-xs",children:wde(ue)},ue.id))}),G.map(ue=>e.jsx(Qt,{value:ue.id,className:"pt-3",children:e.jsx(Rs,{rows:5,value:A[ue.id]??"",placeholder:`Leave blank to use the main caption for ${F4(ue.platform).label}`,onChange:be=>E(Ee=>({...Ee,[ue.id]:be.target.value}))})},ue.id))]})]})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-base",children:"3. Pick your accounts"})}),e.jsxs(Le,{className:"space-y-3",children:[l&&e.jsx(Ct,{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 be=F4(ue.platform),Ee=be.icon,ke=w.includes(ue.id);return e.jsxs("button",{type:"button",onClick:()=>re(ue.id),className:`flex items-center gap-3 rounded-lg border p-3 text-left transition ${ke?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs(Oa,{className:"h-9 w-9",children:[e.jsx(Ii,{src:ue.profile_picture_url??void 0}),e.jsx(za,{children:wde(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:wde(ue)}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ee,{className:"h-3 w-3"})," ",be.label]})]}),ke&&e.jsx(ma,{className:"h-4 w-4 text-primary"})]},ue.id)})})]})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-base",children:"4. Publish or schedule"})}),e.jsxs(Le,{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(jn,{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(kN,{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:WHt(DTe(O,o),o)})]}),fe&&e.jsxs("p",{className:"text-xs text-amber-600",children:["Your device is set to ",ve.replace(/_/g," ")," — posts still go out on your ",ce||"saved"," schedule."]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:din.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(Nse,{variant:"destructive",children:[e.jsx(Al,{className:"h-4 w-4"}),e.jsx(kse,{children:e.jsx("ul",{className:"list-disc pl-4 space-y-1",children:X.map(ue=>e.jsx("li",{children:ue},ue))})})]}),e.jsx(Vc,{}),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(Ct,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Su,{className:"h-4 w-4"}),"Schedule post"]}):e.jsxs($,{onClick:()=>te("now"),disabled:!!W,className:"gap-2",children:[W==="now"?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{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($e,{variant:"secondary",children:[G.length," selected"]})]}),G.length===0?e.jsx(je,{children:e.jsx(Le,{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(fin,{platform:ue.platform,accountName:wde(ue),avatarUrl:ue.profile_picture_url,caption:Z(ue.id),mediaUrl:f,mediaType:x},ue.id))})]}),e.jsx(VHt,{open:c,onOpenChange:d})]})}const Nin=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],b_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 kin({posts:s,onCreateAt:t,onOpenPost:n}){const{timezone:r}=pK(),a=lL(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=bin(f,r);h.set(g,[...h.get(g)??[],m])}),h},[s,r]),d=new Date,u=h=>h.toDateString()===d.toDateString();return e.jsx(je,{children:e.jsxs(Le,{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(kd,{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:Nin.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(cn,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"mt-1 space-y-1",children:[f.slice(0,3).map(x=>{var y;const v=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 ${b_t[x.status]??b_t.draft}`,children:[e.jsx("span",{className:"font-medium",children:_in(v,r)})," ",e.jsx("span",{className:"truncate",children:((y=x.caption)==null?void 0:y.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 ${F4(b.platform).dot}`},b.id))})]},x.id)}),f.length>3&&e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:["+",f.length-3," more"]})]})]},m)})})]})})}const Sin=s=>{switch(s){case"published":case"success":return{label:"Published",variant:"default",icon:Vr};case"partial":return{label:"Partly published",variant:"secondary",icon:Al};case"failed":return{label:"Failed",variant:"destructive",icon:Al};case"publishing":case"pending":return{label:"Publishing",variant:"secondary",icon:Ct};case"scheduled":return{label:"Scheduled",variant:"outline",icon:Su};default:return{label:"Draft",variant:"outline",icon:pi}}};function __t({posts:s,accounts:t,onEdit:n,onChanged:r,emptyLabel:a}){const[i,l]=j.useState(null),{timezone:o}=pK(),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"?ne.error("Publishing failed. See the error details below."):g==="partial"?ne.warning("Some accounts failed."):ne.success("Published."),r()}catch(m){ne.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;ne.success("Post deleted"),r()}catch(m){ne.error((m==null?void 0:m.message)??"Could not delete this post.")}finally{l(null)}};return s.length===0?e.jsx(je,{children:e.jsx(Le,{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 v,y;const f=h.status==="failed"&&!!((v=h.error_message)!=null&&v.startsWith("Missed its scheduled time"))?{label:"Didn't send",variant:"destructive",icon:Al}:Sin(h.status),g=f.icon,x=h.scheduled_for??h.published_at??h.created_at;return e.jsx(je,{children:e.jsx(Le,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[((y=h.media_urls)==null?void 0:y[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($e,{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:WHt(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=F4(b.platform),S=w.icon,A=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(Ii,{src:(A==null?void 0:A.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:(A==null?void 0:A.page_name)||(A==null?void 0:A.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(Ir,{className:"h-3 w-3"})}),I&&e.jsx(Al,{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:[F4(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(pi,{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(Ct,{className:"h-3.5 w-3.5 animate-spin"}):h.status==="failed"||h.status==="partial"?e.jsx(co,{className:"h-3.5 w-3.5"}):e.jsx(Zr,{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(qn,{className:"h-3.5 w-3.5"})," Delete"]})]})]})})},h.id)})})}const Cin=()=>{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 v=JSON.parse(x);(v!=null&&v.mediaUrl||v!=null&&v.caption)&&(r(v),t("compose"))}catch{}}},[]);const{data:l=[]}=drt(),{data:o=[],isLoading:c}=pin(),d=$Ht(),u=j.useMemo(()=>o.filter(x=>x.status==="scheduled"||x.status==="draft"||x.status==="publishing").sort((x,v)=>new Date(x.scheduled_for??x.created_at).getTime()-new Date(v.scheduled_for??v.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,v=null)=>{r(x),i(v),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(je,{className:"overflow-hidden border-none bg-gradient-to-br from-primary/10 via-background to-background",children:e.jsxs(Le,{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($e,{variant:"secondary",className:"gap-1",children:[e.jsx(wn,{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(Ii,{src:x.profile_picture_url??void 0}),e.jsx(za,{className:"text-[10px]",children:F4(x.platform).label.slice(0,2)})]},x.id))}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(br,{to:"/social-connections",children:[e.jsx(JS,{className:"h-4 w-4"})," Manage accounts"]})})]}),e.jsxs($,{className:"gap-2",onClick:()=>f(null),children:[e.jsx(bp,{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:T4},{label:"Scheduled & drafts",value:u.length,icon:Wc},{label:"Published",value:h.filter(x=>x.status==="published").length,icon:Vr}].map(({label:x,value:v,icon:y})=>e.jsx(je,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-2",children:e.jsx(y,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-semibold leading-none",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:x})]})]})},x))}),e.jsxs(pa,{value:s,onValueChange:t,className:"space-y-6",children:[e.jsxs(ga,{className:"flex-wrap h-auto",children:[e.jsxs(Xt,{value:"compose",className:"gap-2",children:[e.jsx(bp,{className:"h-4 w-4"}),"Compose"]}),e.jsxs(Xt,{value:"calendar",className:"gap-2",children:[e.jsx(Wc,{className:"h-4 w-4"}),"Calendar"]}),e.jsxs(Xt,{value:"queue",className:"gap-2",children:[e.jsx(Zr,{className:"h-4 w-4"}),"Queue",u.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1",children:u.length})]}),e.jsxs(Xt,{value:"history",className:"gap-2",children:[e.jsx(Vr,{className:"h-4 w-4"}),"History",m>0&&e.jsx($e,{variant:"destructive",className:"ml-1",children:m})]}),e.jsxs(Xt,{value:"gallery",className:"gap-2",children:[e.jsx(wn,{className:"h-4 w-4"}),"Swag gallery"]})]}),e.jsx(Qt,{value:"compose",children:e.jsx(jin,{seed:n,editingPost:a,onSaved:()=>{d(),i(null),r(null)},onCancelEdit:()=>{i(null),r(null)}})}),e.jsx(Qt,{value:"calendar",children:e.jsx(kin,{posts:o,onCreateAt:x=>f({scheduledFor:x}),onOpenPost:x=>f(null,x)})}),e.jsx(Qt,{value:"queue",children:e.jsx(__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(Qt,{value:"history",children:e.jsx(__t,{posts:h,accounts:l,onEdit:x=>f(null,x),onChanged:d,emptyLabel:"Your published posts will show up here."})}),e.jsx(Qt,{value:"gallery",children:e.jsx(BHt,{embedded:!0,onCompose:g})})]})]})})},Ain=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:Hc,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:Gl,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:Rg,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:Zj,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:ME,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function Ein(){return e.jsx(Vs,{title:"Marketing Studio",children:e.jsxs("div",{className:"container max-w-6xl py-8 space-y-6",children:[e.jsxs(Dl,{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($e,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(wn,{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(br,{to:"/marketing-studio/brand-kit",children:[e.jsx(yd,{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:Ain.map(s=>{const t=s.icon,n=e.jsxs(je,{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(Le,{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($e,{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(br,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function pie(){const s=Sa();return st({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 Tin(){const{data:s,...t}=pie();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function Min(){const s=Sa(),t=Zt();return mt({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 Pin(){const s=Sa(),t=Zt();return mt({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 Iin(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 Lin({preset:s,onSaved:t,onCancel:n}){var x;const r=Sa(),a=Min(),i=Pin(),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:v}=await ri(async()=>{const{supabase:b}=await Promise.resolve().then(()=>_ks);return{supabase:b}},void 0),{data:y}=await v.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",r).maybeSingle();y&&h(b=>({...b,display_name:b.display_name||(y.name??""),email:b.email||(y.email??""),phone:b.phone||(y.phone??""),headshot_url:b.headshot_url||(y.avatar_url??""),website_url:b.website_url||(y.website_url??""),tagline:b.tagline||(y.title??"")}))})()},[r]);const m=async(v,y)=>{if(r){d(v);try{const b=await Iin(r,y,v);h(w=>({...w,[v==="headshot"?"headshot_url":"brokerage_logo_url"]:b}))}catch(b){ne.error(b.message||"Upload failed")}finally{d(null)}}},f=async()=>{try{const v=await a.mutateAsync({id:s==null?void 0:s.id,...u});ne.success("Brand preset saved"),t==null||t(v)}catch(v){ne.error(v.message||"Save failed")}},g=async()=>{s!=null&&s.id&&await mo("Delete this brand preset?")&&(await i.mutateAsync(s.id),ne.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:v=>h({...u,name:v.target.value}),placeholder:"Personal, Team, Luxury..."})]}),e.jsxs("div",{className:"flex items-end gap-3 pb-1",children:[e.jsx(jn,{checked:u.is_default,onCheckedChange:v=>h({...u,is_default:v})}),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:v=>h({...u,display_name:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:u.phone,onChange:v=>h({...u,phone:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:u.email,onChange:v=>h({...u,email:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"License #"}),e.jsx(pe,{value:u.license_number,onChange:v=>h({...u,license_number:v.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:u.tagline,onChange:v=>h({...u,tagline:v.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:v=>h({...u,website_url:v.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(Ii,{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 v;return(v=l.current)==null?void 0:v.click()},disabled:c==="headshot",children:[c==="headshot"?e.jsx(Ct,{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:v=>{var y;return((y=v.target.files)==null?void 0:y[0])&&m("headshot",v.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 v;return(v=o.current)==null?void 0:v.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(Ct,{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:v=>{var y;return((y=v.target.files)==null?void 0:y[0])&&m("logo",v.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:v=>h({...u,brand_color:v.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(pe,{value:u.brand_color,onChange:v=>h({...u,brand_color:v.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:v=>h({...u,accent_color:v.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(pe,{value:u.accent_color,onChange:v=>h({...u,accent_color:v.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(qn,{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(Ct,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function Rin(){const{data:s,isLoading:t}=pie(),[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(Dl,{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(br,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Va,{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(cn,{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(je,{className:"border-dashed",children:e.jsxs(Le,{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(cn,{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(je,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(St,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Et,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(ei,{className:"h-3 w-3"})," Default"]})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>r(a),children:e.jsx(pi,{className:"h-4 w-4"})})]}),e.jsx(Vn,{children:a.display_name})]}),e.jsxs(Le,{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(Os,{open:n!==null,onOpenChange:a=>!a&&r(null),children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(Us,{children:e.jsx($s,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(Lin,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const NWe=[{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"}],Din=s=>NWe.find(t=>t.id===s)??NWe[0];function Fin(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 Oin({value:s,onChange:t,mediaType:n}){const r=NWe.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(zin,{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 zin({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 Bin=Math.PI/180;function $in(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const QU=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},Qo={_global:QU,version:"10.7.0",isBrowser:$in(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return Qo.angleDeg?s*Bin: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:QU.document,_injectGlobal(s){typeof QU.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),QU.Konva=s}},KHt=new Set,Hg=(s,t=!1)=>{Qo[s.prototype.getClassName()]=s,t&&KHt.add(s)};Qo._injectGlobal(Qo);const Uin=`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"; `,w_t=()=>{if(typeof document>"u")throw new Error(Uin)};class v0{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 v0(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=Qn._getRotation(c.rotation),c}}const qin="[object Array]",Vin="[object Number]",Hin="[object String]",Gin="[object Boolean]",Win=Math.PI/180,YHt=180/Math.PI,IBe="#",Kin="",Yin="0",Zin="Konva warning: ",j_t="Konva error: ",Xin={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 IZ=null;const Qin=typeof window<"u"?window:{},LBe=new WeakMap,Jin=(s,t)=>{typeof s.requestAnimationFrame=="function"?s.requestAnimationFrame(t):typeof requestAnimationFrame<"u"?requestAnimationFrame(t):setTimeout(t,16)},N_t=new Map,ZHt=Object.getPrototypeOf(Int8Array),k_t=s=>{const t=s.trim();return t.indexOf(",")===-1?t.split(/\s*\/\s*|\s+/):t.split(/\s*,\s*/)},XHt="[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?",eon=new RegExp(`^(${XHt})(%?)$`,"i"),hR=(s,t)=>{const n=eon.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)},jde=/^#[0-9a-f]+$/i,ton=new RegExp(`^(${XHt})(deg|grad|rad|turn)?$`,"i"),son={deg:1,grad:.9,rad:YHt,turn:360};function LZ(s,t){return Math.min(Math.max(s||0,0),t)}const Qn={_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)===qin},_isNumber(s){return Object.prototype.toString.call(s)===Vin&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===Hin},_isBoolean(s){return Object.prototype.toString.call(s)===Gin},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||Qin;let r=LBe.get(n);r||(r=[],LBe.set(n,r),Jin(n,function(){LBe.delete(n),r.forEach(function(a){a()})})),r.push(s)},createCanvasElement(){w_t();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return w_t(),document.createElement("img")},_urlToImage(s,t,n){const r=Qn.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(IBe,Kin);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=Yin+s;return IBe+s},isCanvasFarblingActive(){if(IZ!==null)return IZ;if(typeof document>"u")return IZ=!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 IZ=r,this.releaseCanvas(s),IZ},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 IBe+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=Qn.colorToRGBA(s))!==null&&t!==void 0?t:{};return{r:n,g:r,b:a}},colorToRGBA(s){s=(s||"").trim()||"black";const t=Qn._namedColorToRBA(s)||Qn._hex3ColorToRGBA(s)||Qn._hex4ColorToRGBA(s)||Qn._hex6ColorToRGBA(s)||Qn._hex8ColorToRGBA(s)||Qn._rgbColorToRGBA(s)||Qn._hslColorToRGBA(s);if(t&&[t.r,t.g,t.b,t.a].every(Qn._isNumber))return t},_namedColorToRBA(s){const t=Xin[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=k_t(t[1]);if(!(n.length<3||n.length>4))return{r:hR(n[0],255),g:hR(n[1],255),b:hR(n[2],255),a:n.length>3?hR(n[3],1):1}},_hex8ColorToRGBA(s){if(s.length===9&&jde.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&&jde.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&&jde.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&&jde.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=k_t(t[1]);if(n.length<3||n.length>4)return;const r=ton.exec(n[0]);if(!r)return;const a=r[2],i=Number(r[1])*(a?son[a.toLowerCase()]:1);if(!isFinite(i))return;const l=(i%360+360)%360/360,o=hR(n[1],100)/100,c=hR(n[2],100)/100,d=n.length>3?hR(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(Qn._cloneValue):s.slice():Qn._isPlainObject(s)?Qn.cloneObject(s):s instanceof ZHt?s.slice():s},cloneArray(s){return s.slice(0)},degToRad(s){return s*Win},radToDeg(s){return s*YHt},_getRotation(s){return Qo.angleDeg?Qn.radToDeg(s):s},_capitalize(s){const t=N_t.get(s);if(t!==void 0)return t;const n=s.charAt(0).toUpperCase()+s.slice(1);return N_t.set(s,n),n},throw(s){throw new Error(j_t+s)},error(s){console.error(j_t+s)},warn(s){Qo.showWarnings&&console.warn(Zin+s)},_batchEvents(s,t){if(!s)return t();let n=!1,r=!0;try{s(()=>{if(n||!r){Qn.warn("eventBatchFunc must call its argument exactly once, synchronously.");return}n=!0,t()})}finally{r=!1,n||Qn.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=Qn.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=Qn._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=LZ(s,r);return[a,a,a,a]}return[LZ(s[0],r),LZ(s[1],r),LZ(s[2],r),LZ(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]=Qn._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+=aon+d.join(ron)+ion)):(i+=o.property,t||(i+=con+o.val)),i+=oon;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=uon&&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=S_t.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=non(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 m7({width:0,height:0,pixelRatio:this.pixelRatio}));if(f.widthMath.min(A,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(),Qn.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 mon(this,{willReadFrequently:t.willReadFrequently}),this.setSize(t.width,t.height)}}class mrt extends hrt{constructor(t={width:0,height:0}){super(t),this.hitCanvas=!0,this.context=new fon(this),this.context.imageSmoothingEnabled=!1,this.setSize(t.width,t.height)}}const mh={get isDragging(){let s=!1;return mh._dragElements.forEach(t=>{t.dragStatus==="dragging"&&(s=!0)}),s},get node(){let s;for(const t of mh._dragElements.values()){if(t.dragStatus==="dragging")return t.node;s=t.node}return s},_dragElements:new Map,_listenToWindow(s){const t=a=>mh._endDragBefore(a,s),n=a=>mh._batchEvents(()=>mh._drag(a,s),s),r=a=>mh._batchEvents(()=>mh._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(!mh._dragElements.size)return;const n=new Set;for(const{node:a}of mh._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=()=>Qn._batchEvents(a,i)}r()},_drag(s,t){const n=[],r=new Set;mh._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=Qn._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;mh._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!==Qn._getEventType(s.type)||!(i.pointerId===void 0||c._changedPointerPositions.some(u=>u.id===i.pointerId)))))if(i.dragStatus==="ready")mh._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){mh._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"&&mh._dragElements.delete(r))})}},LG=new Map,QHt=Qo._global.PointerEvent!==void 0;function Nde(s,t){const n=LG.get(s);return n&&(!t||n.stage===t)?n.shape:void 0}function JHt(s,t,n){s._fire(t,{evt:new PointerEvent(t,{pointerId:n}),pointerId:n})}function eGt(s,t){var n;return((n=LG.get(s))===null||n===void 0?void 0:n.shape)===t}function tGt(s,t){var n;wV(s);const r=t.getStage();if(r&&(LG.set(s,{shape:t,stage:r}),QHt)){try{(n=r.content)===null||n===void 0||n.setPointerCapture(s)}catch{}JHt(t,"gotpointercapture",s)}}function pon(s){LG.forEach(({shape:t,stage:n},r)=>{(t===s||n===s)&&wV(r)})}function wV(s,t){var n;const r=LG.get(s);if(!r||t&&r.shape!==t)return;const{shape:a,stage:i}=r;if(LG.delete(s),QHt){try{(n=i.content)===null||n===void 0||n.releasePointerCapture(s)}catch{}JHt(a,"lostpointercapture",s)}}function m6(s){return Qn._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||Qn._isBoolean(s)?s:Object.prototype.toString.call(s)}function frt(s){return s>255?255:s<0?0:Math.round(s)}function Ti(){if(Qo.isUnminified)return function(s,t){return Qn._isNumber(s)||Qn.warn(m6(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function Q6e(s){if(Qo.isUnminified)return function(t,n){let r=Qn._isNumber(t),a=Qn._isArray(t)&&t.length==s;return!r&&!a&&Qn.warn(m6(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function prt(){if(Qo.isUnminified)return function(s,t){return Qn._isNumber(s)||s==="auto"||Qn.warn(m6(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function $B(){if(Qo.isUnminified)return function(s,t){return Qn._isString(s)||Qn.warn(m6(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function sGt(){if(Qo.isUnminified)return function(s,t){const n=Qn._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||Qn.warn(m6(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 ZHt||(Qn._isArray(s)?s.forEach(function(n){Qn._isNumber(n)||Qn.warn('"'+t+'" attribute has non numeric element '+n+". Make sure that all elements are numbers.")}):Qn.warn(m6(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function wC(){if(Qo.isUnminified)return function(s,t){return s===!0||s===!1||Qn.warn(m6(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function xon(s){if(Qo.isUnminified)return function(t,n){return t==null||Qn.isObject(t)||Qn.warn(m6(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const DZ="get",FZ="set",En={addGetterSetter(s,t,n,r,a){En.addGetter(s,t,n),En.addSetter(s,t,r,a),En.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=DZ+Qn._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=FZ+Qn._capitalize(t);s.prototype[a]||En.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=FZ+Qn._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=Qn._capitalize,o=DZ+l(t),c=FZ+l(t),d=n.map(m=>t+l(m)),u=d.map(m=>DZ+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},En.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=Qn._capitalize(t),r=FZ+n,a=DZ+n,i=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()};s.prototype[t]=i},backCompat(s,t){Qn.each(t,function(n,r){const a=s.prototype[r],i=DZ+Qn._capitalize(n),l=FZ+Qn._capitalize(n);function o(){return Qn.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 yon(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)){Qn.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?GM._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 Qn.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 m7({pixelRatio:c,width:l,height:o}),f=new m7({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(uQ);try{this.drawScene(m,this)}catch(x){throw Qn.releaseCanvas(m._canvas),x}finally{this._isUnderCache=!1,this._clearSelfAndDescendantCache(uQ),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 mrt(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)&&mh._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(vA),this._clearSelfAndDescendantCache(uQ),this._clearSelfAndDescendantCache(E_t),this._clearSelfAndDescendantCache(CWe),this._clearSelfAndDescendantCache(kWe)}_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}),pon(this),this.remove(),this.clearCache(),this}getAttr(t){const n="get"+Qn._capitalize(t);return Qn._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!==bon&&(r=C_t+Qn._capitalize(n),Qn._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(kWe,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(CWe,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!==Eon&&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(HM),this._clearSelfAndDescendantCache(vA))}}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 v0,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(HM);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}):Qn.warn("Cannot set the absolute position: the absolute transform is not invertible (an ancestor has a zero scale)."),this._clearCache(HM),this._clearSelfAndDescendantCache(vA),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 Qn.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 Qn.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 Qn.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&Qn.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(uQ,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=Qn.isObject(a)&&!Qn._isPlainObject(a)&&!Qn._isArray(a),!i&&(((t=this["get"+Qn._capitalize(r)])===null||t===void 0?void 0:t._def)!==a||r==="brightness"||r==="threshold")&&(l.attrs[r]=r==="filters"&&Qn._isArray(a)?a.filter(o=>typeof o=="string"):Qn.isObject(a)?Qn._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||{};Qn._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)||mh._dragElements.has(this._id))return;let a=!1;mh._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=mh._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&mh._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 Qn.haveIntersection(r,this.getClientRect())}static create(t,n){return Qn._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=GM.prototype.getClassName.call(t),a=t.children,i,l,o;if(n&&(t.attrs.container=n),!Qo[r]){const d=a?"Group":"Shape";Qn.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=Qn._getEventType(s);if(t==="pointer")return Qo.pointerEventsEnabled&&RBe.pointer;if(t==="touch")return RBe.touch;if(t==="mouse")return RBe.mouse};function M_t(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&Qn.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const Oon="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);",Lee=[],P_t=new WeakSet,I_t=s=>{!s||P_t.has(s)||(P_t.add(s),mh._listenToWindow(s),s.document.addEventListener("visibilitychange",()=>{Lee.forEach(t=>{t.batchDraw()})}))};let gie=class extends p2{constructor(t){super(M_t(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._pointerStates=new Map,this._lastClicks={},this._buildDOM(),this._bindContentEvents(),Lee.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{M_t(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||Qn.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===Ion){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),I_t(this._getOwnerWindow())),this}shouldDrawHit(){return!0}clear(){const t=this.children,n=t.length;for(let r=0;r-1&&Lee.splice(r,1),Qn.releaseCanvas(this.bufferHitCanvas._canvas),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(Qn.warn(Oon),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 m7({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()),Qn.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+T_t,this.content.style.height=n+T_t),this.children.forEach(r=>{r._setSize({width:t,height:n}),r.draw()})}add(t,...n){if(arguments.length>1){for(let a=0;aDon&&Qn.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 eGt(t,this)}setPointerCapture(t){tGt(t,this)}releaseCapture(t){wV(t,this)}getLayers(){return this.getChildren()}_bindContentEvents(){Qo.isBrowser&&Fon.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this._batchEvents(()=>this[n](r))},{passive:!1})})}_batchEvents(t){Qn._batchEvents(this.eventBatchFunc(),t)}_pointerenter(t){this.setPointersPositions(t);const n=mR(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=mR(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 mh._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=mR(t.type),i=Qn._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=mR(t.type),r=Qn._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 mh._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=mR(t.type),r=Qn._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 mh._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=Nde(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},v=f!==m;h.targetShape=m&&m.isListening()?m:void 0,v&&f&&(f._fireAndBubble(n.pointerout,{...x},m),f._fireAndBubble(n.pointerleave,{...x},m)),m&&m.isListening()?(o=!0,v&&(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=mR(t.type),r=Qn._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=Nde(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},v=m&&m.isListening()?m:null,y=this._lastClicks[r],b=u&&(!v||h===v),w=b&&y&&(d==null?void 0:d.lastClick)===y&&y.shape===v&&Date.now()-y.time{var a;const i=Qn._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=Nde(r.id)||this.getIntersection(r),d={evt:t,pointerId:r.id};c?(n&&c._fireAndBubble(n.pointercancel,{...d}),c._fireAndBubble(JU,{...d})):n&&this._fire(n.pointercancel,{...d,target:this,currentTarget:this}),wV(r.id),n&&i==="touch"&&(o==null?void 0:o.getStage())===this&&(o._fireAndBubble(n.pointerout,{...d}),o._fireAndBubble(n.pointerleave,{...d}))})}_lostpointercapture(t){Nde(t.pointerId,this)&&wV(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:Qn._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:Qn._getFirstPointerId(t)}])}_setPointerPosition(t){Qn.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 mrt({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),I_t(this._getOwnerWindow()),this._resizeDOM()}cache(){return Qn.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}};gie.prototype.nodeType=Pon;Hg(gie);En.addGetterSetter(gie,"container");En.addGetterSetter(gie,"eventBatchFunc");const mGt="hasShadow",fGt="hasFill",pGt="hasStroke",gGt="shadowRGBA",xGt="patternImage",yGt="linearGradient",vGt="radialGradient";let Ade;function DBe(){return Ade||(Ade=Qn.createCanvasElement().getContext("2d"),Ade)}const Ree={};function bGt(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function _Gt(s){s.stroke()}function zon(){this._clearCache(mGt)}function Bon(){this._clearCache(fGt)}function $on(){this._clearCache(pGt)}function Uon(){this._clearCache(gGt)}function qon(){this._clearCache(xGt)}function Von(){this._clearCache(yGt)}function Hon(){this._clearCache(vGt)}let li=class wGt extends zi{constructor(t){super(t);let n,r=0;for(;n=Qn.getHitColor(),!(n&&!(n in Ree));)if(r++,r>=1e4){Qn.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=Qn.getRandomColor();break}this.colorKey=n,Ree[n]=this}getContext(){return Qn.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return Qn.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(mGt,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(xGt,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=DBe().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new v0;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(yGt,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=DBe(),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 Ree[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){Qn.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 v0()._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,v,y]=this.getAbsoluteTransform(f).getMatrix(),b=Math.abs(g*y-x*v);if(b)d*=Math.hypot(v,y)/b,u*=Math.hypot(g,x)/b;else if(!r&&(d=u=0,h=f?f.getAbsoluteTransform().copy():new v0,a)){const w=a.getAbsoluteTransform(),[S,A,E,I]=w.getMatrix();h=S*I-A*E?w.copy().invert().multiply(h):new v0}}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,v=this.shadowBlur()*(i?2*Math.min(Math.abs(f.x),Math.abs(f.y)):1);m.x+=Math.min(0,g)-v,m.y+=Math.min(0,x)-v,m.width+=Math.abs(g)+v*2,m.height+=Math.abs(x)+v*2}if(i)return m;if(!r){const f=this._transformedRect(m,a);if(h){const[g,x,v,y]=h.getMatrix(),b=c*Math.hypot(g,v)/2,w=c*Math.hypot(x,y)/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===wGt.prototype.getSelfRect||!this.attrs.sceneFunc&&!this.attrs.charRenderFunc&&KHt.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||Qn.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=Qn._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){Qn.error("Unable to draw hit graph from cached scene canvas. "+o.message)}return this}hasPointerCapture(t){return eGt(t,this)}setPointerCapture(t){tGt(t,this)}releaseCapture(t){wV(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";Hg(li);li.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetXChange.konva shadowOffsetYChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",zon);li.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Uon);li.prototype.on("fillEnabledChange.konva fillChange.konva fillPatternImageChange.konva fillLinearGradientColorStopsChange.konva fillRadialGradientColorStopsChange.konva",Bon);li.prototype.on("strokeEnabledChange.konva strokeWidthChange.konva strokeChange.konva strokeLinearGradientColorStopsChange.konva",$on);li.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",qon);li.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",Von);li.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",Hon);En.addGetterSetter(li,"stroke",void 0,sGt());En.addGetterSetter(li,"strokeWidth",2,Ti());En.addGetterSetter(li,"fillAfterStrokeEnabled",!1);En.addGetterSetter(li,"hitStrokeWidth","auto",prt());En.addGetterSetter(li,"strokeHitEnabled",!0,wC());En.addGetterSetter(li,"perfectDrawEnabled",!0,wC());En.addGetterSetter(li,"shadowForStrokeEnabled",!0,wC());En.addGetterSetter(li,"lineJoin");En.addGetterSetter(li,"lineCap");En.addGetterSetter(li,"miterLimit");En.addGetterSetter(li,"sceneFunc");En.addGetterSetter(li,"hitFunc");En.addGetterSetter(li,"selfRectFunc");En.addGetterSetter(li,"dash");En.addGetterSetter(li,"dashOffset",0,Ti());En.addGetterSetter(li,"shadowColor",void 0,$B());En.addGetterSetter(li,"shadowBlur",0,Ti());En.addGetterSetter(li,"shadowOpacity",1,Ti());En.addComponentsGetterSetter(li,"shadowOffset",["x","y"]);En.addGetterSetter(li,"shadowOffsetX",0,Ti());En.addGetterSetter(li,"shadowOffsetY",0,Ti());En.addGetterSetter(li,"fillPatternImage");En.addGetterSetter(li,"fill",void 0,sGt());En.addGetterSetter(li,"fillPatternX",0,Ti());En.addGetterSetter(li,"fillPatternY",0,Ti());En.addGetterSetter(li,"fillLinearGradientColorStops");En.addGetterSetter(li,"strokeLinearGradientColorStops");En.addGetterSetter(li,"fillRadialGradientStartRadius",0);En.addGetterSetter(li,"fillRadialGradientEndRadius",0);En.addGetterSetter(li,"fillRadialGradientColorStops");En.addGetterSetter(li,"fillPatternRepeat","repeat");En.addGetterSetter(li,"fillEnabled",!0);En.addGetterSetter(li,"strokeEnabled",!0);En.addGetterSetter(li,"shadowEnabled",!0);En.addGetterSetter(li,"dashEnabled",!0);En.addGetterSetter(li,"strokeScaleEnabled",!0);En.addGetterSetter(li,"fillPriority","color");En.addComponentsGetterSetter(li,"fillPatternOffset",["x","y"]);En.addGetterSetter(li,"fillPatternOffsetX",0,Ti());En.addGetterSetter(li,"fillPatternOffsetY",0,Ti());En.addComponentsGetterSetter(li,"fillPatternScale",["x","y"]);En.addGetterSetter(li,"fillPatternScaleX",1,Ti());En.addGetterSetter(li,"fillPatternScaleY",1,Ti());En.addComponentsGetterSetter(li,"fillLinearGradientStartPoint",["x","y"]);En.addComponentsGetterSetter(li,"strokeLinearGradientStartPoint",["x","y"]);En.addGetterSetter(li,"fillLinearGradientStartPointX",0);En.addGetterSetter(li,"strokeLinearGradientStartPointX",0);En.addGetterSetter(li,"fillLinearGradientStartPointY",0);En.addGetterSetter(li,"strokeLinearGradientStartPointY",0);En.addComponentsGetterSetter(li,"fillLinearGradientEndPoint",["x","y"]);En.addComponentsGetterSetter(li,"strokeLinearGradientEndPoint",["x","y"]);En.addGetterSetter(li,"fillLinearGradientEndPointX",0);En.addGetterSetter(li,"strokeLinearGradientEndPointX",0);En.addGetterSetter(li,"fillLinearGradientEndPointY",0);En.addGetterSetter(li,"strokeLinearGradientEndPointY",0);En.addComponentsGetterSetter(li,"fillRadialGradientStartPoint",["x","y"]);En.addGetterSetter(li,"fillRadialGradientStartPointX",0);En.addGetterSetter(li,"fillRadialGradientStartPointY",0);En.addComponentsGetterSetter(li,"fillRadialGradientEndPoint",["x","y"]);En.addGetterSetter(li,"fillRadialGradientEndPointX",0);En.addGetterSetter(li,"fillRadialGradientEndPointY",0);En.addGetterSetter(li,"fillPatternRotation",0);En.addGetterSetter(li,"fillRule",void 0,$B());En.backCompat(li,{dashArray:"dash",getDashArray:"getDash",setDashArray:"setDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const Gon="beforeDraw",Won="draw",Kon=10,L_t=256;function R_t(s,t){return s[t+3]>=128?Ree[Qn.getHitColorKey(s[t],s[t+1],s[t+2])]:void 0}let UB=class extends p2{constructor(t){super(t),this.canvas=new m7,this.hitCanvas=new mrt({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=Kon,c=o*2+1,d=l(o),u=d[(o*c+o)*4+3];for(let h=1;h<=L_t;h++){h>o&&(o=Math.min(L_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 v=((f+o)*c+x+o)*4,y=R_t(d,v);if(y)return y;m=Math.max(m,d[v+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=R_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(Gon,{node:this}),this.clearBeforeDraw()&&a.getContext().clear(),p2.prototype.drawScene.call(this,a,n),a._trimIsolationCanvas(),this._fire(Won,{node:this}),this}shouldDrawHit(t){var n;if(!super.shouldDrawHit(t))return!1;if(t||Qo.hitOnDragEnabled)return!0;let r=!1;return mh._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()),p2.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){Qn.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return Qn.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(),Qn.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};UB.prototype.nodeType="Layer";Hg(UB);En.addGetterSetter(UB,"imageSmoothingEnabled",!0);En.addGetterSetter(UB,"clearBeforeDraw",!0);En.addOverloadedGetterSetter(UB,"hitGraphEnabled");class grt extends UB{constructor(t){super(t),this.listening(!1),Qn.warn('Konva.FastLayer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}grt.prototype.nodeType="FastLayer";Hg(grt);let Z7=class extends p2{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&Qn.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}}};En.addGetterSetter(Z7,"isolated",!1,wC());Z7.prototype.nodeType="Group";Hg(Z7);var FBe;const OBe=!((FBe=QU.performance)===null||FBe===void 0)&&FBe.now?()=>QU.performance.now():Date.now;class LN{constructor(t,n){this.id=LN.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:OBe(),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(OBe()),!(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=LN;t.animations.size?(t._runFrames(),Qn.requestAnimFrame(t._animationLoop)):t.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,Qn.requestAnimFrame(this._animationLoop))}}LN.animations=new Set;LN.animIdCounter=0;LN.animRunning=!1;const Yon={node:1,duration:1,easing:1,onFinish:1,onUpdate:1,onReset:1,yoyo:1},Zon=1,D_t=2,F_t=3,O_t=["fill","stroke","shadowColor"];let Xon=0;function Ede(s){return Qn.colorToRGBA(s)||Qn.throw('can not tween the color "'+s+'", because it is not a valid color.')}function z_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 B_t(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 Qon{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=D_t,this._startTime=this.getTimer()-this._time,this.fire("onPlay"),this.onEnterFrame()}reverse(){this.state=F_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===D_t?this.setTime(t):this.state===F_t&&this.setTime(this.duration-t)}pause(){this.state=Zon,this.fire("onPause")}getTimer(){return Date.now()}}class vg{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||Dee.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=Xon++;const d=r.getLayer()||(r instanceof Qo.Stage?r.getLayers():null);d||Qn.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new LN(function(){n.tween.onEnterFrame()},d),this.tween=new Qon(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),vg.attrs[a]||(vg.attrs[a]={}),vg.attrs[a][this._id]||(vg.attrs[a][this._id]={}),vg.tweens[a]||(vg.tweens[a]={});for(c in t)Yon[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(Qn._isPlainObject(n)){for(const h in n)this._addAttr(t+Qn._capitalize(h),n[h]);return}const r=this.node,a=r._id;let i,l,o,c;const d=vg.tweens[a][t];d!==void 0&&delete vg.attrs[a][d][t];let u=r.getAttr(t);if(Qn._isArray(n)||Qn._isArray(u))if(i=[],c=u,o=n,u=Qn._isArray(u)?u.slice():new Array(n.length).fill(u||0),Qn._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=Qn._prepareArrayForTween(u,n,r.closed()):n=Qn._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=vg.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=vg.attrs[n])===null||t===void 0?void 0:t[r],i=vg.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 vg.tweens[n]}delete vg.attrs[n][r],Object.keys(vg.attrs[n]).length===0&&delete vg.attrs[n]}}}vg.attrs={};vg.tweens={};zi.prototype.to=function(s){const t=s.onFinish,n=new vg({...s,node:this,onFinish(){n.destroy(),t&&t()}});return n.play(),n};const Dee={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,v=m*(m>0?r:a),y=f*(f>0?a:r);return{x:g,y:i?-1*y:v,width:x-g,height:y-v}}}MT.prototype._centroid=!0;MT.prototype.className="Arc";MT.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];Hg(MT,!0);En.addGetterSetter(MT,"innerRadius",0,Ti());En.addGetterSetter(MT,"outerRadius",0,Ti());En.addGetterSetter(MT,"angle",0,Ti());En.addGetterSetter(MT,"clockwise",!1,wC());const $_t=[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],Jon=[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],TWe=(s,t,n)=>{const r=n/2;let a=0;for(let i=0;i<$_t.length;i++){const l=r*$_t[i]+r;a+=Jon[i]*eln(s,t,l)}return r*a},U_t=(s,t,n=1)=>TWe([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 eln(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 q_t=(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},V_t=(s,t,n,r)=>{const a=1-r;return a*a*s+2*a*r*t+r*r*n},jGt=(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(V_t(s,n,a,c),V_t(t,r,i,c))}return l},H_t=(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},xrt=(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(H_t(s,n,a,l,x),H_t(t,r,i,o,x))}return c};function MWe(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 G_t(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,...jGt(r,a,i,l,o,c)),(r,a,i,l,o,c,d,u)=>n.push(d,u,...xrt(r,a,i,l,o,c,d,u))),t=n}else this.bezier()&&(t=[t[0],t[1],...tln(t)]);return Qn._getPointsRect(t)}};l3.prototype.className="Line";l3.prototype._attrsAffectingSize=["points","bezier","tension","closed"];Hg(l3,!0);En.addGetterSetter(l3,"closed",!1);En.addGetterSetter(l3,"bezier",!1);En.addGetterSetter(l3,"tension",0,Ti());En.addGetterSetter(l3,"points",[],gon());const sln={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7,z:0},zBe=Math.PI*2;let VS=class X1 extends li{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=X1.parsePathData(this.data()),this.pathLength=X1.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)%zBe+zBe)%zBe0&&t<=c;)c-=n[--o].pathLength;for(t-=c;on[o].pathLength;){const m=n[o].pathLength;t-=m,c+=m,++o}if(r&&oTWe([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 X1.getPointOnQuadraticBezier(q_t(t,u.pathLength,m=>U_t([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 X1.getPointOnEllipticalArc(h[0],h[1],h[2],h[3],h[2]===h[3]?h[4]+h[5]*t/u.pathLength:X1._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&&(A[0]==="0"||A[0]==="1");)v.push(+A[0]),y++,A=A.slice(1);const E=parseFloat(A);v.push(isNaN(E)?0:E),y>=0&&(y=(y+1)%7)}let b=0;for(;b=n)return{theta:h+(g-h)*((n-m)/v),length:n};m+=v,u=x,h=g}return{theta:h,length:m}}static calcLength(t,n,r,a){const i=X1;switch(r){case"L":return i.getLineLength(t,n,a[0],a[1]);case"C":return TWe([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return U_t([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,v=g*-c*h/o,y=(t+r)/2+Math.cos(u)*x-Math.sin(u)*v,b=(n+a)/2+Math.sin(u)*x+Math.cos(u)*v,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))},A=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),[y,b,o,c,E,R,u,l]}};VS.prototype.className="Path";VS.prototype._attrsAffectingSize=["data"];Hg(VS,!0);En.addGetterSetter(VS,"data");class f6 extends l3{_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=VS.calcLength(h,m,"Q",[f,g,l,o]),v=VS.getPointOnQuadraticBezier(x?Math.max(0,1-this.pointerLength()/x):0,h,m,f,g,l,o);c=l-v.x,d=o-v.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?Qn.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?Qn.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=Qn.createImageElement();a.onload=()=>{a.onload=a.onerror=null,n(new NGt({image:a}))},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};jC.prototype.className="Image";jC.prototype._attrsAffectingSize=["image"];Hg(jC,!0);En.addGetterSetter(jC,"cornerRadius",0,Q6e(4));En.addGetterSetter(jC,"image");En.addComponentsGetterSetter(jC,"crop",["x","y","width","height"]);En.addGetterSetter(jC,"cropX",0,Ti());En.addGetterSetter(jC,"cropY",0,Ti());En.addGetterSetter(jC,"cropWidth",0,Ti());En.addGetterSetter(jC,"cropHeight",0,Ti());const W_t=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function Fee(s){return s/15}function gQ(s){return W_t?Array.from(W_t.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 k$="auto",K_t="center",kGt="inherit",S$="justify",nln="Change.konva",SGt="2d",rln="-",CGt="left",aln="text",iln="Text",oln="top",lln="bottom",Y_t="middle",AGt="normal",cln="px ",BBe=" ",Z_t="right",X_t="rtl",dln="word",uln="char",Q_t="none",$Be="…",EGt=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"];let OZ=null;function hln(){if(OZ!==null)return OZ;OZ=!1;let s;try{s=Qn.createCanvasElement(),s.width=10,s.height=10;const t=s.getContext(SGt);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){OZ=!0;break}}}catch{}finally{s&&Qn.releaseCanvas(s)}return OZ}function mln(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 Tde;function x3e(){return Tde||(Tde=Qn.createCanvasElement().getContext(SGt),Tde)}function fln(s){this._partialFillStyle&&s.setAttr("fillStyle",this._partialFillStyle),s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function pln(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 lf=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,v=g.indexOf("line-through")!==-1,y,b=c/2,w=Y_t;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!==kGt?t.setAttr("direction",d):d=t.direction,t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",w),t.setAttr("textAlign",CGt),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,A=f?t.strokeStyle:void 0;let E=0;for(y=0;y1&&(b+=c)}}_getTextTop(){const t=this.padding(),n=this.getHeight()-this.textArr.length*this.lineHeight()*this.fontSize()-t*2,r=this.verticalAlign();return r===Y_t?t+n/2:r===lln?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()+Fee(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===Z_t?i-g:l===K_t?(i-g)/2:0),v=Math.min(0,this.letterSpacing())*f.length;d=Math.min(d,x+v),u=Math.max(u,x+g-v)}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=Qn._isString(t)?t:t==null?"":t+"";return this._setAttr(aln,n),this}getWidth(){return this.attrs.width===k$||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===k$||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return Qn.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=x3e(),g=this.fontSize(),x;f.save(),f.font=this._getContextFont(),x=f.measureText(t),f.restore();const v=g/100;return{actualBoundingBoxAscent:(n=x.actualBoundingBoxAscent)!==null&&n!==void 0?n:71.58203125*v,actualBoundingBoxDescent:(r=x.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(a=x.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*v,actualBoundingBoxRight:(i=x.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*v,alphabeticBaseline:(l=x.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=x.emHeightAscent)!==null&&o!==void 0?o:100*v,emHeightDescent:(c=x.emHeightDescent)!==null&&c!==void 0?c:-20*v,fontBoundingBoxAscent:(d=x.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*v,fontBoundingBoxDescent:(u=x.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*v,hangingBaseline:(h=x.hangingBaseline)!==null&&h!==void 0?h:72.80000305175781*v,ideographicBaseline:(m=x.ideographicBaseline)!==null&&m!==void 0?m:-21*v,width:x.width,height:g}}_getContextFont(){return this.fontStyle()+BBe+this.fontVariant()+BBe+(this.fontSize()+cln)+mln(this.fontFamily())}_addTextLine(t){this.align()===S$&&(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??gQ(t).length):0;return x3e().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!==k$&&a!==void 0,o=i!==k$&&i!==void 0,c=this.padding(),d=a-c*2,u=i-c*2,h=0,m=this.wrap(),f=m!==Q_t,g=m!==uln&&f,x=this.ellipsis();const v=this.measureSize("M");this._baselineShift=(v.fontBoundingBoxAscent-v.fontBoundingBoxDescent)/2,this.textArr=[];const y=x3e();y.font=this._getContextFont(),y.fontKerning=this.direction()!==X_t&&(this.letterSpacing()!==0||this.align()===S$||this.charRenderFunc())?"none":"auto";const b=x?this._getTextWidth($Be):0;for(let w=0,S=t.length;wd){const I=gQ(A),P=I.length;let R=0;const D=W=>I.slice(R,W).join(""),O=W=>W===BBe||W===rln,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,Z=Math.min(P,R+U);for(;V(Z)&&(G=Z,Z!==P);)Z=Math.min(P,Z+(Z-R));for(;Z-G>1;){const X=G+Z>>>1;V(X)?G=X:Z=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!==k$&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==Q_t)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==k$&&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+$Be;if(n){const c=gQ(l.text);for(;c.length&&this._getTextWidth(o)>a;)c.pop(),o=c.join("")+$Be;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&&hln()?!0:super._useBufferCanvas(t,n)}};lf.prototype._fillFunc=fln;lf.prototype._strokeFunc=pln;lf.prototype.className=iln;lf.prototype._attrsAffectingSize=EGt.filter(s=>s!=="width"&&s!=="height").concat(["textDecoration","underlineOffset"]);Hg(lf,!0);lf.prototype.on(EGt.map(s=>s+nln).join(" "),function(){this._setTextData()});En.overWriteSetter(lf,"width",prt());En.overWriteSetter(lf,"height",prt());En.addGetterSetter(lf,"direction",kGt);En.addGetterSetter(lf,"fontFamily","Arial");En.addGetterSetter(lf,"fontSize",12,Ti());En.addGetterSetter(lf,"fontStyle",AGt);En.addGetterSetter(lf,"fontVariant",AGt);En.addGetterSetter(lf,"padding",0,Ti());En.addGetterSetter(lf,"align",CGt);En.addGetterSetter(lf,"verticalAlign",oln);En.addGetterSetter(lf,"lineHeight",1,Ti());En.addGetterSetter(lf,"wrap",dln);En.addGetterSetter(lf,"ellipsis",!1,wC());En.addGetterSetter(lf,"letterSpacing",0,Ti());En.addGetterSetter(lf,"text","",$B());En.addGetterSetter(lf,"textDecoration","");En.addGetterSetter(lf,"underlineOffset",void 0,Ti());En.addGetterSetter(lf,"charRenderFunc",void 0);const xln=[...lf.prototype._attrsAffectingSize,"width","height","pointerDirection","pointerWidth","pointerHeight"],J_t=xln.map(s=>s+"Change.konva").join(" "),yln="none",y3e="up",PWe="right",IWe="down",v3e="left";let yrt=class extends Z7{constructor(t){super(t),this._sync=this._sync.bind(this),this.on("add.konva",function(n){n.child.off(J_t,this._sync).on(J_t,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 y3e:o=r/2,c=-1*d;break;case PWe:o=r+l,c=a/2;break;case IWe:o=r/2,c=a+d;break;case v3e: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})}}};yrt.prototype.className="Label";Hg(yrt);class qB 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]=Qn._cornerRadii(o,n,r);t.beginPath(),t.moveTo(c,0),a===y3e&&(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===PWe&&(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===IWe&&(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===v3e&&(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===y3e||r===IWe?{x:Math.min(0,(a-t)/2),y:r===y3e?-n:0,width:Math.max(a,t),height:i+n}:r===v3e||r===PWe?{x:r===v3e?-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}}}qB.prototype.className="Tag";Hg(qB,!0);En.addGetterSetter(qB,"pointerDirection",yln);En.addGetterSetter(qB,"pointerWidth",0,Ti());En.addGetterSetter(qB,"pointerHeight",0,Ti());En.addGetterSetter(qB,"cornerRadius",0,Q6e(4));let xie=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?Qn.drawRoundedRectPath(t,r,a,n):t.rect(0,0,r,a),t.closePath(),t.fillStrokeShape(this)}};xie.prototype.className="Rect";Hg(xie,!0);En.addGetterSetter(xie,"cornerRadius",0,Q6e(4));class g6 extends li{_sceneFunc(t){const n=this._getPoints(),r=this.radius(),a=this.sides(),i=this.cornerRadius();if(n.length){if(t.beginPath(),i)Qn.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)}}g6.prototype.className="RegularPolygon";g6.prototype._centroid=!0;g6.prototype._attrsAffectingSize=["radius","sides"];Hg(g6,!0);En.addGetterSetter(g6,"radius",0,Ti());En.addGetterSetter(g6,"sides",0,Ti());En.addGetterSetter(g6,"cornerRadius",0,Q6e(4));const ewt=Math.PI*2;class VB 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,ewt,!1),t.moveTo(r,0),t.arc(0,0,r,ewt,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)}}VB.prototype.className="Ring";VB.prototype._centroid=!0;VB.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Hg(VB,!0);En.addGetterSetter(VB,"innerRadius",0,Ti());En.addGetterSetter(VB,"outerRadius",0,Ti());class c3 extends li{constructor(t){super(t),this._updated=!0,this.anim=new LN(()=>{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:VS.getPointAtLengthOfDataArray(t,this.dataArray,n)}_readDataAttribute(){this.dataArray=VS.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{v=n(t[x-1],t[x])*this.fontSize()}catch{}r.push({char:t[x],width:this._getTextSize(t[x]).width,kern:v}),a+=r[x].width+v}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,v)=>v>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 A=VS.getLineLength(v.x,v.y,S.x,S.y),E=Math.atan2(S.y-v.y,S.x-v.x);this.glyphInfo.push({text:t[x],rotation:E,p0:v,p1:S,width:A}),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=Qn._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}}}qg.prototype._fillFunc=MGt;qg.prototype._strokeFunc=PGt;qg.prototype._fillFuncHit=MGt;qg.prototype._strokeFuncHit=PGt;qg.prototype.className="TextPath";qg.prototype._attrsAffectingSize=["text","fontSize","data","align","letterSpacing","kerningFunc","fontFamily","fontStyle","fontVariant","direction"];Hg(qg,!0);qg.prototype.on("dataChange.konva",function(){this._readDataAttribute(),this._setTextData()});qg.prototype.on(qg.prototype._attrsAffectingSize.filter(s=>s!=="data").map(s=>s+"Change.konva").join(" "),function(){this._setTextData()});En.addGetterSetter(qg,"data");En.addGetterSetter(qg,"fontFamily","Arial");En.addGetterSetter(qg,"fontSize",12,Ti());En.addGetterSetter(qg,"fontStyle",TGt);En.addGetterSetter(qg,"align","left");En.addGetterSetter(qg,"letterSpacing",0,Ti());En.addGetterSetter(qg,"textBaseline","middle");En.addGetterSetter(qg,"fontVariant",TGt);En.addGetterSetter(qg,"text",vln);En.addGetterSetter(qg,"textDecoration","");En.addGetterSetter(qg,"kerningFunc",void 0);En.addGetterSetter(qg,"direction","inherit");const LWe="tr-konva",bln=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","shouldOverdrawWholeAreaChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange","paddingChange"].map(s=>s+`.${LWe}`).join(" "),UBe="nodesRect",_ln=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","strokeChange","selfRectFuncChange","strokeLinearGradientColorStopsChange","strokeScaleEnabledChange","strokeEnabledChange","draggableChange"],wln={"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 Nln(s,t,n){if(s==="rotater")return n;t+=Qn.degToRad(wln[s]||0);const r=(Qn.radToDeg(t)%360+360)%360;return Qn._inRange(r,315+22.5,360)||Qn._inRange(r,0,22.5)?"ns-resize":Qn._inRange(r,45-22.5,45+22.5)?"nesw-resize":Qn._inRange(r,90-22.5,90+22.5)?"ew-resize":Qn._inRange(r,135-22.5,135+22.5)?"nwse-resize":Qn._inRange(r,180-22.5,180+22.5)?"ns-resize":Qn._inRange(r,225-22.5,225+22.5)?"nesw-resize":Qn._inRange(r,270-22.5,270+22.5)?"ew-resize":Qn._inRange(r,315-22.5,315+22.5)?"nwse-resize":(Qn.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const FTe=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function kln(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 Sln(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 Cln(s,t){const n=kln(s);return Sln(s,t,n)}function Aln(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 b3e=new Set;let Vu=class extends Z7{static _isLayerTransforming(t){for(const n of b3e)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(bln,n=>{n.type==="ignoreStrokeChange"&&this._resetTransformCache(),this.update()}),this.on(`rotationChange.${LWe}`,()=>this._clearCache(UBe)),this.getNode()&&this.update()}attachTo(t){return this.setNode(t),this}setNode(t){return Qn.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 LWe+this._id}setNodes(t=[]){this._nodes&&this._nodes.length&&this.detach();const n=new Set(t);for(const a of n)a.isAncestorOf(this)&&(Qn.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(_ln.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(UBe),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(UBe,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 v0;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 v=f?l.get(m):void 0;if(!v||v.rotation!==r||v.ignoreStroke!==a||v.version!==m._attrsVersion||v.width!==g||v.height!==x){let y=m.getAbsoluteTransform();const[b,w,S,A]=y.getMatrix(),E=b*A-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&&(y=new v0),v={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(y.point(R));v.minX=Math.min(v.minX,D.x),v.minY=Math.min(v.minY,D.y),v.maxX=Math.max(v.maxX,D.x),v.maxY=Math.max(v.maxY,D.y)}f&&l.set(m,v)}o=Math.min(o,v.minX),c=Math.min(c,v.minY),d=Math.max(d,v.maxX),u=Math.max(u,v.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(),FTe.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new xie({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=Nln(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=twt(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:Qn._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},b3e.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=Qn.degToRad(this.rotateAnchorAngle());let A=Math.atan2(-r,n)+Math.PI/2-S;const I=Qo.getAngle(this.rotation())+A,P=Qo.getAngle(this.rotationSnapTolerance()),D=Aln(this.rotationSnaps(),I,P)-w.rotation,O=Cln(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,A=this._anchors["top-left"].y()>w.y?-1:1;n=a*this.cos*S,r=a*this.sin*A,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*A,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();b3e.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||Qn._inRange(t.width,-this.padding()*2-i,i)||Qn._inRange(t.height,-this.padding()*2-i,i)){this.update();return}const l=new v0;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 y=l.point({x:-o,y:0});t.x+=y.x,t.y+=y.y,t.width+=o,c={axis:"width",from:"left",to:"right",offset:y}}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const y=l.point({x:o,y:0});t.width+=o,c={axis:"width",from:"right",to:"left",offset:y}}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const y=l.point({x:0,y:-o});t.x+=y.x,t.y+=y.y,t.height+=o,d={axis:"height",from:"top",to:"bottom",offset:y}}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const y=l.point({x:0,y:o});t.height+=o,d={axis:"height",from:"bottom",to:"top",offset:y}}if(this.boundBoxFunc()){const y=this.boundBoxFunc()(a,t);y?t=y:Qn.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}for(const y of[c,d])y&&t[y.axis]<0&&this._movingAnchorName&&(this._movingAnchorName=this._movingAnchorName.replace(y.from,y.to),this._anchorDragOffset.x-=y.offset.x,this._anchorDragOffset.y-=y.offset.y);const u=1e7,h=new v0;h.translate(a.x,a.y),h.rotate(a.rotation),h.scale(a.width/u,a.height/u);const m=new v0,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()),v=new Set;this._nodes.forEach(y=>{if(!y.getStage())return;const b=y.getParent().getAbsoluteTransform(),w=y.getTransform().copy();w.translate(y.offsetX(),y.offsetY());const S=new v0;S.multiply(b.copy().invert()).multiply(x).multiply(b).multiply(w);const A=S.decompose();y.setAttrs(A);const E=y.getLayer();E&&v.add(E)}),this.rotation(Qn._getRotation(t.rotation)),this._nodes.forEach(y=>{this._fire("transform",{evt:n,target:y}),y._fire("transform",{evt:n,target:y})}),this._resetTransformCache(),this.update(),v.add(this.getLayer()),v.forEach(y=>y&&y.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=twt(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=""),Z7.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(Qn.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}}};Vu.isTransforming=()=>b3e.size>0;function Eln(s){return s instanceof Array||Qn.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){FTe.indexOf(t)===-1&&Qn.warn("Unknown anchor name: "+t+". Available names are: "+FTe.join(", "))}),s||[]}Vu.prototype.className="Transformer";Hg(Vu);En.addGetterSetter(Vu,"enabledAnchors",FTe,Eln);En.addGetterSetter(Vu,"flipEnabled",!0,wC());En.addGetterSetter(Vu,"resizeEnabled",!0);En.addGetterSetter(Vu,"anchorSize",10,Ti());En.addGetterSetter(Vu,"rotateEnabled",!0);En.addGetterSetter(Vu,"rotateLineVisible",!0);En.addGetterSetter(Vu,"rotationSnaps",[]);En.addGetterSetter(Vu,"rotateAnchorOffset",50,Ti());En.addGetterSetter(Vu,"rotateAnchorAngle",0,Ti());En.addGetterSetter(Vu,"rotateAnchorCursor","crosshair");En.addGetterSetter(Vu,"rotationSnapTolerance",5,Ti());En.addGetterSetter(Vu,"borderEnabled",!0);En.addGetterSetter(Vu,"anchorStroke","rgb(0, 161, 255)");En.addGetterSetter(Vu,"anchorStrokeWidth",1,Ti());En.addGetterSetter(Vu,"anchorFill","white");En.addGetterSetter(Vu,"anchorCornerRadius",0,Ti());En.addGetterSetter(Vu,"borderStroke","rgb(0, 161, 255)");En.addGetterSetter(Vu,"borderStrokeWidth",1,Ti());En.addGetterSetter(Vu,"borderDash");En.addGetterSetter(Vu,"keepRatio",!0);En.addGetterSetter(Vu,"shiftBehavior","default");En.addGetterSetter(Vu,"centeredScaling",!1);En.addGetterSetter(Vu,"ignoreStroke",!1);En.addGetterSetter(Vu,"padding",0,Ti());En.addGetterSetter(Vu,"nodes");En.addGetterSetter(Vu,"node");En.addGetterSetter(Vu,"boundBoxFunc");En.addGetterSetter(Vu,"anchorDragBoundFunc");En.addGetterSetter(Vu,"anchorStyleFunc");En.addGetterSetter(Vu,"shouldOverdrawWholeArea",!1);En.addGetterSetter(Vu,"useSingleNodeRotation",!0);En.backCompat(Vu,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class PT 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)}}PT.prototype.className="Wedge";PT.prototype._centroid=!0;PT.prototype._attrsAffectingSize=["radius"];Hg(PT,!0);En.addGetterSetter(PT,"radius",0,Ti());En.addGetterSetter(PT,"angle",0,Ti());En.addGetterSetter(PT,"clockwise",!1);En.backCompat(PT,{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 swt(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const Tln=[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],Mln=[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 eA(s,t){return t===255?s:s*t/255}const IGt=180;function Pln(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,m,f,g,x,v,y,b,w,S,A,E,I,P;const R=t+t+1,D=r-1,O=a-1,U=t+1,W=U*(U+1)/2,V=new swt,G=t<=IGt?Tln[t]/2**Mln[t]:1/(U*U);let Z=null,X=V,ae=null,le=null;for(let re=1;re0?(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=re+((i=J+U)0&&Pln(t,r)};En.addGetterSetter(zi,"blurRadius",0,Ti(),En.afterSetFilter);const Lln=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};En.addGetterSetter(zi,"contrast",0,Ti(),En.afterSetFilter);const Fln=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)),v=(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,y=!!((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=v*Math.PI/180,A=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,v,y,b;if(m>0)f=a+m*(255-a),g=r-m*(r-0),x=o+m*(255-o),v=l-m*(l-0),y=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),v=l+m*(l-S);const A=(u+d)*.5;y=u+m*(u-A),b=d+m*(d-A)}for(let w=0;wd?m:d;const f=l,g=i,x=360/g*Math.PI/180;for(let v=0;vd?m:d;const f=l,g=i,x=0;let v,y;for(u=0;ut&&(w=b,S=0,A=-1),a=0;a=0&&f=0&&g=0&&f=0&&g=255*4?255:0}return l}function Xln(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)),En.afterSetFilter);const rcn=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},icn=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;aur||lt[Ys]!==Ot[ur]){var Or=` `+lt[Ys].replace(" at new "," at ");return ie.displayName&&Or.includes("")&&(Or=Or.replace("",ie.displayName)),Or}while(1<=Ys&&0<=ur);break}}}finally{Ho=!1,Error.prepareStackTrace=Oe}return(ie=ie?ie.displayName||ie.name:"")?Nl(ie):""}var Yr=Object.prototype.hasOwnProperty,Eo=[],Th=-1;function rh(ie){return{current:ie}}function ro(ie){0>Th||(ie.current=Eo[Th],Eo[Th]=null,Th--)}function ea(ie,de){Th++,Eo[Th]=ie.current,ie.current=de}var pc={},ml=rh(pc),Co=rh(!1),mu=pc;function cc(ie,de){var Oe=ie.type.contextTypes;if(!Oe)return pc;var tt=ie.stateNode;if(tt&&tt.__reactInternalMemoizedUnmaskedChildContext===de)return tt.__reactInternalMemoizedMaskedChildContext;var lt={},Ot;for(Ot in Oe)lt[Ot]=de[Ot];return tt&&(ie=ie.stateNode,ie.__reactInternalMemoizedUnmaskedChildContext=de,ie.__reactInternalMemoizedMaskedChildContext=lt),lt}function nd(ie){return ie=ie.childContextTypes,ie!=null}function Dr(){ro(Co),ro(ml)}function Hi(ie,de,Oe){if(ml.current!==pc)throw Error(l(168));ea(ml,de),ea(Co,Oe)}function zc(ie,de,Oe){var tt=ie.stateNode;if(de=de.childContextTypes,typeof tt.getChildContext!="function")return Oe;tt=tt.getChildContext();for(var lt in tt)if(!(lt in de))throw Error(l(108,P(ie)||"Unknown",lt));return i({},Oe,tt)}function Bc(ie){return ie=(ie=ie.stateNode)&&ie.__reactInternalMemoizedMergedChildContext||pc,mu=ml.current,ea(ml,ie),ea(Co,Co.current),!0}function gc(ie,de,Oe){var tt=ie.stateNode;if(!tt)throw Error(l(169));Oe?(ie=zc(ie,de,mu),tt.__reactInternalMemoizedMergedChildContext=ie,ro(Co),ro(ml),ea(ml,ie)):ro(Co),ea(Co,Oe)}var $l=Math.clz32?Math.clz32:Yo,sg=Math.log,Mx=Math.LN2;function Yo(ie){return ie>>>=0,ie===0?32:31-(sg(ie)/Mx|0)|0}var Mc=64,Mh=4194304;function lm(ie){switch(ie&-ie){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 ie&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return ie&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return ie}}function Yc(ie,de){var Oe=ie.pendingLanes;if(Oe===0)return 0;var tt=0,lt=ie.suspendedLanes,Ot=ie.pingedLanes,Ys=Oe&268435455;if(Ys!==0){var ur=Ys&~lt;ur!==0?tt=lm(ur):(Ot&=Ys,Ot!==0&&(tt=lm(Ot)))}else Ys=Oe&~lt,Ys!==0?tt=lm(Ys):Ot!==0&&(tt=lm(Ot));if(tt===0)return 0;if(de!==0&&de!==tt&&!(de<)&&(lt=tt&-tt,Ot=de&-de,lt>=Ot||lt===16&&(Ot&4194240)!==0))return de;if(tt&4&&(tt|=Oe&16),de=ie.entangledLanes,de!==0)for(ie=ie.entanglements,de&=tt;0Oe;Oe++)de.push(ie);return de}function ko(ie,de,Oe){ie.pendingLanes|=de,de!==536870912&&(ie.suspendedLanes=0,ie.pingedLanes=0),ie=ie.eventTimes,de=31-$l(de),ie[de]=Oe}function qi(ie,de){var Oe=ie.pendingLanes&~de;ie.pendingLanes=de,ie.suspendedLanes=0,ie.pingedLanes=0,ie.expiredLanes&=de,ie.mutableReadLanes&=de,ie.entangledLanes&=de,de=ie.entanglements;var tt=ie.eventTimes;for(ie=ie.expirationTimes;0>=Ys,lt-=Ys,er=1<<32-$l(de)+lt|Oe<Md?(bh=Sc,Sc=null):bh=Sc.sibling;var Sl=Zi(zr,Sc,aa[Md],Qi);if(Sl===null){Sc===null&&(Sc=bh);break}ie&&Sc&&Sl.alternate===null&&de(zr,Sc),Hn=Ot(Sl,Hn,Md),Jc===null?gl=Sl:Jc.sibling=Sl,Jc=Sl,Sc=bh}if(Md===aa.length)return Oe(zr,Sc),en&&gr(zr,Md),gl;if(Sc===null){for(;MdMd?(bh=Sc,Sc=null):bh=Sc.sibling;var fr=Zi(zr,Sc,Sl.value,Qi);if(fr===null){Sc===null&&(Sc=bh);break}ie&&Sc&&fr.alternate===null&&de(zr,Sc),Hn=Ot(fr,Hn,Md),Jc===null?gl=fr:Jc.sibling=fr,Jc=fr,Sc=bh}if(Sl.done)return Oe(zr,Sc),en&&gr(zr,Md),gl;if(Sc===null){for(;!Sl.done;Md++,Sl=aa.next())Sl=pl(zr,Sl.value,Qi),Sl!==null&&(Hn=Ot(Sl,Hn,Md),Jc===null?gl=Sl:Jc.sibling=Sl,Jc=Sl);return en&&gr(zr,Md),gl}for(Sc=tt(zr,Sc);!Sl.done;Md++,Sl=aa.next())Sl=Hh(Sc,zr,Md,Sl.value,Qi),Sl!==null&&(ie&&Sl.alternate!==null&&Sc.delete(Sl.key===null?Md:Sl.key),Hn=Ot(Sl,Hn,Md),Jc===null?gl=Sl:Jc.sibling=Sl,Jc=Sl);return ie&&Sc.forEach(function(kr){return de(zr,kr)}),en&&gr(zr,Md),gl}function U_(zr,Hn,aa,Qi){if(typeof aa=="object"&&aa!==null&&aa.type===u&&aa.key===null&&(aa=aa.props.children),typeof aa=="object"&&aa!==null){switch(aa.$$typeof){case c:e:{for(var gl=aa.key,Jc=Hn;Jc!==null;){if(Jc.key===gl){if(gl=aa.type,gl===u){if(Jc.tag===7){Oe(zr,Jc.sibling),Hn=lt(Jc,aa.props.children),Hn.return=zr,zr=Hn;break e}}else if(Jc.elementType===gl||typeof gl=="object"&&gl!==null&&gl.$$typeof===w&&au(gl)===Jc.type){Oe(zr,Jc.sibling),Hn=lt(Jc,aa.props),Hn.ref=Pl(zr,Jc,aa),Hn.return=zr,zr=Hn;break e}Oe(zr,Jc);break}else de(zr,Jc);Jc=Jc.sibling}aa.type===u?(Hn=tj(aa.props.children,zr.mode,Qi,aa.key),Hn.return=zr,zr=Hn):(Qi=Uk(aa.type,aa.key,aa.props,null,zr.mode,Qi),Qi.ref=Pl(zr,Hn,aa),Qi.return=zr,zr=Qi)}return Ys(zr);case d:e:{for(Jc=aa.key;Hn!==null;){if(Hn.key===Jc)if(Hn.tag===4&&Hn.stateNode.containerInfo===aa.containerInfo&&Hn.stateNode.implementation===aa.implementation){Oe(zr,Hn.sibling),Hn=lt(Hn,aa.children||[]),Hn.return=zr,zr=Hn;break e}else{Oe(zr,Hn);break}else de(zr,Hn);Hn=Hn.sibling}Hn=BC(aa,zr.mode,Qi),Hn.return=zr,zr=Hn}return Ys(zr);case w:return Jc=aa._init,U_(zr,Hn,Jc(aa._payload),Qi)}if(G(aa))return uh(zr,Hn,aa,Qi);if(E(aa))return xy(zr,Hn,aa,Qi);Cd(zr,aa)}return typeof aa=="string"&&aa!==""||typeof aa=="number"?(aa=""+aa,Hn!==null&&Hn.tag===6?(Oe(zr,Hn.sibling),Hn=lt(Hn,aa),Hn.return=zr,zr=Hn):(Oe(zr,Hn),Hn=zC(aa,zr.mode,Qi),Hn.return=zr,zr=Hn),Ys(zr)):Oe(zr,Hn)}return U_}var Nn=Vt(!0),nr=Vt(!1),na=rh(null),Wr=null,Ca=null,gi=null;function Ia(){gi=Ca=Wr=null}function el(ie,de,Oe){Ie?(ea(na,de._currentValue),de._currentValue=Oe):(ea(na,de._currentValue2),de._currentValue2=Oe)}function zo(ie){var de=na.current;ro(na),Ie?ie._currentValue=de:ie._currentValue2=de}function Pc(ie,de,Oe){for(;ie!==null;){var tt=ie.alternate;if((ie.childLanes&de)!==de?(ie.childLanes|=de,tt!==null&&(tt.childLanes|=de)):tt!==null&&(tt.childLanes&de)!==de&&(tt.childLanes|=de),ie===Oe)break;ie=ie.return}}function Eu(ie,de){Wr=ie,gi=Ca=null,ie=ie.dependencies,ie!==null&&ie.firstContext!==null&&(ie.lanes&de&&(Xg=!0),ie.firstContext=null)}function iu(ie){var de=Ie?ie._currentValue:ie._currentValue2;if(gi!==ie)if(ie={context:ie,memoizedValue:de,next:null},Ca===null){if(Wr===null)throw Error(l(308));Ca=ie,Wr.dependencies={lanes:0,firstContext:ie}}else Ca=Ca.next=ie;return de}var dm=null;function Ad(ie){dm===null?dm=[ie]:dm.push(ie)}function fu(ie,de,Oe,tt){var lt=de.interleaved;return lt===null?(Oe.next=Oe,Ad(de)):(Oe.next=lt.next,lt.next=Oe),de.interleaved=Oe,Zc(ie,tt)}function Zc(ie,de){ie.lanes|=de;var Oe=ie.alternate;for(Oe!==null&&(Oe.lanes|=de),Oe=ie,ie=ie.return;ie!==null;)ie.childLanes|=de,Oe=ie.alternate,Oe!==null&&(Oe.childLanes|=de),Oe=ie,ie=ie.return;return Oe.tag===3?Oe.stateNode:null}var rd=!1;function ih(ie){ie.updateQueue={baseState:ie.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Pf(ie,de){ie=ie.updateQueue,de.updateQueue===ie&&(de.updateQueue={baseState:ie.baseState,firstBaseUpdate:ie.firstBaseUpdate,lastBaseUpdate:ie.lastBaseUpdate,shared:ie.shared,effects:ie.effects})}function Od(ie,de){return{eventTime:ie,lane:de,tag:0,payload:null,callback:null,next:null}}function ad(ie,de,Oe){var tt=ie.updateQueue;if(tt===null)return null;if(tt=tt.shared,Jl&2){var lt=tt.pending;return lt===null?de.next=de:(de.next=lt.next,lt.next=de),tt.pending=de,Zc(ie,Oe)}return lt=tt.interleaved,lt===null?(de.next=de,Ad(tt)):(de.next=lt.next,lt.next=de),tt.interleaved=de,Zc(ie,Oe)}function Ph(ie,de,Oe){if(de=de.updateQueue,de!==null&&(de=de.shared,(Oe&4194240)!==0)){var tt=de.lanes;tt&=ie.pendingLanes,Oe|=tt,de.lanes=Oe,cm(ie,Oe)}}function Hu(ie,de){var Oe=ie.updateQueue,tt=ie.alternate;if(tt!==null&&(tt=tt.updateQueue,Oe===tt)){var lt=null,Ot=null;if(Oe=Oe.firstBaseUpdate,Oe!==null){do{var Ys={eventTime:Oe.eventTime,lane:Oe.lane,tag:Oe.tag,payload:Oe.payload,callback:Oe.callback,next:null};Ot===null?lt=Ot=Ys:Ot=Ot.next=Ys,Oe=Oe.next}while(Oe!==null);Ot===null?lt=Ot=de:Ot=Ot.next=de}else lt=Ot=de;Oe={baseState:tt.baseState,firstBaseUpdate:lt,lastBaseUpdate:Ot,shared:tt.shared,effects:tt.effects},ie.updateQueue=Oe;return}ie=Oe.lastBaseUpdate,ie===null?Oe.firstBaseUpdate=de:ie.next=de,Oe.lastBaseUpdate=de}function zd(ie,de,Oe,tt){var lt=ie.updateQueue;rd=!1;var Ot=lt.firstBaseUpdate,Ys=lt.lastBaseUpdate,ur=lt.shared.pending;if(ur!==null){lt.shared.pending=null;var Or=ur,ci=Or.next;Or.next=null,Ys===null?Ot=ci:Ys.next=ci,Ys=Or;var Mi=ie.alternate;Mi!==null&&(Mi=Mi.updateQueue,ur=Mi.lastBaseUpdate,ur!==Ys&&(ur===null?Mi.firstBaseUpdate=ci:ur.next=ci,Mi.lastBaseUpdate=Or))}if(Ot!==null){var pl=lt.baseState;Ys=0,Mi=ci=Or=null,ur=Ot;do{var Zi=ur.lane,Hh=ur.eventTime;if((tt&Zi)===Zi){Mi!==null&&(Mi=Mi.next={eventTime:Hh,lane:0,tag:ur.tag,payload:ur.payload,callback:ur.callback,next:null});e:{var uh=ie,xy=ur;switch(Zi=de,Hh=Oe,xy.tag){case 1:if(uh=xy.payload,typeof uh=="function"){pl=uh.call(Hh,pl,Zi);break e}pl=uh;break e;case 3:uh.flags=uh.flags&-65537|128;case 0:if(uh=xy.payload,Zi=typeof uh=="function"?uh.call(Hh,pl,Zi):uh,Zi==null)break e;pl=i({},pl,Zi);break e;case 2:rd=!0}}ur.callback!==null&&ur.lane!==0&&(ie.flags|=64,Zi=lt.effects,Zi===null?lt.effects=[ur]:Zi.push(ur))}else Hh={eventTime:Hh,lane:Zi,tag:ur.tag,payload:ur.payload,callback:ur.callback,next:null},Mi===null?(ci=Mi=Hh,Or=pl):Mi=Mi.next=Hh,Ys|=Zi;if(ur=ur.next,ur===null){if(ur=lt.shared.pending,ur===null)break;Zi=ur,ur=Zi.next,Zi.next=null,lt.lastBaseUpdate=Zi,lt.shared.pending=null}}while(!0);if(Mi===null&&(Or=pl),lt.baseState=Or,lt.firstBaseUpdate=ci,lt.lastBaseUpdate=Mi,de=lt.shared.interleaved,de!==null){lt=de;do Ys|=lt.lane,lt=lt.next;while(lt!==de)}else Ot===null&&(lt.shared.lanes=0);z1|=Ys,ie.lanes=Ys,ie.memoizedState=pl}}function dd(ie,de,Oe){if(ie=de.effects,de.effects=null,ie!==null)for(de=0;deOe?Oe:4,ie(!0);var tt=Ix.transition;Ix.transition={};try{ie(!1),de()}finally{Zo=Oe,Ix.transition=tt}}function Pb(){return df().memoizedState}function Ov(ie,de,Oe){var tt=U1(ie);if(Oe={lane:tt,action:Oe,hasEagerState:!1,eagerState:null,next:null},U2(ie))np(de,Oe);else if(Oe=fu(ie,de,Oe,tt),Oe!==null){var lt=lp();zx(Oe,ie,tt,lt),Pk(Oe,de,tt)}}function N3(ie,de,Oe){var tt=U1(ie),lt={lane:tt,action:Oe,hasEagerState:!1,eagerState:null,next:null};if(U2(ie))np(de,lt);else{var Ot=ie.alternate;if(ie.lanes===0&&(Ot===null||Ot.lanes===0)&&(Ot=de.lastRenderedReducer,Ot!==null))try{var Ys=de.lastRenderedState,ur=Ot(Ys,Oe);if(lt.hasEagerState=!0,lt.eagerState=ur,Nt(ur,Ys)){var Or=de.interleaved;Or===null?(lt.next=lt,Ad(de)):(lt.next=Or.next,Or.next=lt),de.interleaved=lt;return}}catch{}finally{}Oe=fu(ie,de,lt,tt),Oe!==null&&(lt=lp(),zx(Oe,ie,tt,lt),Pk(Oe,de,tt))}}function U2(ie){var de=ie.alternate;return ie===kc||de!==null&&de===kc}function np(ie,de){da=pu=!0;var Oe=ie.pending;Oe===null?de.next=de:(de.next=Oe.next,Oe.next=de),ie.pending=de}function Pk(ie,de,Oe){if(Oe&4194240){var tt=de.lanes;tt&=ie.pendingLanes,Oe|=tt,de.lanes=Oe,cm(ie,Oe)}}var R1={readContext:iu,useCallback:Qc,useContext:Qc,useEffect:Qc,useImperativeHandle:Qc,useInsertionEffect:Qc,useLayoutEffect:Qc,useMemo:Qc,useReducer:Qc,useRef:Qc,useState:Qc,useDebugValue:Qc,useDeferredValue:Qc,useTransition:Qc,useMutableSource:Qc,useSyncExternalStore:Qc,useId:Qc,unstable_isNewReconciler:!1},Zg={readContext:iu,useCallback:function(ie,de){return xh().memoizedState=[ie,de===void 0?null:de],ie},useContext:iu,useEffect:Kg,useImperativeHandle:function(ie,de,Oe){return Oe=Oe!=null?Oe.concat([ie]):null,oh(4194308,4,P1.bind(null,de,ie),Oe)},useLayoutEffect:function(ie,de){return oh(4194308,4,ie,de)},useInsertionEffect:function(ie,de){return oh(4,2,ie,de)},useMemo:function(ie,de){var Oe=xh();return de=de===void 0?null:de,ie=ie(),Oe.memoizedState=[ie,de],ie},useReducer:function(ie,de,Oe){var tt=xh();return de=Oe!==void 0?Oe(de):de,tt.memoizedState=tt.baseState=de,ie={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:ie,lastRenderedState:de},tt.queue=ie,ie=ie.dispatch=Ov.bind(null,kc,ie),[tt.memoizedState,ie]},useRef:function(ie){var de=xh();return ie={current:ie},de.memoizedState=ie},useState:yh,useDebugValue:L1,useDeferredValue:function(ie){return xh().memoizedState=ie},useTransition:function(){var ie=yh(!1),de=ie[0];return ie=Mk.bind(null,ie[1]),xh().memoizedState=ie,[de,ie]},useMutableSource:function(){},useSyncExternalStore:function(ie,de,Oe){var tt=kc,lt=xh();if(en){if(Oe===void 0)throw Error(l(407));Oe=Oe()}else{if(Oe=de(),Ud===null)throw Error(l(349));Gu&30||Mb(tt,de,Oe)}lt.memoizedState=Oe;var Ot={value:Oe,getSnapshot:de};return lt.queue=Ot,Kg(zm.bind(null,tt,Ot,ie),[ie]),tt.flags|=2048,Ui(9,Ww.bind(null,tt,Ot,Oe,de),void 0,null),Oe},useId:function(){var ie=xh(),de=Ud.identifierPrefix;if(en){var Oe=xr,tt=er;Oe=(tt&~(1<<32-$l(tt)-1)).toString(32)+Oe,de=":"+de+"R"+Oe,Oe=Ao++,0Ok&&(de.flags|=128,tt=!0,jr(lt,!1),de.lanes=4194304)}else{if(!tt)if(ie=Ky(Ot),ie!==null){if(de.flags|=128,tt=!0,ie=ie.updateQueue,ie!==null&&(de.updateQueue=ie,de.flags|=4),jr(lt,!0),lt.tail===null&<.tailMode==="hidden"&&!Ot.alternate&&!en)return Qs(de),null}else 2*Kd()-lt.renderingStartTime>Ok&&Oe!==1073741824&&(de.flags|=128,tt=!0,jr(lt,!1),de.lanes=4194304);lt.isBackwards?(Ot.sibling=de.child,de.child=Ot):(ie=lt.last,ie!==null?ie.sibling=Ot:de.child=Ot,lt.last=Ot)}return lt.tail!==null?(de=lt.tail,lt.rendering=de,lt.tail=de.sibling,lt.renderingStartTime=Kd(),de.sibling=null,ie=ya.current,ea(ya,tt?ie&1|2:ie&1),de):(Qs(de),null);case 22:case 23:return $_(),Oe=de.memoizedState!==null,ie!==null&&ie.memoizedState!==null!==Oe&&(de.flags|=8192),Oe&&de.mode&1?Fx&1073741824&&(Qs(de),Fe&&de.subtreeFlags&6&&(de.flags|=8192)):Qs(de),null;case 24:return null;case 25:return null}throw Error(l(156,de.tag))}function yr(ie,de){switch(Gt(de),de.tag){case 1:return nd(de.type)&&Dr(),ie=de.flags,ie&65536?(de.flags=ie&-65537|128,de):null;case 3:return Ap(),ro(Co),ro(ml),Wg(),ie=de.flags,ie&65536&&!(ie&128)?(de.flags=ie&-65537|128,de):null;case 5:return Px(de),null;case 13:if(ro(ya),ie=de.memoizedState,ie!==null&&ie.dehydrated!==null){if(de.alternate===null)throw Error(l(340));io()}return ie=de.flags,ie&65536?(de.flags=ie&-65537|128,de):null;case 19:return ro(ya),null;case 4:return Ap(),null;case 10:return zo(de.type._context),null;case 22:case 23:return $_(),null;case 24:return null;default:return null}}var ra=!1,dr=!1,ua=typeof WeakSet=="function"?WeakSet:Set,lr=null;function Ua(ie,de){var Oe=ie.ref;if(Oe!==null)if(typeof Oe=="function")try{Oe(null)}catch(tt){_m(ie,de,tt)}else Oe.current=null}function Aa(ie,de,Oe){try{Oe()}catch(tt){_m(ie,de,tt)}}var _o=!1;function Fi(ie,de){for(le(ie.containerInfo),lr=de;lr!==null;)if(ie=lr,de=ie.child,(ie.subtreeFlags&1028)!==0&&de!==null)de.return=ie,lr=de;else for(;lr!==null;){ie=lr;try{var Oe=ie.alternate;if(ie.flags&1024)switch(ie.tag){case 0:case 11:case 15:break;case 1:if(Oe!==null){var tt=Oe.memoizedProps,lt=Oe.memoizedState,Ot=ie.stateNode,Ys=Ot.getSnapshotBeforeUpdate(ie.elementType===ie.type?tt:$d(ie.type,tt),lt);Ot.__reactInternalSnapshotBeforeUpdate=Ys}break;case 3:Fe&&zt(ie.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(ur){_m(ie,ie.return,ur)}if(de=ie.sibling,de!==null){de.return=ie.return,lr=de;break}lr=ie.return}return Oe=_o,_o=!1,Oe}function bl(ie,de,Oe){var tt=de.updateQueue;if(tt=tt!==null?tt.lastEffect:null,tt!==null){var lt=tt=tt.next;do{if((lt.tag&ie)===ie){var Ot=lt.destroy;lt.destroy=void 0,Ot!==void 0&&Aa(de,Oe,Ot)}lt=lt.next}while(lt!==tt)}}function oo(ie,de){if(de=de.updateQueue,de=de!==null?de.lastEffect:null,de!==null){var Oe=de=de.next;do{if((Oe.tag&ie)===ie){var tt=Oe.create;Oe.destroy=tt()}Oe=Oe.next}while(Oe!==de)}}function Lc(ie){var de=ie.ref;if(de!==null){var Oe=ie.stateNode;switch(ie.tag){case 5:ie=Z(Oe);break;default:ie=Oe}typeof de=="function"?de(ie):de.current=ie}}function hf(ie){var de=ie.alternate;de!==null&&(ie.alternate=null,hf(de)),ie.child=null,ie.deletions=null,ie.sibling=null,ie.tag===5&&(de=ie.stateNode,de!==null&&qe(de)),ie.stateNode=null,ie.return=null,ie.dependencies=null,ie.memoizedProps=null,ie.memoizedState=null,ie.pendingProps=null,ie.stateNode=null,ie.updateQueue=null}function Xl(ie){return ie.tag===5||ie.tag===3||ie.tag===4}function yo(ie){e:for(;;){for(;ie.sibling===null;){if(ie.return===null||Xl(ie.return))return null;ie=ie.return}for(ie.sibling.return=ie.return,ie=ie.sibling;ie.tag!==5&&ie.tag!==6&&ie.tag!==18;){if(ie.flags&2||ie.child===null||ie.tag===4)continue e;ie.child.return=ie,ie=ie.child}if(!(ie.flags&2))return ie.stateNode}}function vi(ie,de,Oe){var tt=ie.tag;if(tt===5||tt===6)ie=ie.stateNode,de?is(Oe,ie,de):Ht(Oe,ie);else if(tt!==4&&(ie=ie.child,ie!==null))for(vi(ie,de,Oe),ie=ie.sibling;ie!==null;)vi(ie,de,Oe),ie=ie.sibling}function hm(ie,de,Oe){var tt=ie.tag;if(tt===5||tt===6)ie=ie.stateNode,de?Ft(Oe,ie,de):es(Oe,ie);else if(tt!==4&&(ie=ie.child,ie!==null))for(hm(ie,de,Oe),ie=ie.sibling;ie!==null;)hm(ie,de,Oe),ie=ie.sibling}var To=null,Ql=!1;function $c(ie,de,Oe){for(Oe=Oe.child;Oe!==null;)If(ie,de,Oe),Oe=Oe.sibling}function If(ie,de,Oe){if(xt&&typeof xt.onCommitFiberUnmount=="function")try{xt.onCommitFiberUnmount(gh,Oe)}catch{}switch(Oe.tag){case 5:dr||Ua(Oe,de);case 6:if(Fe){var tt=To,lt=Ql;To=null,$c(ie,de,Oe),To=tt,Ql=lt,To!==null&&(Ql?zs(To,Oe.stateNode):jt(To,Oe.stateNode))}else $c(ie,de,Oe);break;case 18:Fe&&To!==null&&(Ql?xa(To,Oe.stateNode):Ln(To,Oe.stateNode));break;case 4:Fe?(tt=To,lt=Ql,To=Oe.stateNode.containerInfo,Ql=!0,$c(ie,de,Oe),To=tt,Ql=lt):(Ne&&(tt=Oe.stateNode.containerInfo,lt=dn(tt),Rr(tt,lt)),$c(ie,de,Oe));break;case 0:case 11:case 14:case 15:if(!dr&&(tt=Oe.updateQueue,tt!==null&&(tt=tt.lastEffect,tt!==null))){lt=tt=tt.next;do{var Ot=lt,Ys=Ot.destroy;Ot=Ot.tag,Ys!==void 0&&(Ot&2||Ot&4)&&Aa(Oe,de,Ys),lt=lt.next}while(lt!==tt)}$c(ie,de,Oe);break;case 1:if(!dr&&(Ua(Oe,de),tt=Oe.stateNode,typeof tt.componentWillUnmount=="function"))try{tt.props=Oe.memoizedProps,tt.state=Oe.memoizedState,tt.componentWillUnmount()}catch(ur){_m(Oe,de,ur)}$c(ie,de,Oe);break;case 21:$c(ie,de,Oe);break;case 22:Oe.mode&1?(dr=(tt=dr)||Oe.memoizedState!==null,$c(ie,de,Oe),dr=tt):$c(ie,de,Oe);break;default:$c(ie,de,Oe)}}function rg(ie){var de=ie.updateQueue;if(de!==null){ie.updateQueue=null;var Oe=ie.stateNode;Oe===null&&(Oe=ie.stateNode=new ua),de.forEach(function(tt){var lt=w9.bind(null,ie,tt);Oe.has(tt)||(Oe.add(tt),tt.then(lt,lt))})}}function Yd(ie,de){var Oe=de.deletions;if(Oe!==null)for(var tt=0;tt";case ip:return":has("+(Tp(ie)||"")+")";case dh:return'[role="'+ie.value+'"]';case xc:return'"'+ie.value+'"';case vh:return'[data-testname="'+ie.value+'"]';default:throw Error(l(365))}}function Jg(ie,de){var Oe=[];ie=[ie,0];for(var tt=0;ttlt&&(lt=Ys),tt&=~Ot}if(tt=lt,tt=Kd()-tt,tt=(120>tt?120:480>tt?480:1080>tt?1080:1920>tt?1920:3e3>tt?3e3:4320>tt?4320:1960*ex(tt/1960))-tt,10ie?16:ie,op===null)var tt=!1;else{if(ie=op,op=null,B_=0,Jl&6)throw Error(l(331));var lt=Jl;for(Jl|=4,lr=ie.current;lr!==null;){var Ot=lr,Ys=Ot.child;if(lr.flags&16){var ur=Ot.deletions;if(ur!==null){for(var Or=0;OrKd()-H2?og(ie,0):ig|=Oe),cp(ie,de)}function HT(ie,de){de===0&&(ie.mode&1?(de=Mh,Mh<<=1,!(Mh&130023424)&&(Mh=4194304)):de=1);var Oe=lp();ie=Zc(ie,de),ie!==null&&(ko(ie,de,Oe),cp(ie,Oe))}function _9(ie){var de=ie.memoizedState,Oe=0;de!==null&&(Oe=de.retryLane),HT(ie,Oe)}function w9(ie,de){var Oe=0;switch(ie.tag){case 13:var tt=ie.stateNode,lt=ie.memoizedState;lt!==null&&(Oe=lt.retryLane);break;case 19:tt=ie.stateNode;break;default:throw Error(l(314))}tt!==null&&tt.delete(de),HT(ie,Oe)}var $k;$k=function(ie,de,Oe){if(ie!==null)if(ie.memoizedProps!==de.pendingProps||Co.current)Xg=!0;else{if(!(ie.lanes&Oe)&&!(de.flags&128))return Xg=!1,Tt(ie,de,Oe);Xg=!!(ie.flags&131072)}else Xg=!1,en&&de.flags&1048576&&qa(de,gn,de.index);switch(de.lanes=0,de.tag){case 2:var tt=de.type;He(ie,de),ie=de.pendingProps;var lt=cc(de,ml.current);Eu(de,Oe),lt=Wo(null,de,tt,ie,lt,Oe);var Ot=B0();return de.flags|=1,typeof lt=="object"&<!==null&&typeof lt.render=="function"&<.$$typeof===void 0?(de.tag=1,de.memoizedState=null,de.updateQueue=null,nd(tt)?(Ot=!0,Bc(de)):Ot=!1,de.memoizedState=lt.state!==null&<.state!==void 0?lt.state:null,ih(de),lt.updater=PC,de.stateNode=lt,lt._reactInternals=de,Ib(de,tt,ie,Oe),de=Dk(null,de,tt,!0,Ot,Oe)):(de.tag=0,en&&Ot&&et(de),uf(null,de,lt,Oe),de=de.child),de;case 16:tt=de.elementType;e:{switch(He(ie,de),ie=de.pendingProps,lt=tt._init,tt=lt(tt._payload),de.type=tt,lt=de.tag=T3(tt),ie=$d(tt,ie),lt){case 0:de=q2(null,de,tt,ie,Oe);break e;case 1:de=Rk(null,de,tt,ie,Oe);break e;case 11:de=D1(null,de,tt,ie,Oe);break e;case 14:de=U0(null,de,tt,$d(tt.type,ie),Oe);break e}throw Error(l(306,tt,""))}return de;case 0:return tt=de.type,lt=de.pendingProps,lt=de.elementType===tt?lt:$d(tt,lt),q2(ie,de,tt,lt,Oe);case 1:return tt=de.type,lt=de.pendingProps,lt=de.elementType===tt?lt:$d(tt,lt),Rk(ie,de,tt,lt,Oe);case 3:e:{if(F_(de),ie===null)throw Error(l(387));tt=de.pendingProps,Ot=de.memoizedState,lt=Ot.element,Pf(ie,de),zd(de,tt,null,Oe);var Ys=de.memoizedState;if(tt=Ys.element,Be&&Ot.isDehydrated)if(Ot={element:tt,isDehydrated:!1,cache:Ys.cache,pendingSuspenseBoundaries:Ys.pendingSuspenseBoundaries,transitions:Ys.transitions},de.updateQueue.baseState=Ot,de.memoizedState=Ot,de.flags&256){lt=Ep(Error(l(423)),de),de=Xw(ie,de,tt,Oe,lt);break e}else if(tt!==lt){lt=Ep(Error(l(424)),de),de=Xw(ie,de,tt,Oe,lt);break e}else for(Be&&(on=la(de.stateNode.containerInfo),Es=de,en=!0,sr=null,tr=!1),Oe=nr(de,null,tt,Oe),de.child=Oe;Oe;)Oe.flags=Oe.flags&-3|4096,Oe=Oe.sibling;else{if(io(),tt===lt){de=pt(ie,de,Oe);break e}uf(ie,de,tt,Oe)}de=de.child}return de;case 5:return Dv(de),ie===null&&Na(de),tt=de.type,lt=de.pendingProps,Ot=ie!==null?ie.memoizedProps:null,Ys=lt.children,fe(tt,lt)?Ys=null:Ot!==null&&fe(tt,Ot)&&(de.flags|=32),Lk(ie,de),uf(ie,de,Ys,Oe),de.child;case 6:return ie===null&&Na(de),null;case 13:return V2(ie,de,Oe);case 4:return vd(de,de.stateNode.containerInfo),tt=de.pendingProps,ie===null?de.child=Nn(de,null,tt,Oe):uf(ie,de,tt,Oe),de.child;case 11:return tt=de.type,lt=de.pendingProps,lt=de.elementType===tt?lt:$d(tt,lt),D1(ie,de,tt,lt,Oe);case 7:return uf(ie,de,de.pendingProps,Oe),de.child;case 8:return uf(ie,de,de.pendingProps.children,Oe),de.child;case 12:return uf(ie,de,de.pendingProps.children,Oe),de.child;case 10:e:{if(tt=de.type._context,lt=de.pendingProps,Ot=de.memoizedProps,Ys=lt.value,el(de,tt,Ys),Ot!==null)if(Nt(Ot.value,Ys)){if(Ot.children===lt.children&&!Co.current){de=pt(ie,de,Oe);break e}}else for(Ot=de.child,Ot!==null&&(Ot.return=de);Ot!==null;){var ur=Ot.dependencies;if(ur!==null){Ys=Ot.child;for(var Or=ur.firstContext;Or!==null;){if(Or.context===tt){if(Ot.tag===1){Or=Od(-1,Oe&-Oe),Or.tag=2;var ci=Ot.updateQueue;if(ci!==null){ci=ci.shared;var Mi=ci.pending;Mi===null?Or.next=Or:(Or.next=Mi.next,Mi.next=Or),ci.pending=Or}}Ot.lanes|=Oe,Or=Ot.alternate,Or!==null&&(Or.lanes|=Oe),Pc(Ot.return,Oe,de),ur.lanes|=Oe;break}Or=Or.next}}else if(Ot.tag===10)Ys=Ot.type===de.type?null:Ot.child;else if(Ot.tag===18){if(Ys=Ot.return,Ys===null)throw Error(l(341));Ys.lanes|=Oe,ur=Ys.alternate,ur!==null&&(ur.lanes|=Oe),Pc(Ys,Oe,de),Ys=Ot.sibling}else Ys=Ot.child;if(Ys!==null)Ys.return=Ot;else for(Ys=Ot;Ys!==null;){if(Ys===de){Ys=null;break}if(Ot=Ys.sibling,Ot!==null){Ot.return=Ys.return,Ys=Ot;break}Ys=Ys.return}Ot=Ys}uf(ie,de,lt.children,Oe),de=de.child}return de;case 9:return lt=de.type,tt=de.pendingProps.children,Eu(de,Oe),lt=iu(lt),tt=tt(lt),de.flags|=1,uf(ie,de,tt,Oe),de.child;case 14:return tt=de.type,lt=$d(tt,de.pendingProps),lt=$d(tt.type,lt),U0(ie,de,tt,lt,Oe);case 15:return q0(ie,de,de.type,de.pendingProps,Oe);case 17:return tt=de.type,lt=de.pendingProps,lt=de.elementType===tt?lt:$d(tt,lt),He(ie,de),de.tag=1,nd(tt)?(ie=!0,Bc(de)):ie=!1,Eu(de,Oe),qT(de,tt,lt),Ib(de,tt,lt,Oe),Dk(null,de,tt,!0,ie,Oe);case 19:return Pe(ie,de,Oe);case 22:return Dx(ie,de,Oe)}throw Error(l(156,de.tag))};function FC(ie,de){return Gg(ie,de)}function OC(ie,de,Oe,tt){this.tag=ie,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=tt,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function G0(ie,de,Oe,tt){return new OC(ie,de,Oe,tt)}function GT(ie){return ie=ie.prototype,!(!ie||!ie.isReactComponent)}function T3(ie){if(typeof ie=="function")return GT(ie)?1:0;if(ie!=null){if(ie=ie.$$typeof,ie===x)return 11;if(ie===b)return 14}return 2}function Fb(ie,de){var Oe=ie.alternate;return Oe===null?(Oe=G0(ie.tag,de,ie.key,ie.mode),Oe.elementType=ie.elementType,Oe.type=ie.type,Oe.stateNode=ie.stateNode,Oe.alternate=ie,ie.alternate=Oe):(Oe.pendingProps=de,Oe.type=ie.type,Oe.flags=0,Oe.subtreeFlags=0,Oe.deletions=null),Oe.flags=ie.flags&14680064,Oe.childLanes=ie.childLanes,Oe.lanes=ie.lanes,Oe.child=ie.child,Oe.memoizedProps=ie.memoizedProps,Oe.memoizedState=ie.memoizedState,Oe.updateQueue=ie.updateQueue,de=ie.dependencies,Oe.dependencies=de===null?null:{lanes:de.lanes,firstContext:de.firstContext},Oe.sibling=ie.sibling,Oe.index=ie.index,Oe.ref=ie.ref,Oe}function Uk(ie,de,Oe,tt,lt,Ot){var Ys=2;if(tt=ie,typeof ie=="function")GT(ie)&&(Ys=1);else if(typeof ie=="string")Ys=5;else e:switch(ie){case u:return tj(Oe.children,lt,Ot,de);case h:Ys=8,lt|=8;break;case m:return ie=G0(12,Oe,de,lt|2),ie.elementType=m,ie.lanes=Ot,ie;case v:return ie=G0(13,Oe,de,lt),ie.elementType=v,ie.lanes=Ot,ie;case y:return ie=G0(19,Oe,de,lt),ie.elementType=y,ie.lanes=Ot,ie;case S:return qk(Oe,lt,Ot,de);default:if(typeof ie=="object"&&ie!==null)switch(ie.$$typeof){case f:Ys=10;break e;case g:Ys=9;break e;case x:Ys=11;break e;case b:Ys=14;break e;case w:Ys=16,tt=null;break e}throw Error(l(130,ie==null?ie:typeof ie,""))}return de=G0(Ys,Oe,de,lt),de.elementType=ie,de.type=tt,de.lanes=Ot,de}function tj(ie,de,Oe,tt){return ie=G0(7,ie,tt,de),ie.lanes=Oe,ie}function qk(ie,de,Oe,tt){return ie=G0(22,ie,tt,de),ie.elementType=S,ie.lanes=Oe,ie.stateNode={isHidden:!1},ie}function zC(ie,de,Oe){return ie=G0(6,ie,null,de),ie.lanes=Oe,ie}function BC(ie,de,Oe){return de=G0(4,ie.children!==null?ie.children:[],ie.key,de),de.lanes=Oe,de.stateNode={containerInfo:ie.containerInfo,pendingChildren:null,implementation:ie.implementation},de}function I6(ie,de,Oe,tt,lt){this.tag=de,this.containerInfo=ie,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=ke,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=ao(0),this.expirationTimes=ao(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ao(0),this.identifierPrefix=tt,this.onRecoverableError=lt,Be&&(this.mutableSourceEagerHydrationData=null)}function M3(ie,de,Oe,tt,lt,Ot,Ys,ur,Or){return ie=new I6(ie,de,Oe,ur,Or),de===1?(de=1,Ot===!0&&(de|=8)):de=0,Ot=G0(3,null,null,de),ie.current=Ot,Ot.stateNode=ie,Ot.memoizedState={element:tt,isDehydrated:Oe,cache:null,transitions:null,pendingSuspenseBoundaries:null},ih(Ot),ie}function L6(ie){if(!ie)return pc;ie=ie._reactInternals;e:{if(R(ie)!==ie||ie.tag!==1)throw Error(l(170));var de=ie;do{switch(de.tag){case 3:de=de.stateNode.context;break e;case 1:if(nd(de.type)){de=de.stateNode.__reactInternalMemoizedMergedChildContext;break e}}de=de.return}while(de!==null);throw Error(l(171))}if(ie.tag===1){var Oe=ie.type;if(nd(Oe))return zc(ie,Oe,de)}return de}function WT(ie){var de=ie._reactInternals;if(de===void 0)throw typeof ie.render=="function"?Error(l(188)):(ie=Object.keys(ie).join(","),Error(l(268,ie)));return ie=U(de),ie===null?null:ie.stateNode}function R6(ie,de){if(ie=ie.memoizedState,ie!==null&&ie.dehydrated!==null){var Oe=ie.retryLane;ie.retryLane=Oe!==0&&Oe=ci&&Ot>=pl&<<=Mi&&Ys<=Zi){ie.splice(de,1);break}else if(tt!==ci||Oe.width!==Or.width||ZiYs){if(!(Ot!==pl||Oe.height!==Or.height||Milt)){ci>tt&&(Or.width+=ci-tt,Or.x=tt),MiOt&&(Or.height+=pl-Ot,Or.y=Ot),ZiOe&&(Oe=Ys)),Ys ")+` No matching component was found for: `)+ie.join(" > ")}return null},n.getPublicRootInstance=function(ie){if(ie=ie.current,!ie.child)return null;switch(ie.child.tag){case 5:return Z(ie.child.stateNode);default:return ie.child.stateNode}},n.injectIntoDevTools=function(ie){if(ie={bundleType:ie.bundleType,version:ie.version,rendererPackageName:ie.rendererPackageName,rendererConfig:ie.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:o.ReactCurrentDispatcher,findHostInstanceByFiber:j9,findFiberByHostInstance:ie.findFiberByHostInstance||D6,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")ie=!1;else{var de=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(de.isDisabled||!de.supportsFiber)ie=!0;else{try{gh=de.inject(ie),xt=de}catch{}ie=!!de.checkDCE}}return ie},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(ie,de,Oe,tt){if(!ht)throw Error(l(363));ie=Mp(ie,de);var lt=gt(ie,Oe,tt).disconnect;return{disconnect:function(){lt()}}},n.registerMutableSourceForHydration=function(ie,de){var Oe=de._getVersion;Oe=Oe(de._source),ie.mutableSourceEagerHydrationData==null?ie.mutableSourceEagerHydrationData=[de,Oe]:ie.mutableSourceEagerHydrationData.push(de,Oe)},n.runWithPriority=function(ie,de){var Oe=Zo;try{return Zo=ie,de()}finally{Zo=Oe}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(ie,de,Oe,tt){var lt=de.current,Ot=lp(),Ys=U1(lt);return Oe=L6(Oe),de.context===null?de.context=Oe:de.pendingContext=Oe,de=Od(Ot,Ys),de.payload={element:ie},tt=tt===void 0?null:tt,tt!==null&&(de.callback=tt),ie=ad(lt,de,Ys),ie!==null&&(zx(ie,lt,Ys,Ot),Ph(ie,lt,Ys)),Ys},n};LGt.exports=ocn;var lcn=LGt.exports;const ccn=ru(lcn);var RGt={exports:{}},HB={};/** * @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. */HB.ConcurrentRoot=1;HB.ContinuousEventPriority=4;HB.DefaultEventPriority=16;HB.DiscreteEventPriority=1;HB.IdleEventPriority=536870912;HB.LegacyRoot=0;RGt.exports=HB;var DGt=RGt.exports;const nwt={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let rwt=!1,awt=!1;const vrt=".react-konva-event",dcn=`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 `,ucn=`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 `,hcn={};function J6e(s,t,n=hcn){if(!rwt&&"zIndex"in t&&(console.warn(ucn),rwt=!0),!awt&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(dcn),awt=!0)}for(var i in n)if(!nwt[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(!nwt[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),y6(s));for(var c in f)s.on(c+vrt,f[c])}function y6(s){if(!Qo.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const FGt={},mcn={};X7.Node.prototype._applyProps=J6e;function fcn(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),y6(s)}function pcn(s,t,n){let r=X7[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=X7.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 J6e(c,i),c}function gcn(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function xcn(s,t,n){return!1}function ycn(s){return s}function vcn(){return null}function bcn(){return null}function _cn(s,t,n,r){return mcn}function wcn(){}function jcn(s){}function Ncn(s,t){return!1}function kcn(){return FGt}function Scn(){return FGt}const Ccn=setTimeout,Acn=clearTimeout,Ecn=-1;function Tcn(s,t){return!1}const Mcn=!1,Pcn=!0,Icn=!0;function Lcn(s,t){t.parent===s?t.moveToTop():s.add(t),y6(s)}function Rcn(s,t){t.parent===s?t.moveToTop():s.add(t),y6(s)}function OGt(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),y6(s)}function Dcn(s,t,n){OGt(s,t,n)}function Fcn(s,t){t.destroy(),t.off(vrt),y6(s)}function Ocn(s,t){t.destroy(),t.off(vrt),y6(s)}function zcn(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function Bcn(s,t,n){}function $cn(s,t,n,r,a){J6e(s,a,r)}function Ucn(s){s.hide(),y6(s)}function qcn(s){}function Vcn(s,t){(t.visible==null||t.visible)&&s.show()}function Hcn(s,t){}function Gcn(s){}function Wcn(){}const Kcn=()=>DGt.DefaultEventPriority,Ycn=Object.freeze(Object.defineProperty({__proto__:null,appendChild:Lcn,appendChildToContainer:Rcn,appendInitialChild:fcn,cancelTimeout:Acn,clearContainer:Gcn,commitMount:Bcn,commitTextUpdate:zcn,commitUpdate:$cn,createInstance:pcn,createTextInstance:gcn,detachDeletedInstance:Wcn,finalizeInitialChildren:xcn,getChildHostContext:Scn,getCurrentEventPriority:Kcn,getPublicInstance:ycn,getRootHostContext:kcn,hideInstance:Ucn,hideTextInstance:qcn,idlePriority:XQ.unstable_IdlePriority,insertBefore:OGt,insertInContainerBefore:Dcn,isPrimaryRenderer:Mcn,noTimeout:Ecn,now:XQ.unstable_now,prepareForCommit:vcn,preparePortalMount:bcn,prepareUpdate:_cn,removeChild:Fcn,removeChildFromContainer:Ocn,resetAfterCommit:wcn,resetTextContent:jcn,run:XQ.unstable_runWithPriority,scheduleTimeout:Ccn,shouldDeprioritizeSubtree:Ncn,shouldSetTextContent:Tcn,supportsMutation:Icn,unhideInstance:Vcn,unhideTextInstance:Hcn,warnsIfNotActing:Pcn},Symbol.toStringTag,{value:"Module"}));var Zcn=Object.defineProperty,Xcn=Object.defineProperties,Qcn=Object.getOwnPropertyDescriptors,iwt=Object.getOwnPropertySymbols,Jcn=Object.prototype.hasOwnProperty,edn=Object.prototype.propertyIsEnumerable,owt=(s,t,n)=>t in s?Zcn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,lwt=(s,t)=>{for(var n in t||(t={}))Jcn.call(t,n)&&owt(s,n,t[n]);if(iwt)for(var n of iwt(t))edn.call(t,n)&&owt(s,n,t[n]);return s},tdn=(s,t)=>Xcn(s,Qcn(t)),cwt,dwt;typeof window<"u"&&((cwt=window.document)!=null&&cwt.createElement||((dwt=window.navigator)==null?void 0:dwt.product)==="ReactNative")?j.useLayoutEffect:j.useEffect;function zGt(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=zGt(r,t,n);if(a)return a;r=r.sibling}}function BGt(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const uwt=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=uwt;return}return uwt.apply(this,arguments)};const brt=BGt(j.createContext(null));class $Gt extends j.Component{render(){return j.createElement(brt.Provider,{value:this._reactInternals},this.props.children)}}function sdn(){const s=j.useContext(brt);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=zGt(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 ndn(){const s=sdn(),[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!==brt&&!t.has(a)&&t.set(a,j.useContext(BGt(a)))}n=n.return}return t}function rdn(){const s=ndn();return j.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>j.createElement(t,null,j.createElement(n.Provider,tdn(lwt({},r),{value:s.get(n)}))),t=>j.createElement($Gt,lwt({},t))),[s])}function adn(s){const t=Kt.useRef({});return Kt.useLayoutEffect(()=>{t.current=s}),Kt.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const idn=s=>{const t=Kt.useRef(null),n=Kt.useRef(null),r=Kt.useRef(null),a=adn(s),i=rdn(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return Kt.useLayoutEffect(()=>(n.current=new X7.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=xQ.createContainer(n.current,DGt.LegacyRoot,!1,null),xQ.updateContainer(Kt.createElement(i,{},s.children),r.current),()=>{X7.isBrowser&&(l(null),xQ.updateContainer(null,r.current,null),n.current.destroy())}),[]),Kt.useLayoutEffect(()=>{l(n.current),J6e(n.current,s,a),xQ.updateContainer(Kt.createElement(i,{},s.children),r.current,null)}),Kt.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})},odn="Layer",xI="Group",g5="Rect",eq="Image",C$="Text",Jkr="Transformer",xQ=ccn(Ycn);xQ.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:Kt.version,rendererPackageName:"react-konva"});const ldn=Kt.forwardRef((s,t)=>Kt.createElement($Gt,{},Kt.createElement(idn,{...s,forwardedRef:t})));function cdn({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=Din(n),v=(o==null?void 0:o.naturalWidth)??1080,y=(o==null?void 0:o.naturalHeight)??1080,b=j.useMemo(()=>Math.min(1,a/v),[v,a]),w=v*b,S=y*b,A=(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(ldn,{ref:W=>{l.current=W,i&&(i.current=W)},width:w,height:S,scaleX:b,scaleY:b,children:e.jsxs(odn,{children:[o&&e.jsx(eq,{image:o,width:v,height:y,listening:!1}),!o&&e.jsx(g5,{x:0,y:0,width:v,height:y,fill:"#e2e8f0"}),e.jsx(ddn,{style:x,canvasW:v,canvasH:y,brandColor:A,accentColor:E,name:I,phone:P,email:R,tagline:D,headshot:d,logo:h,hidden:O,has:U})]})})})}function ddn({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":Fin(r),x=g==="#ffffff"?"rgba(255,255,255,0.78)":"rgba(15,23,42,0.7)";if(s.position==="bottom"||s.position==="top"){const v=s.position==="bottom"?n-m:0;return e.jsxs(xI,{children:[e.jsx(g5,{x:0,y:v,width:t,height:m,fill:r}),e.jsx(g5,{x:0,y:s.position==="bottom"?v:m-4,width:t,height:4,fill:a}),e.jsx(Pde,{x:f,y:v+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 v=t*.42,y=m,b=t-v-n*.025,w=n-y-n*.025;return e.jsxs(xI,{children:[e.jsx(g5,{x:b,y:w,width:v,height:y,fill:r,cornerRadius:y*.12,opacity:.92}),e.jsx(g5,{x:b,y:w+y-4,width:v,height:4,fill:a,cornerRadius:2}),e.jsx(Pde,{x:b+f,y:w+f,width:v-f*2,height:y-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 v=Math.max(t*.22,Math.min(t*.3,260)),y=v*.12;return e.jsxs(xI,{children:[e.jsx(g5,{x:t-v,y:0,width:v,height:n,fill:r}),e.jsx(g5,{x:t-v,y:0,width:4,height:n,fill:a}),e.jsx(Pde,{x:t-v+y,y:n*.08,width:v-y*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:v})]})}return s.position==="letterbox"?e.jsxs(xI,{children:[e.jsx(g5,{x:0,y:0,width:t,height:m,fill:"#0a0a0a"}),e.jsx(g5,{x:0,y:n-m,width:t,height:m,fill:"#0a0a0a"}),e.jsx(g5,{x:0,y:n-m,width:t,height:3,fill:a}),e.jsx(Pde,{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(eq,{image:u,x:t-f-m*.7,y:f,height:m-f*2,width:m*.7})]}):null}function Pde({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),Z=Math.max(11,W*.085),X=W*.08,ae=W*.35;let le=t;const re=le;le+=V+X;const te=le,J=l.length>12?2:1;le+=G*1.15*J+X*.5;const ce=le;m("phone")&&o&&(le+=Z*1.3+X*.4);const ve=le;m("email")&&c&&(le+=Z*1.3+X*.4);const fe=le+X*.5;return e.jsxs(xI,{children:[m("headshot")&&u&&e.jsx(xI,{clipFunc:f?ue=>{ue.beginPath(),ue.arc(s+n/2,re+V/2,V/2,0,Math.PI*2),ue.closePath()}:void 0,children:e.jsx(eq,{image:u,x:s+(n-V)/2,y:re,width:V,height:V})}),m("name")&&l&&e.jsx(C$,{text:l,x:s,y:te,width:n,align:"center",fontSize:G,fontStyle:"bold",fill:a}),m("phone")&&o&&e.jsx(C$,{text:o,x:s,y:ce,width:n,align:"center",fontSize:Z,fill:i}),m("email")&&c&&e.jsx(C$,{text:c,x:s,y:ve,width:n,align:"center",fontSize:Z,fill:i,ellipsis:!0,wrap:"none"}),m("logo")&&h&&e.jsx(eq,{image:h,x:s,y:fe,width:n,height:ae})]})}const v=r*.95,y=u&&m("headshot")?s+v+r*.18:s,b=n-(y-s)-(h&&m("logo")?r*1.6:0),w=Math.max(20,r*.34),S=Math.max(13,r*.22),A=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)*A;let U=t+(r-D)/2;return e.jsxs(xI,{children:[m("headshot")&&u&&e.jsx(xI,{clipFunc:f?W=>{W.beginPath(),W.arc(s+v/2,t+v/2,v/2,0,Math.PI*2),W.closePath()}:void 0,children:e.jsx(eq,{image:u,x:s,y:t+(r-v)/2,width:v,height:v})}),m("name")&&l&&e.jsx(C$,{text:l,x:y,y:U,width:b,fontSize:w,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(U+=w+A,null),m("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(C$,{text:d,x:y,y:U,width:b,fontSize:S*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(U+=S*1.1+A,null)]}),I||P?e.jsx(C$,{text:[o,c].filter(Boolean).join(" • "),x:y,y:U,width:b,fontSize:S,fill:i,ellipsis:!0,wrap:"none"}):null,m("logo")&&h&&e.jsx(eq,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function udn(){const{data:s}=pie(),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),[v,y]=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&&y(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),A=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",Z=atob(V),X=new Uint8Array(Z.length);for(let le=0;le{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}),Z=`${((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),ne.success('Long-press the image and tap "Save to Photos"');else{const le=document.createElement("a");le.href=ae,le.download=Z,document.body.appendChild(le),le.click(),le.remove(),ne.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(ae),6e4)}catch(W){ne.error(W.message||"Export failed")}finally{g(!1)}}},D=async()=>{if(i.length){g(!0);try{const U=new zHt,W=i.length,V=o;for(let X=0;XsetTimeout(J,600)),!S.current)continue;const ae=S.current,re=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`,re,{base64:!0})}c(V);const G=await U.generateAsync({type:"blob"}),Z=document.createElement("a");Z.href=URL.createObjectURL(G),Z.download=`branded-images-${Date.now()}.zip`,Z.click(),URL.revokeObjectURL(Z.href),ne.success(`${W} images exported`)}catch(U){ne.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(Dl,{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(br,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Va,{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(br,{to:"/marketing-studio/brand-kit",children:[e.jsx(yd,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(je,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(Le,{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(br,{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(je,{className:"overflow-hidden",children:e.jsxs(Le,{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(cdn,{imageUrl:O.url,preset:a,barStyleId:d,overrides:h,maxDisplayWidth:v,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(),A(U.dataTransfer.files)},children:[e.jsx(Hc,{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=>A(U.target.files)})]})}),i.length>0&&e.jsx(je,{className:"overflow-hidden",children:e.jsx(Le,{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(mr,{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(cn,{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(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ji,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs($,{onClick:D,disabled:f,children:[f?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ji,{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(je,{className:"overflow-hidden",children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-base",children:"Brand preset"})}),e.jsx(Le,{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(je,{className:"overflow-hidden",children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-base",children:"Bar style"})}),e.jsx(Le,{children:e.jsx(Oin,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(je,{className:"overflow-hidden",children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-base",children:"Tweak this design"})}),e.jsx(Le,{children:e.jsxs(pa,{defaultValue:"text",children:[e.jsxs(ga,{className:"grid grid-cols-2 w-full",children:[e.jsx(Xt,{value:"text",children:"Text"}),e.jsx(Xt,{value:"colors",children:"Colors"})]}),e.jsxs(Qt,{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(Qt,{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 hdn(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 mdn=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function cL(s){const t=[];for(let n=0,r=s.length;nhj||s.height>hj)&&(s.width>hj&&s.height>hj?s.width>s.height?(s.height*=hj/s.width,s.width=hj):(s.width*=hj/s.height,s.height=hj):s.width>hj?(s.height*=hj/s.width,s.width=hj):(s.width*=hj/s.height,s.height=hj))}function zTe(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 ydn(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function vdn(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),ydn(a)}const Mw=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||Mw(n,t)};function bdn(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function _dn(s,t){return UGt(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function wdn(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?bdn(n):_dn(n,r);return document.createTextNode(`${a}{${i}}`)}function hwt(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=mdn();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(wdn(l,n,a,r)),t.appendChild(o)}function jdn(s,t,n){hwt(s,t,":before",n),hwt(s,t,":after",n)}const mwt="application/font-woff",fwt="image/jpeg",Ndn={woff:mwt,woff2:mwt,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:fwt,jpeg:fwt,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function kdn(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function _rt(s){const t=kdn(s).toLowerCase();return Ndn[t]||""}function Sdn(s){return s.split(/,/)[1]}function RWe(s){return s.search(/^(data:)/)!==-1}function Cdn(s,t){return`data:${t};base64,${s}`}async function VGt(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 VBe={};function Adn(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 wrt(s,t,n){const r=Adn(s,t,n.includeQueryParams);if(VBe[r]!=null)return VBe[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await VGt(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),Sdn(o)));a=Cdn(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 VBe[r]=a,a}async function Edn(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):zTe(t)}async function Tdn(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 zTe(o)}const n=s.poster,r=_rt(n),a=await wrt(n,r,t);return zTe(a)}async function Mdn(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await eRe(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function Pdn(s,t){return Mw(s,HTMLCanvasElement)?Edn(s):Mw(s,HTMLVideoElement)?Tdn(s,t):Mw(s,HTMLIFrameElement)?Mdn(s,t):s.cloneNode(HGt(s))}const Idn=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",HGt=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function Ldn(s,t,n){var r,a;if(HGt(t))return t;let i=[];return Idn(s)&&s.assignedNodes?i=cL(s.assignedNodes()):Mw(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=cL(s.contentDocument.body.childNodes):i=cL(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||Mw(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>eRe(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function Rdn(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):UGt(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`),Mw(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 Ddn(s,t){Mw(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),Mw(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function Fdn(s,t){if(Mw(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function Odn(s,t,n){return Mw(t,Element)&&(Rdn(s,t,n),jdn(s,t,n),Ddn(s,t),Fdn(s,t)),t}async function zdn(s,t){const n=s.querySelectorAll?s.querySelectorAll("use"):[];if(n.length===0)return s;const r={};for(let i=0;iPdn(r,t)).then(r=>Ldn(s,r,t)).then(r=>Odn(s,r,t)).then(r=>zdn(r,t))}const GGt=/url\((['"]?)([^'"]+?)\1\)/g,Bdn=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,$dn=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Udn(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function qdn(s){const t=[];return s.replace(GGt,(n,r,a)=>(t.push(a),n)),t.filter(n=>!RWe(n))}async function Vdn(s,t,n,r,a){try{const i=n?hdn(t,n):t,l=_rt(t);let o;return a||(o=await wrt(i,l,r)),s.replace(Udn(t),`$1${o}$3`)}catch{}return s}function Hdn(s,{preferredFontFormat:t}){return t?s.replace($dn,n=>{for(;;){const[r,,a]=Bdn.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function WGt(s){return s.search(GGt)!==-1}async function KGt(s,t,n){if(!WGt(s))return s;const r=Hdn(s,n);return qdn(r).reduce((i,l)=>i.then(o=>Vdn(o,l,t,n)),Promise.resolve(r))}async function E$(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await KGt(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function Gdn(s,t){await E$("background",s,t)||await E$("background-image",s,t),await E$("mask",s,t)||await E$("-webkit-mask",s,t)||await E$("mask-image",s,t)||await E$("-webkit-mask-image",s,t)}async function Wdn(s,t){const n=Mw(s,HTMLImageElement);if(!(n&&!RWe(s.src))&&!(Mw(s,SVGImageElement)&&!RWe(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await wrt(r,_rt(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 Kdn(s,t){const r=cL(s.childNodes).map(a=>YGt(a,t));await Promise.all(r).then(()=>s)}async function YGt(s,t){Mw(s,Element)&&(await Gdn(s,t),await Wdn(s,t),await Kdn(s,t))}function Ydn(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 pwt={};async function gwt(s){let t=pwt[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},pwt[s]=t,t}async function xwt(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),VGt(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function ywt(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 Zdn(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{cL(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=gwt(c).then(u=>xwt(u,t)).then(u=>ywt(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(gwt(a.href).then(o=>xwt(o,t)).then(o=>ywt(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{cL(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function Xdn(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>WGt(t.style.getPropertyValue("src")))}async function Qdn(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=cL(s.ownerDocument.styleSheets),r=await Zdn(n,t);return Xdn(r)}function ZGt(s){return s.trim().replace(/["']/g,"")}function Jdn(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(ZGt(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function eun(s,t){const n=await Qdn(s,t),r=Jdn(s);return(await Promise.all(n.filter(i=>r.has(ZGt(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return KGt(i.cssText,l,t)}))).join(` `)}async function tun(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await eun(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 XGt(s,t={}){const{width:n,height:r}=qGt(s,t),a=await eRe(s,t,!0);return await tun(a,t),await YGt(a,t),Ydn(a,t),await vdn(a,n,r)}async function QGt(s,t={}){const{width:n,height:r}=qGt(s,t),a=await XGt(s,t),i=await zTe(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||xdn(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 RG(s,t={}){return(await QGt(s,t)).toDataURL()}const JGt=Object.freeze(Object.defineProperty({__proto__:null,toCanvas:QGt,toPng:RG,toSvg:XGt},Symbol.toStringTag,{value:"Module"})),DG=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),tRe={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},yI={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},sun=({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})]})]}),jrt=Kt.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=tRe[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:DG(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",DG(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(sun,{branding:r,dim:l})]})]})]})});jrt.displayName="LuxuryDarkTemplate";const nun=({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})]})]}),Nrt=Kt.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=tRe[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:DG(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(nun,{branding:r,dim:l,accentColor:m})]})]})});Nrt.displayName="ModernCleanTemplate";const run=({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})]})]}),krt=Kt.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=tRe[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:DG(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(run,{branding:r,dim:l})]})]})]})});krt.displayName="BoldColorfulTemplate";const aun=({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})]})]}),Srt=Kt.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=tRe[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:DG(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",DG(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(aun,{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"}})]})]})})});Srt.displayName="EditorialTemplate";const iun=[{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:"📉"}],vwt=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(Ef,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(Ef,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(Zp,{className:"h-4 w-4"})}],oun=[{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:"📰"}],bwt={"luxury-dark":jrt,"modern-clean":Nrt,"bold-colorful":krt,editorial:Srt},HBe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function lun(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([]),[v,y]=j.useState(null),[b,w]=j.useState(0),[S,A]=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([]),[Z,X]=j.useState("search"),ae=j.useRef({}),{data:le=[],isLoading:re}=st({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:Ee,error:ke}=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(ke)throw ke;return(Ee||[]).map(Ie=>{const Fe=(Ie.listing_photos||[]).slice().sort((Be,Se)=>(Se.is_primary?1:0)-(Be.is_primary?1:0)||(Be.sort_order??0)-(Se.sort_order??0)).map(Be=>Be.photo_url).filter(Boolean),Ne=String(Ie.status||"");return{mlsNumber:Ie.id,address:Ie.property_address||"",city:Ie.city||"",state:Ie.state||"",zip:"",price:Number(Ie.price||0),status:Ne,bedrooms:Number(Ie.bedrooms||0),bathrooms:Number(Ie.bathrooms||0),sqft:Number(Ie.square_footage||0),lotSize:"",yearBuilt:Ie.year_built??null,propertyType:Ie.property_type||"",description:Ie.description||"",photos:Fe,listDate:Ie.created_at,soldDate:Ne.toLowerCase().includes("sold")?Ie.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:ke}=await q.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(ke)throw ke;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&&ne.info("No listings found. Try a different search.")}catch(Ee){ne.error(Ee.message||"Search failed")}finally{f(!1)}}},ce=Ee=>{var ke;y(Ee),w(0),X("customize"),Ee.soldDate||(ke=Ee.status)!=null&&ke.toLowerCase().includes("sold")?A("just-sold"):A("just-listed")},ve=Ee=>I(ke=>ke.includes(Ee)?ke.filter(Ie=>Ie!==Ee):[...ke,Ee]),fe=v?{listing:v,postType:S,format:"instagram-square",branding:te,selectedPhotoIndex:b}:null,ue=j.useCallback(async()=>{if(!(!v||E.length===0)){W(!0),G([]),X("generate");try{await new Promise(ke=>setTimeout(ke,600));const Ee=[];for(const ke of E){const Ie=`${P}-${ke}`,Fe=ae.current[Ie];if(!Fe)continue;const Ne=yI[ke],Be=await RG(Fe,{width:Ne.width,height:Ne.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ee.push({format:ke,url:Be})}G(Ee),ne.success(`Generated ${Ee.length} design${Ee.length>1?"s":""}!`)}catch(Ee){ne.error(Ee.message||"Generation failed")}finally{W(!1)}}},[v,E,P]),be=(Ee,ke)=>{const Ie=`${((v==null?void 0:v.address)||"listing").replace(/\s+/g,"-")}-${S}-${ke}.png`;try{const Fe=lun(Ee),Ne=URL.createObjectURL(Fe);if(cun)window.open(Ne,"_blank"),ne.message("Long-press the image to save to Photos");else{const Be=document.createElement("a");Be.href=Ne,Be.download=Ie,document.body.appendChild(Be),Be.click(),document.body.removeChild(Be)}setTimeout(()=>URL.revokeObjectURL(Ne),6e4)}catch{const Fe=document.createElement("a");Fe.href=Ee,Fe.download=Ie,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(Dl,{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(br,{to:"/marketing-studio",children:[e.jsx(Va,{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($e,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(wn,{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 ${Z==="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:()=>v&&X("customize"),disabled:!v,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Z==="customize"?"bg-primary text-primary-foreground":v?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(wn,{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 ${Z==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(ji,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),Z==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(pa,{value:l,onValueChange:Ee=>o(Ee),children:e.jsxs(ga,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(Xt,{value:"mine",children:[e.jsx(va,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(Xt,{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:re?e.jsx(je,{children:e.jsx(Le,{className:"py-12 flex items-center justify-center",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):le.length===0?e.jsx(je,{children:e.jsxs(Le,{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(br,{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:[le.length," listing",le.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:le.map((Ee,ke)=>{var Ie;return e.jsx(je,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ce(Ee),children:e.jsx(Le,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(Ie=Ee.photos)!=null&&Ie[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?HBe(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(C4,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(C0,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(qz,{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($e,{variant:"outline",className:"text-[10px]",children:Ee.status})})]})]})})},Ee.mlsNumber||ke)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(je,{className:"overflow-hidden",children:[e.jsxs(St,{children:[e.jsxs(Et,{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(Vn,{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(Le,{className:"space-y-3",children:[e.jsx(pa,{value:u,onValueChange:Ee=>h(Ee),children:e.jsxs(ga,{children:[e.jsxs(Xt,{value:"address",children:[e.jsx(ui,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Xt,{value:"mls",children:[e.jsx(Cp,{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(Ct,{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,ke)=>{var Ie;return e.jsx(je,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ce(Ee),children:e.jsx(Le,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(Ie=Ee.photos)!=null&&Ie[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:HBe(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(C4,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(C0,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(qz,{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($e,{variant:"outline",className:"text-[10px]",children:Ee.mlsNumber}),Ee.status&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:Ee.status})]})]})]})})},Ee.mlsNumber||ke)})})]})]})]}),Z==="customize"&&v&&fe&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(je,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-base",children:"Selected listing"})}),e.jsxs(Le,{className:"space-y-3",children:[v.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:v.photos[b],alt:"",className:"w-full h-full object-cover"})}),v.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(kd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b+1," of ",v.photos.length]}),e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>w(Ee=>Math.min(v.photos.length-1,Ee+1)),disabled:b===v.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:HBe(v.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.city,", ",v.state," ",v.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[v.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),v.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),v.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.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"),y(null)},children:[e.jsx(Sx,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(je,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(wn,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(Vn,{children:"Pick a template, post type, and output format."})]}),e.jsxs(Le,{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(yd,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:oun.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:iun.map(Ee=>e.jsxs("button",{onClick:()=>A(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:vwt.map(Ee=>e.jsxs("button",{onClick:()=>ve(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(jn,{checked:D,onCheckedChange:O})]}),D&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(br,{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*(yI[E[0]||"instagram-square"].height/yI[E[0]||"instagram-square"].width)},children:(()=>{const Ee=bwt[P],ke=E[0]||"instagram-square";return e.jsx(Ee,{...fe,format:ke})})()})})]}),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(Ct,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(wn,{className:"h-5 w-5"})," Generate ",E.length," design",E.length>1?"s":""]})})]})]})]}),Z==="generate"&&e.jsxs("div",{className:"space-y-4",children:[U&&e.jsx(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Ct,{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(Sx,{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,ke)=>{const Ie=vwt.find(Fe=>Fe.value===Ee.format);return e.jsxs(je,{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(Le,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ie==null?void 0:Ie.icon,e.jsx("span",{className:"text-sm font-medium",children:Ie==null?void 0:Ie.label})]}),e.jsx($e,{variant:"outline",className:"text-[10px]",children:Ie==null?void 0:Ie.dimensions})]}),e.jsxs($,{size:"sm",className:"w-full gap-1.5",onClick:()=>be(Ee.url,Ee.format),children:[e.jsx(ji,{className:"h-3.5 w-3.5"})," Download"]})]})]},ke)})})]})]}),Z==="generate"&&v&&fe&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:E.map(Ee=>{const ke=bwt[P],Ie=yI[Ee];return e.jsx("div",{style:{width:Ie.width,height:Ie.height},children:e.jsx(ke,{ref:Fe=>{ae.current[`${P}-${Ee}`]=Fe},...fe,format:Ee})},`${P}-${Ee}`)})})]})})}var uun=Object.defineProperty,hun=(s,t)=>uun(s,"name",{value:t,configurable:!0}),mun="Toggle",eWt=j.forwardRef(hun(function(t,n){const{pressed:r,defaultPressed:a,onPressedChange:i,...l}=t,[o,c]=dy({prop:r,onChange:i,defaultProp:a??!1,caller:mun});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")),tWt=eWt,fun=Object.defineProperty,PL=(s,t)=>fun(s,"name",{value:t,configurable:!0}),xK="ToggleGroup",[sWt,eSr]=ep(xK,[JL]),nWt=JL(),rWt=j.forwardRef(PL(function(t,n){const{type:r,...a}=t;if(r==="single"){const i=a;return e.jsx(pun,{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 \`${xK}\``)},"ToggleGroup")),[aWt,iWt]=sWt(xK),pun=j.forwardRef(PL(function(t,n){const{value:r,defaultValue:a,onValueChange:i=PL(()=>{},"onValueChange"),...l}=t,[o,c]=dy({prop:r,defaultProp:a??"",onChange:i,caller:xK});return e.jsx(aWt,{scope:t.__scopeToggleGroup,type:"single",value:j.useMemo(()=>o?[o]:[],[o]),onItemActivate:c,onItemDeactivate:j.useCallback(()=>c(""),[c]),children:e.jsx(oWt,{...l,ref:n})})},"ToggleGroupImplSingle")),gun=j.forwardRef(PL(function(t,n){const{value:r,defaultValue:a,onValueChange:i=PL(()=>{},"onValueChange"),...l}=t,[o,c]=dy({prop:r,defaultProp:a??[],onChange:i,caller:xK}),d=j.useCallback(h=>c((m=[])=>[...m,h]),[c]),u=j.useCallback(h=>c((m=[])=>m.filter(f=>f!==h)),[c]);return e.jsx(aWt,{scope:t.__scopeToggleGroup,type:"multiple",value:o,onItemActivate:d,onItemDeactivate:u,children:e.jsx(oWt,{...l,ref:n})})},"ToggleGroupImplMultiple")),[xun,yun]=sWt(xK),oWt=j.forwardRef(PL(function(t,n){const{__scopeToggleGroup:r,disabled:a=!1,rovingFocus:i=!0,orientation:l,dir:o,loop:c=!0,...d}=t,u=nWt(r),h=a3(o),m={dir:h,...d};return e.jsx(xun,{scope:r,rovingFocus:i,disabled:a,children:i?e.jsx(uLe,{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")),DWe="ToggleGroupItem",lWt=j.forwardRef(PL(function(t,n){const r=iWt(DWe,t.__scopeToggleGroup),a=yun(DWe,t.__scopeToggleGroup),i=nWt(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(hLe,{asChild:!0,...i,focusable:!o,active:l,ref:d,children:e.jsx(_wt,{...c,ref:n})}):e.jsx(_wt,{...c,ref:n})},"ToggleGroupItem")),_wt=j.forwardRef(PL(function(t,n){const{__scopeToggleGroup:r,value:a,...i}=t,l=iWt(DWe,r),o={role:"radio","aria-checked":t.pressed,"aria-pressed":void 0},c=l.type==="single"?o:void 0;return e.jsx(eWt,{...c,...i,ref:n,onPressedChange:d=>{d?l.onItemActivate(a):l.onItemDeactivate(a)}})},"ToggleGroupItemImpl"));const cWt=AB("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"}}),vun=j.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(tWt,{ref:a,className:Pt(cWt({variant:t,size:n,className:s})),...r}));vun.displayName=tWt.displayName;const dWt=j.createContext({size:"default",variant:"default"}),jV=j.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(rWt,{ref:i,className:Pt("flex items-center justify-center gap-1",s),...a,children:e.jsx(dWt.Provider,{value:{variant:t,size:n},children:r})}));jV.displayName=rWt.displayName;const f7=j.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=j.useContext(dWt);return e.jsx(lWt,{ref:i,className:Pt(cWt({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});f7.displayName=lWt.displayName;const bun=[{id:"meet",label:"Meet Your Agent",icon:sl,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:d2,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:QS,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:gm,description:"Personal philosophy, mantra, or rallying call."}],GBe={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"}},_un=[{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."}],wwt={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 wun(){const{data:s}=Tin(),{data:t}=pie(),[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,...wwt.meet}),o=g=>l(x=>({...x,...g})),c=g=>l(x=>({...x,template:g,...wwt[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 v=await RG(g,{cacheBust:!0,pixelRatio:2,width:g.offsetWidth,height:g.offsetHeight,backgroundColor:"#ffffff"}),y=document.createElement("a");y.href=v,y.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(y),y.click(),y.remove(),ne.success("Downloaded to your device")}catch(v){ne.error((v==null?void 0:v.message)||"Export failed")}finally{g.style.transform=x,h(!1)}},f=GBe[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(Dl,{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(br,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Va,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(wn,{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(br,{to:"/marketing-studio/brand-kit",children:[e.jsx(yd,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs($,{onClick:m,disabled:u,children:[e.jsx(ji,{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(je,{children:e.jsxs(Le,{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:bun.map(g=>{const x=g.icon,v=i.template===g.id;return e.jsxs("button",{onClick:()=>c(g.id),className:`text-left rounded-lg border p-3 transition-all ${v?"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(jV,{type:"single",value:i.style,onValueChange:g=>g&&o({style:g}),className:"grid grid-cols-2 gap-1",children:_un.map(g=>e.jsx(f7,{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(jV,{type:"single",value:i.aspect,onValueChange:g=>g&&o({aspect:g}),className:"grid grid-cols-3 gap-1",children:Object.keys(GBe).map(g=>e.jsx(f7,{value:g,className:"text-xs h-9",children:GBe[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(je,{children:e.jsxs(Le,{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(jV,{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(f7,{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(Nun,{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 Nun({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(kun,{...f}):s.style==="bold"?e.jsx(Sun,{...f}):s.style==="luxury"?e.jsx(Aun,{...f}):e.jsx(Cun,{...f})}function uWt({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 sRe({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((n,r)=>e.jsx(ei,{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(sRe,{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(uWt,{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 Sun(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%, ${Eun(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(sRe,{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(uWt,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function Cun(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(sRe,{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 Aun(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(sRe,{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 Eun(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 Tun=()=>{const{swagId:s}=Wi(),{user:t}=_s(),{toast:n}=Bi(),r=Zt(),{trackEngagement:a}=dK(),[i,l]=j.useState(""),{data:o,isLoading:c}=st({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:y,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{...y,links:w||[]}},enabled:!!s});j.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=st({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:y,error:b}=await q.from("social_swag_likes").select("*").eq("swag_id",s);if(b)throw b;return y},enabled:!!s}),{data:u=[]}=st({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:y,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(y.map(E=>E.user_id))],{data:S}=await q.from("profiles").select("id, name").in("id",w),A=new Map((S==null?void 0:S.map(E=>[E.id,E.name]))||[]);return y.map(E=>({...E,user_name:A.get(E.user_id)||"Unknown User"}))},enabled:!!s}),h=mt({mutationFn:async y=>{const{error:b}=await q.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:y});if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),n({title:"Comment added!"})},onError:y=>{n({title:"Error adding comment",description:y.message,variant:"destructive"})}}),m=mt({mutationFn:async y=>{const{error:b}=await q.from("social_swag_comments").delete().eq("id",y);if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),n({title:"Comment deleted"})}}),f=mt({mutationFn:async()=>{const y=d.find(b=>b.user_id===(t==null?void 0:t.id));if(y){const{error:b}=await q.from("social_swag_likes").delete().eq("id",y.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(y=>y.user_id===(t==null?void 0:t.id)),x=y=>y.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),v=y=>{y.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(br,{to:"/social-swag",children:[e.jsx(Va,{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(mK,{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($y,{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(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Sd,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(y=>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(y.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:y.title}),e.jsx(Ir,{className:"h-4 w-4 text-muted-foreground"})]},y.id))})]})}),e.jsx(Vc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ah,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:v,className:"flex gap-2",children:[e.jsx(Rs,{placeholder:"Add a comment...",value:i,onChange:y=>l(y.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(Zr,{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(je,{children:e.jsx(Le,{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(y=>e.jsx(je,{children:e.jsx(Le,{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(y.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:y.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:hu(new Date(y.created_at),{addSuffix:!0})}),y.user_id===(t==null?void 0:t.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>m.mutate(y.id),children:e.jsx(qn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:y.content})]})]})})},y.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(Sd,{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(br,{to:"/social-swag",children:"Back to Social Swag"})})]})})},Mun=({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(qI,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(y1,{open:i,onOpenChange:l,children:[e.jsx(v1,{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(wl,{className:"h-4 w-4"}):e.jsx(Di,{className:"h-4 w-4"})]})}),e.jsx(b1,{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(y1,{open:o,onOpenChange:c,children:[e.jsx(v1,{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(jc,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(wl,{className:"h-4 w-4"}):e.jsx(Di,{className:"h-4 w-4"})]})}),e.jsx(b1,{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(y1,{open:d,onOpenChange:u,children:[e.jsx(v1,{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(Yn,{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(wl,{className:"h-4 w-4"}):e.jsx(Di,{className:"h-4 w-4"})]})}),e.jsx(b1,{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(Ii,{src:m.avatarUrl}),e.jsx(za,{className:"text-xs",children:h(m.name)})]}),e.jsx(Dg,{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))})]})]})})})},Pun=({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(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(wl,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(Cu,{className:"w-56 bg-background border",children:[e.jsxs(ja,{onClick:()=>r("all"),children:[e.jsx(qI,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(P0,{}),e.jsx(_L,{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(P0,{}),e.jsxs(_L,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(jc,{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(Vy,{open:i,onOpenChange:l,children:[e.jsx(Tae,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(Yn,{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(uy,{children:[e.jsx(I0,{children:e.jsxs(L0,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(go,{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(Ii,{src:d.avatarUrl}),e.jsx(za,{children:o(d.name)})]}),e.jsx(Dg,{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 Iun=Object.defineProperty,IL=(s,t)=>Iun(s,"name",{value:t,configurable:!0}),WBe,Crt="HoverCard",[hWt,tSr]=ep(Crt,[n3]),Art=n3(),[Lun,Ert]=hWt(Crt),Run=IL(s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=Art(t),d=j.useRef(0),u=j.useRef(0),h=j.useRef(!1),m=j.useRef(!1),[f,g]=dy({prop:r,defaultProp:a??!1,onChange:i,caller:Crt}),x=j.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>g(!0),l)},[l,g]),v=j.useCallback(()=>{clearTimeout(d.current),!h.current&&!m.current&&(u.current=window.setTimeout(()=>g(!1),o))},[o,g]),y=j.useCallback(()=>g(!1),[g]);return j.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(Lun,{scope:t,open:f,onOpenChange:g,onOpen:x,onClose:v,onDismiss:y,hasSelectionRef:h,isPointerDownOnContentRef:m,children:e.jsx(bae,{...c,children:n})})},"HoverCard"),Dun="HoverCardTrigger",Fun=j.forwardRef(IL(function(t,n){const{__scopeHoverCard:r,...a}=t,i=Ert(Dun,r),l=Art(r);return e.jsx(_ae,{asChild:!0,...l,children:e.jsx(Ei.a,{"data-state":i.open?"open":"closed",...a,ref:n,onPointerEnter:Ra(t.onPointerEnter,Sse(i.onOpen)),onPointerLeave:Ra(t.onPointerLeave,Sse(i.onClose)),onFocus:Ra(t.onFocus,i.onOpen),onBlur:Ra(t.onBlur,i.onClose),onTouchStart:Ra(t.onTouchStart,o=>o.preventDefault())})})},"HoverCardTrigger")),Oun="HoverCardPortal",[sSr,zun]=hWt(Oun,{forceMount:void 0}),FWe="HoverCardContent",Bun=j.forwardRef(IL(function(t,n){const r=zun(FWe,t.__scopeHoverCard),{forceMount:a=r.forceMount,...i}=t,l=Ert(FWe,t.__scopeHoverCard);return e.jsx(my,{present:a||l.open,children:e.jsx($un,{"data-state":l.open?"open":"closed",...i,onPointerEnter:Ra(t.onPointerEnter,Sse(l.onOpen)),onPointerLeave:Ra(t.onPointerLeave,Sse(l.onClose)),ref:n})})},"HoverCardContent")),$un=j.forwardRef(IL(function(t,n){const{__scopeHoverCard:r,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:l,onInteractOutside:o,...c}=t,d=Ert(FWe,r),u=Art(r),h=j.useRef(null),m=Vo(n,h),[f,g]=j.useState(!1);return j.useEffect(()=>{if(f){const x=document.body;return WBe=x.style.userSelect||x.style.webkitUserSelect,x.style.userSelect="none",x.style.webkitUserSelect="none",()=>{x.style.userSelect=WBe,x.style.webkitUserSelect=WBe}}},[f]),j.useEffect(()=>{if(h.current){const x=IL(()=>{g(!1),d.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var y;((y=document.getSelection())==null?void 0:y.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&&mWt(h.current).forEach(v=>v.setAttribute("tabindex","-1"))}),e.jsx(CB,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:o,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:Ra(l,x=>{x.preventDefault()}),onDismiss:d.onDismiss,children:e.jsx(wae,{...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 Sse(s){return t=>t.pointerType==="touch"?void 0:s()}IL(Sse,"excludeTouch");function mWt(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:IL(r=>r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP,"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}IL(mWt,"getTabbableNodes");var Uun=Run,qun=Fun,fWt=Bun;const Vun=Uun,Hun=qun,pWt=j.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(fWt,{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}));pWt.displayName=fWt.displayName;const Gun=[{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"}],Wun=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),gWt=({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(Vun,{openDelay:200,closeDelay:100,children:[e.jsx(Hun,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(pWt,{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=Gun.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(Ii,{src:l.user_avatar||void 0}),e.jsx(za,{className:"text-[10px]",children:Wun(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 Kun({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(Os,{open:n,onOpenChange:r,children:e.jsxs(Fs,{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(mr,{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(kd,{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(hV,{className:"h-5 w-5"}):e.jsx(JI,{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 Ide=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],Yun=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=Zt(),[a,i]=j.useState(!1),l=t.find(h=>h.user_id===n),o=mt({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(gWt,{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=Ide.find(f=>f.type===h))==null?void 0:m.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(Gd,{open:a,onOpenChange:i,children:[e.jsx(Wd,{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=Ide.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=Ide.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(Dd,{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:Ide.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 Trt({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(br,{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 BTe({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"),[v,y]=j.useState(""),[b,w]=j.useState(null),[S,A]=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,ke)=>{J.includes(`@${ke}`)&&ue.push(Ee)}),[...new Set(ue)]}const ce=/@\[([^\]]+)\]\(([^)]+)\)/g,ve=[];let fe;for(;(fe=ce.exec(J))!==null;)ve.push(fe[2]);return[...new Set(ve)]},O=J=>{if(c==="plain"){const ue=[];return R.current.forEach((Ee,ke)=>{J.includes(`#${ke}`)&&ue.push(Ee)}),[...new Set(ue)]}const ce=/#\[([^\]]+)\]\(([^)]+)\)/g,ve=[];let fe;for(;(fe=ce.exec(J))!==null;)ve.push(fe[2]);return[...new Set(ve)]};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}=st({queryKey:["mention-users",v],queryFn:async()=>{const J=q.from("profiles").select("id, name").limit(8),ce=v.length>=1?J.ilike("name",`%${v}%`):J.order("name"),{data:ve,error:fe}=await ce;if(fe)throw fe;const ue=ve.map(Ee=>Ee.id),be=await AOt(ue);return ve.map(Ee=>({id:Ee.id,name:Ee.name||"Unknown",avatar_url:be.get(Ee.id)}))},enabled:m&&g==="user",staleTime:3e4}),{data:V=[],isLoading:G}=st({queryKey:["mention-templates",v],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);v.length>=1&&(J=J.ilike("name",`%${v}%`));const{data:ce,error:ve}=await J;if(ve)throw ve;return ce||[]},enabled:m&&g==="template"&&d,staleTime:3e4}),Z=g==="user"?W:G,X=g==="user"?U:V,ae=J=>J.split(" ").map(ce=>ce[0]).join("").toUpperCase().slice(0,2),le=J=>{const ce=J.target.value,ve=J.target.selectionStart;t(ce);const fe=ce.substring(0,ve),ue=fe.lastIndexOf("@"),be=d?fe.lastIndexOf("#"):-1;let Ee=-1,ke="user";if(ue>be?(Ee=ue,ke="user"):be>ue&&d&&(Ee=be,ke="template"),Ee!==-1){const Ie=fe.substring(Ee+1),Fe=Ie.includes(" "),Ne=Ie.includes(` `);if(!Fe&&!Ne&&Ie.length<=30){w(Ee),y(Ie),x(ke),f(!0),A(0);return}}f(!1),w(null)},re=J=>{if(b===null)return;const ce=s.substring(0,b),ve=s.substring(b+v.length+1),fe=g==="user"?"@":"#",ue=c==="plain"?`${fe}${J.name} `:`${fe}[${J.name}](${J.id}) `;c==="plain"&&(g==="user"?P.current.set(J.name,J.id):R.current.set(J.name,J.id));const be=ce+ue+ve;t(be),f(!1),w(null),y(""),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(),A(ce=>(ce+1)%X.length);break;case"ArrowUp":J.preventDefault(),A(ce=>(ce-1+X.length)%X.length);break;case"Enter":X[S]&&(J.preventDefault(),re(X[S]));break;case"Escape":J.preventDefault(),f(!1);break;case"Tab":X[S]&&(J.preventDefault(),re(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 ve=ce.getBoundingClientRect();I({top:ve.bottom+4,left:ve.left,width:ve.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:le,onKeyDown:J=>{te(J),J.defaultPrevented||o==null||o(J)},placeholder:n,className:Pt("resize-none",r),style:{minHeight:a}}),m&&yv.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"}),Z?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:v.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:()=>re(J),onMouseEnter:()=>A(ce),children:g==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(Oa,{className:"h-6 w-6",children:[e.jsx(Ii,{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(yd,{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 Zun(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const jwt=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function xWt({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=Zt(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState([]),g=mt({mutationFn:async({content:b,parentCommentId:w})=>{const{data:S,error:A}=await q.from("community_comments").insert({post_id:t,user_id:n,content:b,parent_comment_id:w}).select("id").single();if(A)throw A;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=mt({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"]})}),v=()=>{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(Ii,{src:s.user_avatar||void 0}),e.jsx(za,{className:"text-xs",children:jwt(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(Trt,{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:hu(new Date(s.created_at),{addSuffix:!0})}),e.jsx(Yun,{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(Kq,{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(Ii,{src:r||void 0}),e.jsx(za,{className:"text-xs",children:jwt((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(BTe,{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:v,disabled:!u.trim()||g.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(Zr,{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(xWt,{comment:b,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},b.id))})]})}const Lde=[{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"}],Xun=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=_s(),{avatarUrl:a}=COt(s==null?void 0:s.id),{onlineUsers:i}=DFt(),{toast:l}=Bi(),o=Zt(),c=j.useRef(null),[d,u]=j.useState("all"),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,v]=j.useState(""),[y,b]=j.useState([]),[w,S]=j.useState([]),[A,E]=j.useState(""),[I,P]=j.useState(!1),[R,D]=j.useState(null),[O,U]=j.useState(""),[W,V]=j.useState(new Set),[G,Z]=j.useState({}),[X,ae]=j.useState({}),[le,re]=j.useState([]),[te,J]=j.useState([]),[ce,ve]=j.useState({open:!1,images:[],index:0});j.useEffect(()=>{if(d.startsWith("group:")){const gt=d.replace("group:","");v(gt),g("")}else d!=="all"?(g(d),v("")):(g(""),v(""))},[d]);const{data:fe=[]}=st({queryKey:["community-categories"],queryFn:async()=>{const{data:gt,error:es}=await q.from("community_categories").select("*").order("sort_order");if(es)throw es;return gt}}),{data:ue=[]}=st({queryKey:["community-private-groups"],queryFn:async()=>{const{data:gt,error:es}=await q.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(es)throw es;return gt}}),be=20,{data:Ee,isLoading:ke,hasNextPage:Ie,fetchNextPage:Fe,isFetchingNextPage:Ne}=Tws({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:gt})=>{var Xn;const es=gt*be,Ht=es+be;let as=q.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(es,Ht);if(d.startsWith("group:")){const wr=d.replace("group:","");as=as.eq("private_group_id",wr)}else d==="all"||(as=as.eq("category_id",d).is("private_group_id",null));const{data:bs,error:Ut}=await as;if(Ut)throw Ut;const Ft=((bs==null?void 0:bs.length)||0)>be,is=(bs||[]).slice(0,be);if(is.length===0)return{posts:[],hasMore:!1,nextPage:gt+1};const jt=is.map(wr=>wr.id),zs=[...new Set(is.filter(wr=>wr.category_id).map(wr=>wr.category_id))].filter(Boolean),[yt,gs,Ss,Ds,Bt]=await Promise.all([zs.length?q.from("community_categories").select("*").in("id",zs):Promise.resolve({data:[]}),q.from("community_post_media").select("*").in("post_id",jt).order("sort_order"),q.from("community_reactions").select("*").in("post_id",jt),q.from("community_comments").select("*").in("post_id",jt).order("created_at",{ascending:!0}),q.from("community_post_resources").select("*").in("post_id",jt)]),zt=yt==null?void 0:yt.data,vs=gs==null?void 0:gs.data,dn=Ss==null?void 0:Ss.data,Ks=Ds==null?void 0:Ds.data,Cn=Bt==null?void 0:Bt.data,Rr=(Ks||[]).map(wr=>wr.id),[ia,Hs]=await Promise.all([Rr.length?q.from("community_comment_reactions").select("*").in("comment_id",Rr):Promise.resolve({data:[]}),(()=>{const wr=(Cn||[]).filter(Bn=>Bn.resource_type==="template").map(Bn=>Bn.resource_id);return wr.length===0?Promise.resolve({data:[]}):q.from("canva_templates").select("id, name, preview_image_url").in("id",wr)})()]),Br=(ia==null?void 0:ia.data)||[],Ur=(Hs==null?void 0:Hs.data)||[],Wn=new Map(Ur.map(wr=>[wr.id,{name:wr.name,preview_image_url:wr.preview_image_url}])),Sn=Array.from(new Set([...is.map(wr=>wr.user_id),...(dn||[]).map(wr=>wr.user_id),...(Ks||[]).map(wr=>wr.user_id),...Br.map(wr=>wr.user_id)])),[Fn,bn]=await Promise.all([Sn.length?q.from("profiles").select("id, name").in("id",Sn):Promise.resolve({data:[]}),AOt(Sn)]),xs=new Map(((Xn=Fn==null?void 0:Fn.data)==null?void 0:Xn.map(wr=>[wr.id,wr.name]))||[]),Tr=new Map((zt||[]).map(wr=>[wr.id,wr])),Lr=wr=>{const Bn=new Map,cr=[];return wr.forEach(Pa=>{Bn.set(Pa.id,{...Pa,user_name:xs.get(Pa.user_id)||"Unknown User",user_avatar:bn.get(Pa.user_id),reactions:Br.filter(ii=>ii.comment_id===Pa.id).map(ii=>({...ii,user_name:xs.get(ii.user_id)||"Unknown User",user_avatar:bn.get(ii.user_id)})),replies:[]})}),wr.forEach(Pa=>{const ii=Bn.get(Pa.id);if(Pa.parent_comment_id&&Bn.has(Pa.parent_comment_id)){const $i=Bn.get(Pa.parent_comment_id);$i.replies=$i.replies||[],$i.replies.push(ii)}else cr.push(ii)}),cr};return{posts:is.map(wr=>{const Bn=(Cn||[]).filter(cr=>cr.post_id===wr.id).map(cr=>{let Pa="",ii=null;if(cr.resource_type==="template"){const $i=Wn.get(cr.resource_id);Pa=($i==null?void 0:$i.name)||"Unknown Template",ii=($i==null?void 0:$i.preview_image_url)||null}return{id:cr.id,resource_type:cr.resource_type,resource_id:cr.resource_id,resource_name:Pa,resource_preview_url:ii}});return{...wr,user_name:xs.get(wr.user_id)||"Unknown User",user_avatar:bn.get(wr.user_id),category:wr.category_id?Tr.get(wr.category_id):null,media:(vs||[]).filter(cr=>cr.post_id===wr.id),reactions:((dn||[]).filter(cr=>cr.post_id===wr.id)||[]).map(cr=>({...cr,user_name:xs.get(cr.user_id)||"Unknown User",user_avatar:bn.get(cr.user_id)})),comments:Lr((Ks||[]).filter(cr=>cr.post_id===wr.id)),resources:Bn}}),hasMore:Ft,nextPage:gt+1}},getNextPageParam:gt=>gt.hasMore?gt.nextPage:void 0}),Be=j.useMemo(()=>(Ee==null?void 0:Ee.pages.flatMap(gt=>gt.posts))??[],[Ee]),Se=mt({mutationFn:async()=>{P(!0);const{data:gt,error:es}=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:A||null}).select().single();if(es)throw es;for(let as=0;as0){const as=le.filter(bs=>bs!==s.id).map(bs=>({post_id:gt.id,mentioned_user_id:bs,mentioned_by_user_id:s.id}));as.length>0&&await q.from("community_post_mentions").insert(as)}const Ht=Zun(h);if(Ht.length>0){const as=Ht.map(bs=>({post_id:gt.id,resource_type:"template",resource_id:bs}));await q.from("community_post_resources").insert(as)}return gt},onSuccess:async gt=>{var es;o.invalidateQueries({queryKey:["community-posts"]}),m(""),re([]),J([]),g(""),v(""),b([]),S([]),E(""),l({title:"Post created!"});try{const Ht=((es=s==null?void 0:s.user_metadata)==null?void 0:es.name)||"Someone",as=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),bs=as.length>50?as.substring(0,50)+"...":as;await q.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${Ht}: ${bs}`,url:"/community"}})}catch(Ht){console.error("Failed to send push notification:",Ht)}},onError:gt=>{l({title:"Error creating post",description:gt.message,variant:"destructive"})},onSettled:()=>P(!1)}),Ae=mt({mutationFn:async({postId:gt,content:es})=>{const{error:Ht}=await q.from("community_posts").update({content:es}).eq("id",gt);if(Ht)throw Ht},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),D(null),U(""),l({title:"Post updated!"})}}),Ce=mt({mutationFn:async gt=>{const{error:es}=await q.from("community_posts").delete().eq("id",gt);if(es)throw es},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),qe=mt({mutationFn:async({postId:gt,isPinned:es})=>{const{error:Ht}=await q.from("community_posts").update({is_pinned:!es,pinned_at:es?null:new Date().toISOString(),pinned_by:es?null:s==null?void 0:s.id}).eq("id",gt);if(Ht)throw Ht},onSuccess:(gt,{isPinned:es})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:es?"Post unpinned":"Post pinned to top"})}}),ze=mt({mutationFn:async({postId:gt,reactionType:es})=>{var as;const Ht=(as=Be.find(bs=>bs.id===gt))==null?void 0:as.reactions.find(bs=>bs.user_id===(s==null?void 0:s.id));Ht?Ht.reaction_type===es?await q.from("community_reactions").delete().eq("id",Ht.id):await q.from("community_reactions").update({reaction_type:es}).eq("id",Ht.id):await q.from("community_reactions").insert({post_id:gt,user_id:s.id,reaction_type:es})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),Ve=mt({mutationFn:async({postId:gt,content:es})=>{const{data:Ht,error:as}=await q.from("community_comments").insert({post_id:gt,user_id:s.id,content:es}).select("id").single();if(as)throw as;const bs=X[gt]||[];if(bs.length>0&&Ht){const Ut=bs.filter(Ft=>Ft!==s.id).map(Ft=>({comment_id:Ht.id,mentioned_user_id:Ft,mentioned_by_user_id:s.id}));Ut.length>0&&await q.from("community_comment_mentions").insert(Ut)}},onSuccess:(gt,{postId:es})=>{o.invalidateQueries({queryKey:["community-posts"]}),Z(Ht=>({...Ht,[es]:""})),ae(Ht=>({...Ht,[es]:[]}))}});mt({mutationFn:async gt=>{const{error:es}=await q.from("community_comments").delete().eq("id",gt);if(es)throw es},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const ht=gt=>{const es=Array.from(gt.target.files||[]);if(es.length+y.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}b(Ht=>[...Ht,...es]),es.forEach(Ht=>{const as=new FileReader;as.onloadend=()=>{S(bs=>[...bs,as.result])},as.readAsDataURL(Ht)})},Qe=gt=>{b(es=>es.filter((Ht,as)=>as!==gt)),S(es=>es.filter((Ht,as)=>as!==gt))},at=gt=>gt.split(" ").map(es=>es[0]).join("").toUpperCase().slice(0,2),rt=gt=>{const es={};return gt.forEach(Ht=>{es[Ht.reaction_type]=(es[Ht.reaction_type]||0)+1}),es},Ke=gt=>{var es;return(es=gt.find(Ht=>Ht.user_id===(s==null?void 0:s.id)))==null?void 0:es.reaction_type},Je=gt=>gt.reduce((es,Ht)=>es+1+(Ht.replies?Je(Ht.replies):0),0),ft=gt=>{if(r)return!0;if(!t||!gt.private_group_id)return!1;const es=ue.find(Ht=>Ht.id===gt.private_group_id);return es!=null&&es.brokerage_id?n.some(Ht=>Ht.id===es.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(Mun,{categories:fe,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(Pun,{categories:fe,privateGroups:ue,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(je,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(Ii,{src:a||void 0}),e.jsx(za,{children:s!=null&&s.email?at(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(BTe,{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:re,onTemplatesChange:J,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),w.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:w.map((gt,es)=>{var Ht;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(Ht=y[es])!=null&&Ht.type.startsWith("video/")?e.jsx("video",{src:gt,className:"w-full h-full object-cover"}):e.jsx("img",{src:gt,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:()=>Qe(es),children:e.jsx(mr,{className:"h-3 w-3"})})]},es)})}),A&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sd,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:A,onChange:gt=>E(gt.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>E(""),children:e.jsx(mr,{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:ht,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>{var gt;return(gt=c.current)==null?void 0:gt.click()},children:[e.jsx(Hc,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>{var gt;return(gt=c.current)==null?void 0:gt.click()},children:[e.jsx(fa,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>E("https://"),children:[e.jsx(Sd,{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:gt=>{gt==="none"?(g(""),v("")):gt.startsWith("group:")?(v(gt.replace("group:","")),g("")):(g(gt),v(""))},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"}),fe.map(gt=>e.jsxs(Ge,{value:gt.id,children:[gt.icon," ",gt.name]},gt.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(gt=>e.jsxs(Ge,{value:`group:${gt.id}`,children:[gt.icon||"🔒"," ",gt.name]},gt.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:fe.map(gt=>e.jsxs(Ge,{value:gt.id,children:[gt.icon," ",gt.name]},gt.id))})]}),e.jsxs($,{size:"sm",onClick:()=>Se.mutate(),disabled:!h.trim()||I,children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),ke?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((gt,es)=>e.jsx(je,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(xn,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(xn,{className:"h-4 w-32"}),e.jsx(xn,{className:"h-4 w-full"}),e.jsx(xn,{className:"h-4 w-3/4"})]})]})})},es))}):Be.length===0?e.jsx(je,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(Ah,{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:[Be.map(gt=>{var es,Ht,as,bs;return e.jsx(je,{children:e.jsxs(Le,{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(Ii,{src:gt.user_avatar||void 0}),e.jsx(za,{children:at(gt.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:gt.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:hu(new Date(gt.created_at),{addSuffix:!0})}),gt.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs($e,{variant:"secondary",className:"text-xs",children:[gt.category.icon," ",gt.category.name]})]})]})]})]}),(gt.user_id===(s==null?void 0:s.id)||ft(gt))&&e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(o_,{className:"h-4 w-4"})})}),e.jsxs(Cu,{align:"end",children:[ft(gt)&>.private_group_id&&e.jsx(ja,{onClick:()=>qe.mutate({postId:gt.id,isPinned:gt.is_pinned}),children:gt.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(VJ,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(IE,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),gt.user_id===(s==null?void 0:s.id)&&e.jsxs(ja,{onClick:()=>{D(gt),U(gt.content)},children:[e.jsx(pi,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ja,{className:"text-destructive",onClick:()=>Ce.mutate(gt.id),children:[e.jsx(qn,{className:"h-4 w-4 mr-2"}),gt.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),gt.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(IE,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(Trt,{content:gt.content})}),gt.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${gt.media.length===1?"grid-cols-1":gt.media.length===2?"grid-cols-2":gt.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:gt.media.slice(0,4).map((Ut,Ft)=>{const is=Ft===3&>.media.length>4,jt=gt.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${gt.media.length===1?"max-h-[500px]":gt.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>ve({open:!0,images:gt.media.map(zs=>({url:zs.media_url,type:zs.media_type==="video"?"video":"image"})),index:Ft}),children:[Ut.media_type==="video"?e.jsx("video",{src:Ut.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:Ut.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"})})})}),is&&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:["+",jt]})})]},Ut.id)})}),gt.link_url&&e.jsxs("a",{href:gt.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[gt.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:gt.link_image,alt:gt.link_title||"Link preview",className:"w-full h-full object-cover",onError:Ut=>{Ut.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:gt.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:gt.link_title}),gt.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:gt.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(gt.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(Sd,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:gt.link_url})]})})]}),gt.reactions.length>0&&e.jsx(gWt,{reactions:gt.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(rt(gt.reactions)).slice(0,3).map(([Ut])=>{var Ft;return e.jsx("span",{className:"text-base",children:(Ft=Lde.find(is=>is.type===Ut))==null?void 0:Ft.emoji},Ut)})}),e.jsx("span",{children:gt.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"flex-1",children:[Ke(gt.reactions)?e.jsx("span",{className:"mr-1",children:(es=Lde.find(Ut=>Ut.type===Ke(gt.reactions)))==null?void 0:es.emoji}):e.jsx($y,{className:"h-4 w-4 mr-1"}),Ke(gt.reactions)?(Ht=Lde.find(Ut=>Ut.type===Ke(gt.reactions)))==null?void 0:Ht.label:"Like"]})}),e.jsx(Dd,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:Lde.map(Ut=>e.jsx("button",{onClick:()=>ze.mutate({postId:gt.id,reactionType:Ut.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:Ut.label,children:Ut.emoji},Ut.type))})})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>V(Ut=>{const Ft=new Set(Ut);return Ft.has(gt.id)?Ft.delete(gt.id):Ft.add(gt.id),Ft}),children:[e.jsx(Ah,{className:"h-4 w-4 mr-1"}),(()=>{const Ut=Je(gt.comments);return Ut>0?`Comment (${Ut})`:"Comment"})()]})]}),W.has(gt.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[gt.comments.map(Ut=>e.jsx(xWt,{comment:Ut,postId:gt.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:ft(gt)},Ut.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Ii,{src:a||void 0}),e.jsx(za,{className:"text-xs",children:at(((as=s.email)==null?void 0:as.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(BTe,{placeholder:"Write a comment... (use @ to mention)",value:G[gt.id]||"",onChange:Ut=>Z(Ft=>({...Ft,[gt.id]:Ut})),onMentionsChange:Ut=>ae(Ft=>({...Ft,[gt.id]:Ut})),mentionFormat:"plain",onKeyDown:Ut=>{var Ft;Ut.defaultPrevented||Ut.key==="Enter"&&!Ut.shiftKey&&((Ft=G[gt.id])!=null&&Ft.trim())&&(Ut.preventDefault(),Ve.mutate({postId:gt.id,content:G[gt.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{var Ut;(Ut=G[gt.id])!=null&&Ut.trim()&&Ve.mutate({postId:gt.id,content:G[gt.id]})},disabled:!((bs=G[gt.id])!=null&&bs.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(Zr,{className:"h-4 w-4"})})]})]})]})]})},gt.id)}),Ie&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx($,{variant:"outline",onClick:()=>Fe(),disabled:Ne,children:Ne?"Loading…":"Load more posts"})})]}),e.jsx(Os,{open:!!R,onOpenChange:()=>D(null),children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{children:"Edit Post"})}),e.jsx(Rs,{value:O,onChange:gt=>U(gt.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(Kun,{images:ce.images,initialIndex:ce.index,open:ce.open,onOpenChange:gt=>ve(es=>({...es,open:gt}))})]})]})})},Qun=50*1024*1024;function yWt({value:s,onChange:t,disabled:n}){const{user:r}=_s(),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/")){ne.error(`${h.name}: only images and videos allowed`);continue}if(h.size>Qun){ne.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){ne.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(bJ,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx($I,{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(mr,{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(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(KI,{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 vWt({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(Ct,{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 T$={open:{label:"Open",icon:ca,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Ah,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Wl,color:"bg-green-500"},closed:{label:"Closed",icon:ju,color:"bg-muted-foreground"}},Nwt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function Jun(){const{user:s}=_s(),t=Zt(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState([]),{data:c=[],isLoading:d}=st({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=[]}=st({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=mt({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([]),ne.success("Reply sent!")},onError:()=>{ne.error("Failed to send reply")}}),m=()=>{!a.trim()&&l.length===0||h.mutate({content:a,attachments:l})};if(n){const f=T$[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(Va,{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($e,{variant:"secondary",children:Nwt[n.category]}),e.jsxs($e,{className:T$[n.status].color,children:[e.jsx(f,{className:"h-3 w-3 mr-1"}),T$[n.status].label]})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Vn,{children:["Created on ",Js(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Le,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Conversation"})}),e.jsxs(Le,{children:[e.jsx(go,{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:Js(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(vWt,{attachments:g.attachments})]},g.id)})})}),n.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(Vc,{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(Zr,{className:"h-4 w-4"})})]}),e.jsx(yWt,{value:l,onChange:o,disabled:h.isPending})]})]})]})]})]})})}return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(je,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(Le,{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(J5,{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(BHe,{trigger:e.jsxs($,{size:"lg",className:"gap-2",children:[e.jsx(cn,{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(BHe,{trigger:e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(cn,{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(je,{className:"border-dashed",children:e.jsxs(Le,{className:"text-center py-12",children:[e.jsx(Ah,{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=T$[f.status].icon;return e.jsx(je,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(f),children:e.jsx(Le,{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($e,{variant:"outline",className:"text-xs",children:Nwt[f.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Js(new Date(f.created_at),"MMM d, yyyy")})]})]}),e.jsxs($e,{className:T$[f.status].color,children:[e.jsx(g,{className:"h-3 w-3 mr-1"}),T$[f.status].label]})]})})},f.id)})})]})})}function ehn({open:s,onOpenChange:t}){return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{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(Ea,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Schedule Agent Onboarding"}),e.jsx(Er,{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 thn({open:s,onOpenChange:t}){const{brokerageId:n}=_s(),[r,a]=j.useState(""),[i,l]=j.useState([]),[o,c]=j.useState(!1),{data:d,isLoading:u}=st({queryKey:["brokerage-agents-for-onboarding",n],queryFn:async()=>{if(!n)return[];const{data:x,error:v}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name",{ascending:!0});if(v)throw v;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(v=>v.includes(x)?v.filter(y=>y!==x):[...v,x])},f=async()=>{if(i.length===0){ne.error("Please select at least one agent");return}c(!0);try{const{data:x,error:v}=await q.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(v)throw v;ne.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(x){console.error("Error sending onboarding link:",x),ne.error(x.message||"Failed to send onboarding link")}finally{c(!1)}},g=x=>{x||(l([]),a("")),t(x)};return e.jsx(Os,{open:s,onOpenChange:g,children:e.jsxs(Fs,{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(Zr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Send Onboarding Link"}),e.jsx(Er,{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(Ct,{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(Yn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(go,{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(v=>v[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(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function shn(){const[s,t]=j.useState(!1),[n,r]=j.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(je,{className:"mb-8",children:[e.jsx(St,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Yn,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Et,{children:"Agent Onboarding"}),e.jsx(Vn,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Le,{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(Ea,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs($,{variant:"outline",onClick:()=>r(!0),className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(ehn,{open:s,onOpenChange:t}),e.jsx(thn,{open:n,onOpenChange:r})]})}function nhn({open:s,onOpenChange:t}){return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{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(By,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Schedule Launch Meeting"}),e.jsx(Er,{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 rhn(){const[s,t]=j.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(je,{className:"mb-8",children:[e.jsx(St,{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(By,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Et,{children:"Launch or ReLaunch Meeting"}),e.jsx(Vn,{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(Le,{children:e.jsxs($,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(By,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(nhn,{open:s,onOpenChange:t})]})}function ahn(){const s=Zn(),[t,n]=j.useState(""),[r,a]=j.useState(null),{data:i,isLoading:l}=st({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:x,error:v}=await q.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(v)throw v;return x}}),{data:o}=st({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:x,error:v}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(v)throw v;return x}}),{data:c}=st({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:x,error:v}=await q.from("brokerage_resource_pdfs").select("resource_id");if(v)throw v;return x}}),{data:d}=st({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:x,error:v}=await q.from("brokerage_resource_videos").select("resource_id");if(v)throw v;return x}}),{data:u}=st({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:x,error:v}=await q.from("brokerage_resource_links").select("resource_id");if(v)throw v;return x}}),h=i==null?void 0:i.filter(x=>{var b;const v=x.title.toLowerCase().includes(t.toLowerCase())||((b=x.description)==null?void 0:b.toLowerCase().includes(t.toLowerCase())),y=!r||x.category_id===r;return v&&y}),m=o==null?void 0:o.filter(x=>i==null?void 0:i.some(v=>v.category_id===x.id)),f=x=>{const v=(c==null?void 0:c.filter(w=>w.resource_id===x).length)||0,y=(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:v,videoCount:y,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(shn,{}),e.jsx(rhn,{}),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($e,{variant:r===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),m.map(x=>e.jsx($e,{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,v)=>e.jsxs(je,{children:[e.jsx(xn,{className:"h-40 w-full"}),e.jsx(St,{children:e.jsx(xn,{className:"h-5 w-3/4"})}),e.jsxs(Le,{children:[e.jsx(xn,{className:"h-4 w-full mb-2"}),e.jsx(xn,{className:"h-4 w-2/3"})]})]},v))}):(h==null?void 0:h.length)===0?e.jsxs(je,{className:"p-12 text-center",children:[e.jsx(wx,{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:v,videoCount:y,linkCount:b}=f(x.id),w=o==null?void 0:o.find(S=>S.id===x.category_id);return e.jsxs(je,{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(wx,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(St,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(Et,{className:"text-lg line-clamp-1",children:x.title}),w&&e.jsx($e,{variant:"secondary",className:"shrink-0 text-xs",children:w.name})]})}),e.jsxs(Le,{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:[v>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Qr,{className:"h-4 w-4"}),v]}),y>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fa,{className:"h-4 w-4"}),y]}),b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Sd,{className:"h-4 w-4"}),b]})]})]})]},x.id)})})]})})}const ihn=()=>{const{resourceId:s}=Wi(),{data:t,isLoading:n}=st({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(br,{to:"/brokerage-resources",children:[e.jsx(Va,{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(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(fa,{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(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Qr,{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(Qr,{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(ji,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Ir,{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(Ir,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(Ir,{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(wx,{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(br,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function ohn(){const{onlineUsers:s,totalOnline:t}=DFt(),{user:n}=_s();return e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs($e,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(Dg,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Le,{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(go,{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(Ii,{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 ",hu(new Date(r.onlineSince),{addSuffix:!1})]})]})]},r.id)})})})})]})}const kwt={users:{label:"Users & Access",sections:[{title:"Member Broadcasts",description:"Email a filtered group of members (paste HTML or write it)",icon:gm,path:"/admin/broadcasts",color:"bg-rose-500/10 text-rose-600"},{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:Yn,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Partnerships",description:"Manage partnership packages, rosters, and upgrade requests",icon:dl,path:"/admin/partnerships",color:"bg-indigo-500/10 text-indigo-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:Qz,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:jv,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:fJ,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:Cp,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:Hd,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:Yn,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:ph,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:lc,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:XN,path:"/admin/blog",color:"bg-amber-500/10 text-amber-600"},{title:"Manage Templates",description:"Upload and organize Canva templates",icon:yd,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Programs",description:"Cohorts, enrollments and delayed billing",icon:af,path:"/admin/programs",color:"bg-emerald-500/10 text-emerald-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:af,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:I4,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:wn,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:wn,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:XN,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:XN,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:Wc,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"LevelUp Live",description:"Public streaming pages, invite links, and live leads",icon:bb,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:wx,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:wx,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:pn,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:gm,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:HI,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:Dj,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:pn,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:gm,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:GN,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:P4,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:dl,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:nu,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:Yn,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:gm,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:no,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:Fq,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:QS,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:ei,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:pn,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:Gl,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:_x,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:vb,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:af,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:lc,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:lc,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:vb,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:Qr,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:wn,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:Hc,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:nf,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:_x,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:Hc,path:"/admin/beta/social-post-generator",color:"bg-gradient-to-br from-fuchsia-500/20 to-pink-500/10 text-fuchsia-600"},{title:"Postcard Direct Mail",description:"Upload monthly postcard designs and manage agent direct mail via Postalytics",icon:pn,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:UI,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:cl,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:Sq,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:dl,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:Zl,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:Qr,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:Qr,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:Qr,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:su,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function Swt(){const s=Zn();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(pa,{defaultValue:"users",className:"w-full",children:[e.jsx(ga,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(kwt).map(([t,n])=>e.jsx(Xt,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries(kwt).map(([t,n])=>e.jsx(Qt,{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(je,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(r.path),children:[e.jsxs(St,{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(Et,{className:"text-base",children:r.title})]}),e.jsx(Le,{className:"pt-0",children:e.jsx(Vn,{className:"text-sm",children:r.description})})]},r.path))})},t))]}),e.jsx(ohn,{})]})})}const lhn=()=>{const{isAdmin:s}=_s(),t=Zn(),[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:v}=await q.from("app_tiles").select("*").order("name");if(v)throw v;r(x||[])}catch(x){console.error("Error loading apps:",x),ne.error("Failed to load apps")}finally{i(!1)}},h=async x=>{x.preventDefault();const v=new FormData(x.currentTarget),y={name:v.get("name"),description:v.get("description"),icon:v.get("icon"),app_id:v.get("app_id"),target_url:v.get("target_url"),required_tags:v.get("required_tags").split(",").map(b=>b.trim()).filter(Boolean)};try{if(c){const{error:b}=await q.from("app_tiles").update(y).eq("id",c.id);if(b)throw b;ne.success("App updated successfully")}else{const{error:b}=await q.from("app_tiles").insert([y]);if(b)throw b;ne.success("App created successfully")}o(!1),d(null),u()}catch(b){console.error("Error saving app:",b),ne.error("Failed to save app")}},m=async x=>{if(await mo("Are you sure you want to delete this app?"))try{const{error:v}=await q.from("app_tiles").delete().eq("id",x);if(v)throw v;ne.success("App deleted successfully"),u()}catch(v){console.error("Error deleting app:",v),ne.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(Va,{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(Os,{open:l,onOpenChange:o,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:g,children:[e.jsx(cn,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx($s,{children:c?"Edit App":"Create New App"}),e.jsx(Er,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Application Tiles"}),e.jsx(Vn,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Le,{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(cn,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:n.map(x=>e.jsxs(An,{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(v=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:v},v))})}),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(pi,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(x.id),children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},x.id))})]})})]})})]})};function Dm({title:s,description:t,children:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(br,{to:"/admin",children:e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(Va,{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 Cwt=({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($e,{variant:"destructive",className:Pt("gap-1",t),children:[e.jsx(Al,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs($e,{variant:"destructive",className:Pt("gap-1",t),children:[e.jsx(ca,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs($e,{className:Pt("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(ca,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs($e,{variant:"secondary",className:Pt("gap-1",t),children:[e.jsx(ca,{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,v]=j.useState(null),y=()=>{c([]),u(""),g("upload"),v(null),l.current&&(l.current.value="")},b=()=>{y(),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 Z=(V.includes(" ")?V.split(" "):V.split(",")).map(X=>X.trim().replace(/^["']|["']$/g,""));if(Z.length>=2){let X="",ae="",le="",re="",te;if(Z.length===2){const ve=Z[0].split(" ");X=ve[0]||"",ae=ve.slice(1).join(" ")||"",le=Z[1]}else if(Z.length===3)X=Z[0],ae=Z[1],le=Z[2];else if(Z.length===4)X=Z[0],ae=Z[1],le=Z[2],re=Z[3];else if(Z.length>=5){X=Z[0],ae=Z[1],le=Z[2],re=Z[3];const ve=Z[4].toLowerCase();te=ve==="true"||ve==="yes"||ve==="1"||ve==="y"}const ce=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(le);W.push({firstName:X.trim(),lastName:ae.trim(),email:le.trim().toLowerCase(),phone:re.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)},A=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");v(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(Os,{open:s,onOpenChange:b,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(KN,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(Er,{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(Vr,{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(vl,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:o.slice(0,100).map((P,R)=>e.jsxs(An,{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($e,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx($e,{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(Vr,{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(Nr,{children:[f==="upload"&&e.jsx($,{variant:"outline",onClick:b,children:"Cancel"}),f==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:y,children:"Back"}),e.jsx($,{onClick:A,disabled:h||E===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{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 Mm({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(Lg,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Dy,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function yie(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 chn=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:ei},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:Kl},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:kx}];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=hRs(),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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(kx,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",r]}),e.jsx(Er,{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:chn.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(ei,{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(su,{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(kx,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const KBe={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:su,color:"bg-green-500"},custom:{label:"Custom",icon:wn,color:"bg-purple-500"}};function dhn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),{data:l=[],isLoading:o}=st({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 v,y,b;return{...x,user_name:((v=g.get(x.user_id))==null?void 0:v.name)||"Unknown",user_email:((y=g.get(x.user_id))==null?void 0:y.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(KBe).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(Ct,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(kx,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(Vn,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Le,{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(KBe).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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:c.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=KBe[u.celebration_type],m=h.icon;return e.jsxs(An,{children:[e.jsx(wt,{children:e.jsxs($e,{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($e,{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:Js(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(wt,{children:u.seen_at?e.jsx($e,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx($e,{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 uhn=()=>{const{user:s}=_s(),{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),v=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:Z}=await q.from("trial_email_exports").select("user_id");if(Z)throw Z;const X=new Set((G||[]).map(le=>le.user_id)),ae=(W||[]).map(le=>({...le,converted_from_trial_at:le.converted_from_trial_at??null,already_exported:X.has(le.id)}));ae.sort((le,re)=>new Date(re.created_at).getTime()-new Date(le.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(()=>{v()},[v]);const y=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},A=n.filter(W=>!(c!=="all"&&y(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===A.length?x(new Set):x(new Set(A.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]||"",ve=J.slice(1).join(" ")||"",fe=y(te)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",ue=w(te)?"Converted":S(te)?"Expired":"Active",be=te.created_at?new Date(te.created_at).toLocaleDateString():"",Ee=b(te)?new Date(b(te)).toLocaleDateString():"";return`"${ce}","${ve}","${te.email}","${te.phone||""}","${fe}","${ue}","${be}","${Ee}"`}),Z=[V,...G].join(` `),X=new Blob([Z],{type:"text/csv"}),ae=URL.createObjectURL(X),le=document.createElement("a");le.href=ae,le.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,le.click(),URL.revokeObjectURL(ae);const re=W.filter(te=>!te.already_exported).map(te=>({user_id:te.id,exported_by:s.id}));if(re.length>0){const{error:te}=await q.from("trial_email_exports").upsert(re,{onConflict:"user_id"});te&&console.error("Error marking exports:",te)}t({title:"Export complete",description:`Downloaded ${W.length} trial user(s). ${re.length} newly marked as exported.`}),x(new Set),v()}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(Ct,{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(je,{children:e.jsxs(St,{className:"pb-2",children:[e.jsx(Vn,{children:"Total"}),e.jsx(Et,{className:"text-2xl",children:n.length})]})}),e.jsx(je,{children:e.jsxs(St,{className:"pb-2",children:[e.jsx(Vn,{children:"New (Not Exported)"}),e.jsx(Et,{className:"text-2xl text-green-600",children:R})]})}),e.jsx(je,{children:e.jsxs(St,{className:"pb-2",children:[e.jsx(Vn,{children:"Active Trials"}),e.jsx(Et,{className:"text-2xl",children:U})]})}),e.jsx(je,{children:e.jsxs(St,{className:"pb-2",children:[e.jsx(Vn,{children:"Converted 🎉"}),e.jsx(Et,{className:"text-2xl text-primary",children:O})]})}),e.jsx(je,{children:e.jsxs(St,{className:"pb-2",children:[e.jsx(Vn,{children:"Already Exported"}),e.jsx(Et,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Export Selected (",g.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(ai,{checked:A.length>0&&g.size===A.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(fi,{children:A.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):A.map(W=>{const V=y(W),G=w(W),Z=S(W),X=b(W);return e.jsxs(An,{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(Zl,{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($e,{variant:"outline",className:"gap-1",children:[e.jsx(jv,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(pn,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(wt,{children:G?e.jsxs($e,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(Zl,{className:"h-3 w-3"}),"Converted"]}):Z?e.jsx($e,{variant:"destructive",children:"Expired"}):e.jsx($e,{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(Vr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx($e,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},W.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",A.length," of ",n.length," trial users · ",O," converted to paid"]})]})},hhn=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,mhn=()=>{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){ne.info("No deletion records to export");return}const i=["Date","Deleted User","Deleted Email","Brokerage","Type","Deleted By"],l=s.map(h=>[Js(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(hhn).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),ne.success(`Exported ${s.length} deletion record(s)`)};return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(je,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(qn,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsx(Et,{className:"text-lg",children:"User Deletion History"}),e.jsxs($,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(Le,{children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:s.map(i=>e.jsxs(An,{children:[e.jsx(wt,{className:"whitespace-nowrap text-sm",children:Js(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($e,{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))})]})})]})},d3=s=>{const{user:t}=_s(),n=Zt(),r=st({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=>st({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(y=>y.user_id),{data:x}=await q.from("profiles").select("id, name, email, avatar_url").in("id",g),v=new Map((x||[]).map(y=>[y.id,y]));return(m||[]).map(y=>({...y,profile:v.get(y.user_id)||null}))},enabled:!!h}),i=mt({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"]}),ne.success("Team created!")},onError:h=>{ne.error("Failed to create team: "+h.message)}}),l=mt({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"]}),ne.success("Team updated")},onError:h=>{ne.error("Failed to update team: "+h.message)}}),o=mt({mutationFn:async h=>{const{error:m}=await q.from("teams").delete().eq("id",h);if(m)throw m},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ne.success("Team deleted")},onError:h=>{ne.error("Failed to delete team: "+h.message)}}),c=mt({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]}),ne.success("Member added to team")},onError:h=>{ne.error(h.message)}}),d=mt({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]}),ne.success("Member removed from team")},onError:h=>{ne.error("Failed to remove member: "+h.message)}}),u=mt({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]}),ne.success("Member role updated")},onError:h=>{ne.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}},Mrt=s=>{const t=Zt(),n=st({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=mt({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(),ne.success("Pond created")},onError:o=>ne.error(o.message)}),i=mt({mutationFn:async({id:o,...c})=>{const{error:d}=await q.from("team_ponds").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),ne.success("Pond updated")},onError:o=>ne.error(o.message)}),l=mt({mutationFn:async o=>{const{error:c}=await q.from("team_ponds").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ne.success("Pond deleted")},onError:o=>ne.error(o.message)});return{ponds:n.data||[],isLoading:n.isLoading,createPond:a,updatePond:i,deletePond:l}},fhn=s=>{const t=Zt(),n=st({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=mt({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=>ne.error(a.message)});return{assignedUserIds:(n.data||[]).map(a=>a.user_id),isLoading:n.isLoading,setAssigned:r}},phn=({pond:s,teamId:t})=>{const{useTeamMembers:n}=d3(),{data:r=[],isLoading:a}=n(t),{assignedUserIds:i,isLoading:l,setAssigned:o}=fhn(s.id);return a||l?e.jsx(xn,{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(Yn,{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($e,{variant:"secondary",className:"ml-auto text-[10px]",children:"Leader"})]},c.id)})})]})},wWt=({teamId:s})=>{const{ponds:t,isLoading:n,createPond:r,updatePond:a,deletePond:i}=Mrt(s),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState(null),[g,x]=j.useState(null),v=async()=>{c.trim()&&(await r.mutateAsync({name:c.trim(),description:u.trim()}),d(""),h(""),o(!1))};return e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:"Lead Ponds"}),e.jsx(Vn,{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(cn,{className:"mr-1 h-4 w-4"})," New Pond"]})]}),e.jsxs(Le,{className:"space-y-3",children:[n&&e.jsx(xn,{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(y=>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(p1,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"font-medium",children:y.name}),y.is_default&&e.jsx($e,{variant:"secondary",className:"text-[10px]",children:"Default"})]}),y.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:y.description}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[y.available_count," available"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[y.claimed_count," claimed"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>x(g===y.id?null:y.id),children:[e.jsx(Yn,{className:"mr-1 h-3.5 w-3.5"}),g===y.id?"Hide agents":"Assign agents"]}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>f(y),children:e.jsx(pi,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>{confirm(`Delete "${y.name}"? Leads in this pond will no longer be shared.`)&&i.mutate(y.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5 text-destructive"})})]})]}),g===y.id&&e.jsx(phn,{pond:y,teamId:s})]},y.id))]}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"New Lead Pond"}),e.jsx(Er,{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:y=>d(y.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:y=>h(y.target.value),placeholder:"What kind of leads go in this pond?"})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:v,disabled:!c.trim()||r.isPending,children:"Create Pond"})]})]})}),e.jsx(Os,{open:!!m,onOpenChange:y=>!y&&f(null),children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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:y=>f({...m,name:y.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(pe,{value:m.description||"",onChange:y=>f({...m,description:y.target.value})})]})]}),e.jsxs(Nr,{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)=>st({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}),xhn=()=>{const{user:s}=_s();return st({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})},jWt=(s,t)=>{const{user:n}=_s(),r=Zt(),a=st({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=mt({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"]}),ne.success("Contact added to Lead Pond")},onError:c=>{ne.error(c.message)}}),l=mt({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"]}),ne.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=>{ne.error(c.message)}}),o=mt({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"]}),ne.success("Lead returned to pond")},onError:c=>{ne.error(c.message)}});return{leadPondItems:a.data||[],isLoading:a.isLoading,addToLeadPond:i,claimLead:l,returnLead:o}},yhn=(s,t,n=100)=>st({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}),vhn=()=>{const s=Zt();return mt({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"]}),ne.success("Contact transferred successfully")},onError:t=>{ne.error(t.message||"Failed to transfer contact")}})};function NWt({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var A;const{user:i}=_s(),{data:l}=Ow(),{useTeamMembers:o}=d3(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=vhn(),[u,h]=j.useState(null),[m,f]=j.useState(""),[g,x]=j.useState(!1),v=c.filter(E=>E.user_id!==(i==null?void 0:i.id)),y=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=v.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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(S4,{className:"h-5 w-5"}),"Transfer ",S]}),e.jsxs(Er,{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:v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):v.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(Ii,{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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:y,disabled:!u||g,children:[g?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(S4,{className:"h-4 w-4 mr-2"}),"Transfer",b?` to ${(A=b.profile)==null?void 0:A.name}`:""]})]})]})})}const nRe=()=>{const s=Zn(),{data:t,isLoading:n}=xhn(),{data:r}=Ow(),[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(v=>{x.has(v.owner_user_id)||x.set(v.owner_user_id,{id:v.owner_user_id,name:v.owner_name||"Unknown",avatar:v.owner_avatar_url})}),Array.from(x.values())},[t]),g=j.useMemo(()=>{if(!t)return[];let x=t;if(l!=="all"&&(x=x.filter(v=>v.owner_user_id===l)),a.trim()){const v=a.toLowerCase();x=x.filter(y=>{var b,w,S;return(y.first_name+" "+(y.last_name||"")).toLowerCase().includes(v)||((b=y.email)==null?void 0:b.toLowerCase().includes(v))||((w=y.phone)==null?void 0:w.includes(v))||((S=y.owner_name)==null?void 0:S.toLowerCase().includes(v))})}return x},[t,a,l]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-10 w-full"}),e.jsx(xn,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Yn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-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(je,{children:e.jsx(Le,{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(je,{children:e.jsx(Le,{className:"p-0 overflow-x-auto",children:e.jsxs(hi,{className:"min-w-[800px]",children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:g.length===0?e.jsx(An,{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(An,{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(Ii,{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(pn,{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(ui,{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($e,{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:Js(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:v=>{v.stopPropagation(),d(x.id),h(`${x.first_name} ${x.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(S4,{className:"h-4 w-4"})})})]},x.id))})]})})}),e.jsx(NWt,{open:!!c,onOpenChange:x=>{x||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},bhn=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)},_hn=({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(xn,{className:"h-4 w-2/3"}),e.jsx(xn,{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(Xz,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(rf,{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:bhn(a.occurred_at)})]})]},i))})},whn=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:Pq,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:Sx,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:p1,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"]})}}},Awt=({teamId:s,pondId:t})=>{const{data:n,isLoading:r}=yhn(s,t),[a,i]=j.useState(!1),l=n||[],o=a?l:l.slice(0,8);return e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"flex items-center gap-2 text-sm",children:[e.jsx(Cw,{className:"h-4 w-4"}),"Pond Activity History"]})}),e.jsx(Le,{className:"space-y-3",children:r?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(c=>e.jsx(xn,{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(Ii,{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:whn(c.occurred_at)}),c.pond_name&&e.jsx($e,{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(xb,{className:"mr-1 h-3 w-3"}):e.jsx(wl,{className:"mr-1 h-3 w-3"}),a?"Show less":`Show all ${l.length} events`]})]})})]})},Nhn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric"}).format(new Date(s)):null,khn=({item:s,isClaimer:t,onReturn:n,returning:r})=>{var o,c,d;const[a,i]=j.useState(!1),l=Nhn(s.last_activity_at);return e.jsx(je,{children:e.jsxs(Le,{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($e,{variant:"secondary",className:"text-xs",children:["Claimed by ",((d=s.claimer)==null?void 0:d.name)||"Unknown"]}),e.jsxs($e,{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(ca,{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(Ta,{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(Sx,{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(xb,{className:"mr-1 h-3 w-3"}):e.jsx(wl,{className:"mr-1 h-3 w-3"}),a?"Hide notes & activity":"View notes & activity"]}),a&&e.jsx(_hn,{leadPondId:s.id})]})]})})},rRe=({teamId:s})=>{const{user:t}=_s(),[n,r]=j.useState(null),{ponds:a}=Mrt(s),i=a.filter(f=>f.has_access),{leadPondItems:l,isLoading:o,claimLead:c,returnLead:d}=jWt(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(p1,{className:"mr-1 h-3 w-3"}),f.name,e.jsx($e,{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(xn,{className:"h-20 w-full"},f))});if(l.length===0)return e.jsxs("div",{className:"space-y-4",children:[u,e.jsx(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(p1,{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(Awt,{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,v,y,b,w,S,A,E,I,P;return e.jsx(je,{children:e.jsxs(Le,{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:[((v=f.contact)==null?void 0:v.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(pn,{className:"h-3 w-3"})," ",f.contact.email]}),((y=f.contact)==null?void 0:y.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(ui,{className:"h-3 w-3"})," ",f.contact.address]})]}),f.pond_name&&n===null&&i.length>1&&e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:[e.jsx(p1,{className:"mr-1 h-2.5 w-2.5"})," ",f.pond_name]}),((w=f.contact)==null?void 0:w.lead_source)&&e.jsxs($e,{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(Xz,{className:"h-3 w-3 mt-0.5 shrink-0"}),e.jsx("span",{className:"whitespace-pre-wrap",children:f.notes||((A=f.contact)==null?void 0:A.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(Ii,{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(Pq,{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(khn,{item:f,isClaimer:f.claimed_by===(t==null?void 0:t.id),onReturn:()=>d.mutate(f.id),returning:d.isPending},f.id))})]}),e.jsx(Awt,{teamId:s,pondId:n})]})},Prt=({teamId:s})=>{const{useTeamMembers:t}=d3(),{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}=st({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}=st({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}=st({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(xn,{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(je,{children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx(vb,{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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{className:"flex items-center gap-3 p-4",children:[e.jsx(fa,{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(pa,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(Xt,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(Xt,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(Qt,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(YBe,{icon:e.jsx(vb,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(f=>{const g=m(f.owner_user_id);return e.jsx(je,{children:e.jsxs(Le,{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(Ii,{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," · ",Js(new Date(f.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx($e,{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(Ta,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})}),e.jsx(Qt,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(YBe,{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(je,{children:e.jsxs(Le,{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(Ii,{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," · ",Js(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($e,{className:"text-xs",children:"Active"}):e.jsx($e,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Yn,{className:"h-3 w-3"}),f.visitor_count||0]})]})]})},f.id)})}),e.jsx(Qt,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(YBe,{icon:e.jsx(fa,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(f=>{const g=m(f.owner_user_id);return e.jsx(je,{children:e.jsxs(Le,{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(Ii,{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," · ",Js(new Date(f.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx($e,{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(Ta,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})})]})]})},YBe=({icon:s,label:t})=>e.jsx(je,{children:e.jsxs(Le,{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})]})}),kWt=({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}=d3(),{data:h=[],isLoading:m}=u(s.id),[f,g]=j.useState(!1),[x,v]=j.useState(""),[y,b]=j.useState("team_member"),{data:w}=st({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)),A=t.filter(R=>!S.has(R.id)),E=async()=>{x&&(await a(x,y),v(""),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(pa,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"members",children:"Members"}),e.jsxs(Xt,{value:"contacts",children:[e.jsx(BI,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(Xt,{value:"lead-pond",children:[e.jsx(p1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(Xt,{value:"shared-assets",children:[e.jsx(Nv,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(Xt,{value:"settings",children:"Settings"})]}),e.jsxs(Qt,{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(Os,{open:f,onOpenChange:g,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(lc,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Add Team Member"}),e.jsxs(Er,{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(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[x&&(((I=A.find(R=>R.id===x))==null?void 0:I.name)||((P=A.find(R=>R.id===x))==null?void 0:P.email))||"Select an agent",e.jsx(kw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Dd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(N2,{children:[e.jsx(k2,{placeholder:"Search agents..."}),e.jsxs(S2,{children:[e.jsx(C2,{children:"No agents found."}),e.jsx(Rw,{children:A.map(R=>{const D=w==null?void 0:w.get(R.id);return e.jsxs(h1,{value:R.name||R.email||R.id,onSelect:()=>v(R.id),children:[e.jsx(ma,{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:y,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(Nr,{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(xn,{className:"h-16 w-full"},R))}):h.length===0?e.jsx(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(Yn,{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(je,{children:e.jsxs(Le,{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(Ii,{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($e,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(Og,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx($e,{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(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(oV,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Remove Member?"}),e.jsxs(ic,{children:["Remove ",((V=R.profile)==null?void 0:V.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:()=>i(R.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},R.id)})})]}),e.jsx(Qt,{value:"contacts",className:"space-y-4",children:e.jsx(nRe,{})}),s.lead_pond_enabled&&e.jsx(Qt,{value:"lead-pond",className:"space-y-4",children:e.jsx(rRe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(Qt,{value:"shared-assets",className:"space-y-4",children:e.jsx(Prt,{teamId:s.id})}),e.jsxs(Qt,{value:"settings",className:"space-y-4",children:[e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-lg",children:"Team Settings"}),e.jsx(Vn,{children:"Configure how this team operates."})]}),e.jsxs(Le,{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(jn,{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(jn,{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(jn,{checked:s.shared_videos_enabled??!1,onCheckedChange:R=>r({shared_videos_enabled:R})})]})]})]}),s.lead_pond_enabled&&e.jsx(wWt,{teamId:s.id}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsxs($,{variant:"destructive",size:"sm",children:[e.jsx(qn,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Delete Team?"}),e.jsxs(ic,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:()=>{o(),n()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},SWt=({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(""),[v,y]=j.useState(""),[b,w]=j.useState([]),S=()=>{d(1),h(""),f(""),x(""),y(""),w([])},A=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:v||void 0,memberIds:b.length>0?b:void 0}),S()},I=R=>{R!==v&&w(D=>D.includes(R)?D.filter(O=>O!==R):[...D,R])},P=a.filter(R=>R.id!==v);return e.jsx(Os,{open:s,onOpenChange:A,children:e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx($s,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(Er,{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(Og,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(ms,{value:v,onValueChange:R=>{y(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(lc,{className:"h-3.5 w-3.5"}),"Initial Members",b.length>0&&e.jsxs($e,{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(Yn,{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(Ii,{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(ma,{className:"h-3 w-3"})})]},R.id)})})]})]})}),e.jsx(Nr,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>d(2),disabled:!u.trim(),children:["Next",e.jsx(Qa,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",onClick:()=>d(1),children:[e.jsx(Va,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx($,{onClick:E,disabled:r,children:r?"Creating…":"Create Team"})]})})]})})},Shn=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=d3(),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,f]=j.useState(""),{data:g}=st({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:A,error:E}=await q.from("brokerages").select("id, name").order("name");if(E)throw E;return A||[]}}),{data:x}=st({queryKey:["admin-team-member-info",s.map(A=>A.id).join(",")],queryFn:async()=>{var R;if(s.length===0)return{};const{data:A}=await q.from("team_members").select("team_id, user_id, role").in("team_id",s.map(D=>D.id));if(!A)return{};const E=A.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=A.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}),v=(u==null?void 0:u.brokerage_id)||null,{data:y}=st({queryKey:["brokerage-agents-for-teams",v],queryFn:async()=>{let A=q.from("profiles").select("id, name, email, avatar_url").order("name");v&&(A=A.eq("brokerage_id",v));const{data:E,error:I}=await A;if(I)throw I;return E||[]},enabled:!!u}),b=Object.fromEntries((g||[]).map(A=>[A.id,A.name])),w=async A=>{const E=await n.mutateAsync({name:A.name,brokerage_id:A.brokerage_id||null,description:A.description});if(A.leaderId&&A.leaderId!=="none"&&await i.mutateAsync({team_id:E.id,user_id:A.leaderId,role:"team_leader"}),A.memberIds)for(const I of A.memberIds)await i.mutateAsync({team_id:E.id,user_id:I,role:"team_member"});d(!1)};if(u)return e.jsx(kWt,{team:u,brokerageAgents:y||[],onBack:()=>h(null),onUpdate:A=>r.mutateAsync({id:u.id,...A}).then(E=>h(E)),onAddMember:(A,E)=>i.mutateAsync({team_id:u.id,user_id:A,role:E}),onRemoveMember:A=>l.mutateAsync({team_id:u.id,member_id:A}),onUpdateRole:(A,E)=>o.mutateAsync({team_id:u.id,member_id:A,role:E}),onDeleteTeam:()=>{a.mutate(u.id),h(null)},isUpdating:r.isPending,isAddingMember:i.isPending});const S=s.filter(A=>A.name.toLowerCase().includes(m.toLowerCase())||(A.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:A=>f(A.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(cn,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(SWt,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(A=>e.jsxs(An,{children:[e.jsx(wt,{children:e.jsx(xn,{className:"h-4 w-32"})}),e.jsx(wt,{children:e.jsx(xn,{className:"h-4 w-24"})}),e.jsx(wt,{children:e.jsx(xn,{className:"h-4 w-28"})}),e.jsx(wt,{children:e.jsx(xn,{className:"h-4 w-12"})}),e.jsx(wt,{children:e.jsx(xn,{className:"h-4 w-20"})}),e.jsx(wt,{children:e.jsx(xn,{className:"h-4 w-16"})})]},A))}):S.length===0?e.jsx(An,{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(A=>{const E=x==null?void 0:x[A.id];return e.jsxs(An,{className:"hover:bg-muted/30",children:[e.jsxs(wt,{children:[e.jsx("button",{onClick:()=>h(A),className:"text-primary hover:underline font-medium",children:A.name}),A.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:A.description})]}),e.jsx(wt,{children:A.brokerage_id?e.jsx("span",{className:"text-sm",children:b[A.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(Og,{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($e,{variant:"secondary",className:"text-xs",children:[e.jsx(Yn,{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(Tf,{className:"h-3 w-3"}),A.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(A),title:"Edit team",children:e.jsx(pi,{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 mo(`Delete team "${A.name}"? This cannot be undone.`)&&a.mutate(A.id)},title:"Delete team",children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})})]},A.id)})})]})})]})};function Ewt(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 Chn({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),[v,y]=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}y(!0)},A=async()=>{if(b){y(!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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(Er,{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(Ct,{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:[Ewt(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(Ea,{className:"h-4 w-4 text-primary"}),b.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ewt(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($e,{variant:"secondary",className:"text-xs font-normal",children:E.name||E.email},E.id)),w.length>30&&e.jsxs($e,{variant:"outline",className:"text-xs",children:["+",w.length-30," more"]})]})]})]}),e.jsxs(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"})," Send to ",w.length]})})]})]})}),e.jsx(fc,{open:v,onOpenChange:y,children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Send event invite?"}),e.jsx(ic,{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(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsxs(Yl,{onClick:A,children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const Ahn=()=>{var au;const s=Zn(),{user:t,isAdmin:n}=_s(),{startImpersonation:r,isLoading:a}=cLe(),{toast:i}=Bi(),[l,o]=j.useState([]),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,f]=j.useState({}),[g,x]=j.useState(!0),[v,y]=j.useState({}),[b,w]=j.useState(!1),[S,A]=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"),[Z,X]=j.useState(!1),[ae,le]=j.useState(!1),[re,te]=j.useState({done:0,total:0}),[J,ce]=j.useState(null),[ve,fe]=j.useState("all"),[ue,be]=j.useState("all"),[Ee,ke]=j.useState("all"),[Ie,Fe]=j.useState("all"),[Ne,Be]=j.useState(!1),[Se,Ae]=j.useState(!1),[Ce,qe]=j.useState(!1),[ze,Ve]=j.useState(""),[ht,Qe]=j.useState(!1),[at,rt]=j.useState(null),[Ke,Je]=j.useState(null),[ft,gt]=j.useState(!1),[es,Ht]=j.useState({name:"",email:"",brokerage_id:"",phone:""}),[as,bs]=j.useState(null),[Ut,Ft]=j.useState(!1),[is,jt]=j.useState(""),[zs,yt]=j.useState(!1),[gs,Ss]=j.useState(!1),[Ds,Bt]=j.useState(null),[zt,vs]=j.useState(""),[dn,Ks]=j.useState(!1),[Cn,Rr]=j.useState(!1),[ia,Hs]=j.useState(null),[Br,Ur]=j.useState(!1),[Wn,Sn]=j.useState(!1),[Fn,bn]=j.useState(null),[xs,Tr]=j.useState(""),[Lr,la]=j.useState(!1),[Xn,wr]=j.useState({email:"",name:"",password:"",phone:""}),[Bn,cr]=j.useState(!1),[Pa,ii]=j.useState(null),[$i,Ln]=j.useState([]),[xa,Ka]=j.useState("none"),[uo,Tc]=j.useState(!1),[Fd,Nl]=j.useState(""),[Ho,ti]=j.useState(!1),[Yr,Eo]=j.useState(!1),[Th,rh]=j.useState(""),[ro,ea]=j.useState(new Set),[pc,ml]=j.useState(!1),[Co,mu]=j.useState(!1),[cc,nd]=j.useState(null),[Dr,Hi]=j.useState(!1),[zc,Bc]=j.useState(null),[gc,$l]=j.useState([]),[sg,Mx]=j.useState([]),[Yo,Mc]=j.useState(!1),[Mh,lm]=j.useState({});j.useEffect(()=>{if(!t||!n){t&&!n&&x(!1);return}ws(),Xa()},[t,n]);const Yc=async()=>{try{const{data:Vt,error:Nn}=await q.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(Nn)throw Nn;const nr={};for(const na of Vt??[])nr[na.brokerage_id]||(nr[na.brokerage_id]=[]),nr[na.brokerage_id].push(na.user_id);f(nr)}catch(Vt){console.error("Error loading brokerage manager assignments:",Vt)}},ws=async()=>{try{x(!0);const{data:Vt,error:Nn}=await q.functions.invoke("get-user-details");if(Nn)throw Nn;const nr=Vt.users||[];o(nr),h(Vt.brokerages||[]),await Yc();const na=nr.filter(Wr=>Wr.roles.includes("assistant"));if(na.length>0){const Wr=na.map(gi=>gi.id),{data:Ca}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",Wr);if(Ca&&Ca.length>0){const gi=[...new Set(Ca.map(zo=>zo.agent_id))],{data:Ia}=await q.from("profiles").select("id, name, email").in("id",gi),el={};for(const zo of Ca){const Pc=Ia==null?void 0:Ia.find(Eu=>Eu.id===zo.agent_id);Pc&&(el[zo.assistant_id]={agent_name:Pc.name||"",agent_email:Pc.email||""})}lm(el)}}}catch(Vt){console.error("Error loading members:",Vt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{x(!1)}},Xa=async()=>{try{const{data:Vt,error:Nn}=await q.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(Nn)throw Nn;d(Vt||[])}catch(Vt){console.error("Error loading apps:",Vt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},No=async Vt=>{if(!es.name.trim()||!es.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(es.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:nr}=await q.from("profiles").update({name:es.name.trim(),email:es.email.trim(),brokerage_id:es.brokerage_id||null,phone:es.phone.trim()||null}).eq("id",Vt);if(nr)throw nr;i({title:"Success",description:"Member details updated successfully"}),rt(null),ws()}catch(nr){console.error("Error updating member:",nr),i({title:"Error",description:nr.message||"Failed to update member",variant:"destructive"})}},Ba=async Vt=>{try{const{data:{session:Nn}}=await q.auth.getSession(),nr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Nn==null?void 0:Nn.access_token}`},body:JSON.stringify({userId:Vt})}),na=await nr.json();if(!nr.ok)throw new Error(na.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(Nn){console.error("Error resending welcome email:",Nn),i({title:"Error",description:Nn.message||"Failed to resend welcome email",variant:"destructive"})}},ao=async(Vt,Nn)=>{try{const{error:nr}=await q.functions.invoke("send-password-reset",{body:{email:Vt,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(nr)throw nr;i({title:"Password Reset Sent",description:`Password reset email sent to ${Nn}`})}catch(nr){console.error("Error sending password reset:",nr),i({title:"Error",description:nr.message||"Failed to send password reset email",variant:"destructive"})}},ko=async(Vt,Nn)=>{if(await mo(`Are you sure you want to delete ${Nn}? This action cannot be undone.`))try{const{data:{session:nr}}=await q.auth.getSession(),na=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nr==null?void 0:nr.access_token}`},body:JSON.stringify({userId:Vt})}),Wr=await na.json();if(!na.ok)throw new Error(Wr.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),ws()}catch(nr){console.error("Error deleting user:",nr),i({title:"Error",description:nr.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:Vt}}=await q.auth.getSession(),Nn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vt==null?void 0:Vt.access_token}`},body:JSON.stringify(S)}),nr=await Nn.json();if(!Nn.ok)throw new Error(nr.error||"Failed to create user");if(S.role&&S.role!=="user"&&nr.userId){const na=S.role==="brokerage_manager"?S.brokerage_id:void 0;await cm(nr.userId,S.role,"add",na)}i({title:"Success",description:`User ${S.email} created successfully`}),A({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),I(!1),ws()}catch(Vt){console.error("Error creating user:",Vt),i({title:"Error",description:Vt.message||"Failed to create user",variant:"destructive"})}finally{w(!1)}},cm=async(Vt,Nn,nr,na)=>{try{const{data:{session:Wr}}=await q.auth.getSession(),Ca={userId:Vt,role:Nn,action:nr};if(Nn==="brokerage_manager"){if(!na){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}Ca.brokerageId=na}const gi=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wr==null?void 0:Wr.access_token}`},body:JSON.stringify(Ca)}),Ia=await gi.json();if(!gi.ok)throw new Error(Ia.error||"Failed to manage user role");i({title:"Success",description:`Role ${nr==="add"?"added":"removed"} successfully`}),ws()}catch(Wr){console.error("Error managing user role:",Wr),i({title:"Error",description:Wr.message||"Failed to manage user role",variant:"destructive"})}},Zo=(Vt,Nn)=>Nn.length===0?!0:Nn.some(nr=>Vt.includes(nr)),vo=async(Vt,Nn,nr)=>{const na=`${Vt}-${Nn.id}`;bs(na);try{if(nr){const Wr=l.find(gi=>gi.id===Vt),Ca=Nn.required_tags.filter(gi=>Wr==null?void 0:Wr.tags.includes(gi));for(const gi of Ca){const{error:Ia}=await q.from("user_tags").delete().eq("user_id",Vt).eq("tag",gi);if(Ia)throw Ia}i({title:"Access Removed",description:`Removed access to ${Nn.name}`})}else if(Nn.required_tags.length>0){const{error:Wr}=await q.from("user_tags").insert({user_id:Vt,tag:Nn.required_tags[0]});if(Wr)throw Wr;i({title:"Access Granted",description:`Granted access to ${Nn.name}`})}await ws()}catch(Wr){console.error("Error toggling access:",Wr),i({title:"Error",description:Wr.message||"Failed to update access",variant:"destructive"})}finally{bs(null)}},Gg=async()=>{const Vt=is.trim();if(!Vt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Vt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(nr=>nr.name.toLowerCase()===Vt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}yt(!0);try{const{error:nr}=await q.from("brokerages").insert({name:Vt});if(nr)throw nr;i({title:"Success",description:`Brokerage "${Vt}" created successfully`}),jt(""),Ft(!1),ws()}catch(nr){console.error("Error creating brokerage:",nr),i({title:"Error",description:nr.message||"Failed to create brokerage",variant:"destructive"})}finally{yt(!1)}},Fl=Vt=>{Bt(Vt),vs(Vt.name),Ss(!0)},Ol=()=>{Bt(null),vs(""),Ss(!1)},fy=async()=>{if(!Ds)return;const Vt=zt.trim();if(!Vt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Vt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}Ks(!0);try{const{error:Nn}=await q.from("brokerages").update({name:Vt}).eq("id",Ds.id);if(Nn)throw Nn;i({title:"Success",description:"Brokerage updated successfully"}),Ol(),ws()}catch(Nn){console.error("Error updating brokerage:",Nn),i({title:"Error",description:Nn.message||"Failed to update brokerage",variant:"destructive"})}finally{Ks(!1)}},Kd=async(Vt,Nn)=>{var nr;if(!Nn||typeof Nn!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const na={userId:Vt,role:"brokerage_manager",action:"add",brokerageId:Nn};console.debug("[assignManagerToBrokerage] payload",na);const{data:{session:Wr}}=await q.auth.getSession(),Ca=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wr==null?void 0:Wr.access_token}`},body:JSON.stringify(na)}),gi=await Ca.json();if(!Ca.ok&&!((nr=gi.error)!=null&&nr.includes("duplicate")))throw new Error(gi.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await ws()}catch(na){console.error("Error assigning manager:",na),i({title:"Error",description:na.message||"Failed to assign manager",variant:"destructive"})}},Vh=Vt=>{Hs(Vt),Rr(!0)},cf=async()=>{if(ia){Ur(!0);try{const Vt=l.filter(na=>na.brokerage_id===ia.id),{data:{session:Nn}}=await q.auth.getSession();for(const na of Vt){const Wr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Nn==null?void 0:Nn.access_token}`},body:JSON.stringify({userId:na.id})});if(!Wr.ok){const Ca=await Wr.json();console.error(`Failed to delete user ${na.email}:`,Ca.error)}}const{error:nr}=await q.from("brokerages").delete().eq("id",ia.id);if(nr)throw nr;i({title:"Success",description:`Brokerage "${ia.name}" and ${Vt.length} member(s) deleted`}),Rr(!1),Hs(null),ws()}catch(Vt){console.error("Error deleting brokerage:",Vt),i({title:"Error",description:Vt.message||"Failed to delete brokerage",variant:"destructive"})}finally{Ur(!1)}}},Wy=Vt=>{bn(Vt),Tr(""),Sn(!0)},ah=()=>{bn(null),Tr(""),Sn(!1)},gh=async Vt=>{try{const{error:Nn}=await q.from("profiles").update({brokerage_id:null}).eq("id",Vt);if(Nn)throw Nn;i({title:"Success",description:"User removed from brokerage"}),ws()}catch(Nn){console.error("Error removing user from brokerage:",Nn),i({title:"Error",description:Nn.message||"Failed to remove user",variant:"destructive"})}},xt=async(Vt,Nn)=>{try{const{error:nr}=await q.from("profiles").update({brokerage_id:Nn}).eq("id",Vt);if(nr)throw nr;i({title:"Success",description:"User added to brokerage"}),ws()}catch(nr){console.error("Error adding user to brokerage:",nr),i({title:"Error",description:nr.message||"Failed to add user",variant:"destructive"})}};j.useEffect(()=>{(async()=>{var Nn;if(!(Fn!=null&&Fn.id)){ii(null),Ln([]),Ka("none");return}try{const{data:nr}=await q.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",Fn.id).maybeSingle();if(!nr||!nr.enabled){ii(null),Ln([]),Ka("none");return}const{data:na}=await q.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",nr.id).order("sort_order",{ascending:!0});ii({id:nr.id,name:nr.name}),Ln(na||[]),Ka(((Nn=na==null?void 0:na[0])==null?void 0:Nn.id)||"none")}catch(nr){console.error("Error loading partnership packages:",nr)}})()},[Fn==null?void 0:Fn.id]);const We=async()=>{if(!Fn||!Xn.email||!Xn.name||!Xn.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}cr(!0);try{const{data:{session:Vt}}=await q.auth.getSession(),Nn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vt==null?void 0:Vt.access_token}`},body:JSON.stringify({...Xn,brokerage_id:Fn.id,role:"user",partnershipPackageId:Pa&&xa!=="none"?xa:void 0})}),nr=await Nn.json();if(!Nn.ok)throw new Error(nr.error||"Failed to create agent");i({title:"Success",description:`Agent ${Xn.email} created successfully`}),wr({email:"",name:"",password:"",phone:""}),la(!1),ws()}catch(Vt){console.error("Error creating agent:",Vt),i({title:"Error",description:Vt.message||"Failed to create agent",variant:"destructive"})}finally{cr(!1)}},ct=Vt=>l.filter(Nn=>Nn.brokerage_id===Vt),Nt=Vt=>{const Nn=ct(Vt);if(!xs)return Nn;const nr=xs.toLowerCase();return Nn.filter(na=>na.name.toLowerCase().includes(nr)||na.email.toLowerCase().includes(nr))},Rt=Vt=>l.filter(Nn=>Nn.brokerage_id!==Vt),$t=l.filter(Vt=>{var nr;if(P){const na=P.toLowerCase();if(!(Vt.name.toLowerCase().includes(na)||Vt.email.toLowerCase().includes(na)||((nr=Vt.brokerage_name)==null?void 0:nr.toLowerCase().includes(na))))return!1}if(V==="claimed"&&!Vt.claimed||V==="unclaimed"&&Vt.claimed||ve!=="all"&&!Vt.roles.includes(ve))return!1;const Nn=Vt.is_trial||Vt.subscription_status==="trialing";if(ue==="trial"&&!Nn||ue==="non-trial"&&Nn||Ee==="none"&&Vt.brokerage_id||Ee!=="all"&&Ee!=="none"&&Vt.brokerage_id!==Ee)return!1;if(Ie!=="all"){if(!Vt.created_at)return!1;const na=parseInt(Ie,10),Wr=Date.now()-na*24*60*60*1e3;if(new Date(Vt.created_at).getTime(){var Nn;return((Nn=Vt.name)==null?void 0:Nn.toLowerCase())||""},brokerage:Vt=>{var Nn;return((Nn=Vt.brokerage_name)==null?void 0:Nn.toLowerCase())||""},status:Vt=>Vt.claimed?"active":"pending",role:Vt=>Vt.roles[0]||"",last_login:Vt=>Vt.last_sign_in_at?new Date(Vt.last_sign_in_at).getTime():null,created_at:Vt=>Vt.created_at?new Date(Vt.created_at).getTime():null}),hn=Ms.length,fn=U===0,gn=fn?1:Math.ceil(hn/U),Mn=fn?0:(D-1)*U,ar=fn?hn:Mn+U,Jn=Ms.slice(Mn,ar),er=Vt=>{R(Vt),O(1)},xr=Vt=>{W(Vt),O(1)},gr=(Vt,Nn)=>{Vt(Nn),O(1)},qa=async(Vt,Nn)=>{Ae(!0);try{const nr=l.find(gi=>gi.id===Vt);if(!nr)return;const na=nr.trial_expires_at?new Date(nr.trial_expires_at):new Date,Wr=new Date(na.getTime()+Nn*24*60*60*1e3),{error:Ca}=await q.from("profiles").update({trial_expires_at:Wr.toISOString()}).eq("id",Vt);if(Ca)throw Ca;i({title:"Trial Extended",description:`Trial extended by ${Nn} days`}),ws()}catch(nr){console.error("Error extending trial:",nr),i({title:"Error",description:nr.message||"Failed to extend trial",variant:"destructive"})}finally{Ae(!1)}},et=async(Vt,Nn,nr)=>{qe(!0);try{const{error:na}=await q.from("profiles").update({is_paused:Nn,paused_at:Nn?new Date().toISOString():null,paused_reason:Nn&&(nr==null?void 0:nr.trim())||null}).eq("id",Vt);if(na)throw na;o(Wr=>Wr.map(Ca=>Ca.id===Vt?{...Ca,is_paused:Nn,paused_reason:Nn&&(nr==null?void 0:nr.trim())||null,paused_at:Nn?new Date().toISOString():null}:Ca)),Je(Wr=>Wr&&Wr.id===Vt?{...Wr,is_paused:Nn,paused_reason:Nn&&(nr==null?void 0:nr.trim())||null}:Wr),i({title:Nn?"Account paused":"Account reactivated",description:Nn?"This member can no longer sign in and will see a paused message.":"This member can sign in again."})}catch(na){console.error("Error updating pause state:",na),i({title:"Error",description:na.message||"Failed to update account",variant:"destructive"})}finally{qe(!1)}},Gt=async Vt=>{Qe(!0);try{const{error:Nn}=await q.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",Vt);if(Nn)throw Nn;i({title:"Account Converted",description:"User has been converted to a full account"}),ws(),Xr()}catch(Nn){console.error("Error converting trial:",Nn),i({title:"Error",description:Nn.message||"Failed to convert account",variant:"destructive"})}finally{Qe(!1)}},[Es,on]=j.useState(!1),en=async(Vt,Nn)=>{if(await mo(`Revert this user to a ${Nn}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){on(!0);try{const nr=new Date,na=new Date(nr.getTime()+Nn*24*60*60*1e3),{error:Wr}=await q.from("profiles").update({is_trial:!0,trial_started_at:nr.toISOString(),trial_expires_at:na.toISOString(),trial_claimed_at:nr.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",Vt);if(Wr)throw Wr;i({title:"Reverted to Trial",description:`User is now on a ${Nn}-day free trial.`}),ws()}catch(nr){console.error("Error reverting to trial:",nr),i({title:"Error",description:nr.message||"Failed to revert to trial",variant:"destructive"})}finally{on(!1)}}},tr=async Vt=>{Mc(!0);try{const{data:Nn}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",Vt);if(Nn&&Nn.length>0){const na=Nn.map(Ca=>Ca.assistant_id),{data:Wr}=await q.from("profiles").select("id, name, email").in("id",na);$l(Nn.map(Ca=>{const gi=Wr==null?void 0:Wr.find(Ia=>Ia.id===Ca.assistant_id);return{id:Ca.id,assistant_id:Ca.assistant_id,assistant_name:(gi==null?void 0:gi.name)||"Unknown",assistant_email:(gi==null?void 0:gi.email)||"",permissions:Ca.permissions||{}}}))}else $l([]);const{data:nr}=await q.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",Vt);if(nr&&nr.length>0){const na=nr.map(Ca=>Ca.agent_id),{data:Wr}=await q.from("profiles").select("id, name, email").in("id",na);Mx(nr.map(Ca=>{const gi=Wr==null?void 0:Wr.find(Ia=>Ia.id===Ca.agent_id);return{id:Ca.id,agent_id:Ca.agent_id,agent_name:(gi==null?void 0:gi.name)||"Unknown",agent_email:(gi==null?void 0:gi.email)||"",permissions:Ca.permissions||{}}}))}else Mx([])}catch(Nn){console.error("Error loading assistant data:",Nn)}finally{Mc(!1)}},sr=Vt=>{Je(Vt),Ht({name:Vt.name,email:Vt.email,brokerage_id:Vt.brokerage_id||"",phone:Vt.phone||""}),gt(!0),tr(Vt.id)},Xr=()=>{Je(null),gt(!1),Ht({name:"",email:"",brokerage_id:"",phone:""})},sa=async()=>{Ke&&(await No(Ke.id),Xr())},$a=Vt=>{ea(Nn=>{const nr=new Set(Nn);return nr.has(Vt)?nr.delete(Vt):nr.add(Vt),nr})},Na=()=>{if(ro.size===Jn.length&&Jn.every(Vt=>ro.has(Vt.id))){const Vt=new Set(ro);Jn.forEach(Nn=>Vt.delete(Nn.id)),ea(Vt)}else{const Vt=new Set(ro);Jn.forEach(Nn=>Vt.add(Nn.id)),ea(Vt)}},La=()=>{ea(new Set)},eo=async()=>{if(ro.size===0)return;ml(!0);let Vt=0,Nn=0;try{const{data:{session:nr}}=await q.auth.getSession();for(const na of ro)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nr==null?void 0:nr.access_token}`},body:JSON.stringify({userId:na,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"})})).ok?Vt++:Nn++}catch{Nn++}i({title:"Bulk Email Complete",description:`Sent ${Vt} emails${Nn>0?`, ${Nn} failed`:""}`}),La()}catch(nr){i({title:"Error",description:nr.message||"Failed to send emails",variant:"destructive"})}finally{ml(!1)}},xo=async()=>{if(ro.size===0)return;ml(!0);let Vt=0,Nn=0;try{const{data:{session:nr}}=await q.auth.getSession();for(const na of ro)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nr==null?void 0:nr.access_token}`},body:JSON.stringify({userId:na})})).ok?Vt++:Nn++}catch{Nn++}i({title:"Bulk Password Reset Complete",description:`Sent ${Vt} reset emails${Nn>0?`, ${Nn} failed`:""}`}),La()}catch(nr){i({title:"Error",description:nr.message||"Failed to send password reset emails",variant:"destructive"})}finally{ml(!1)}},io=async Vt=>{le(!0),te({done:0,total:Vt.length});const Nn=[];try{const{data:{session:nr}}=await q.auth.getSession(),na=5;for(let Ca=0;Ca{try{const el=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nr==null?void 0:nr.access_token}`},body:JSON.stringify({userId:Ia.id,variant:"activation"})}),zo=await el.json().catch(()=>({}));el.ok&&(zo==null?void 0:zo.sent)!==!1?Nn.push({email:Ia.email,ok:!0}):Nn.push({email:Ia.email,ok:!1,reason:(zo==null?void 0:zo.reason)||`HTTP ${el.status}`})}catch(el){Nn.push({email:Ia.email,ok:!1,reason:(el==null?void 0:el.message)||"Network error"})}})),te({done:Math.min(Ca+na,Vt.length),total:Vt.length}),Ca+nasetTimeout(Ia,1200))}ce(Nn);const Wr=Nn.filter(Ca=>Ca.ok).length;i({title:"Activation emails sent",description:`${Wr} of ${Vt.length} sent successfully`})}finally{le(!1)}},Lo=async()=>{if(ro.size===0)return;const Vt=l.filter(Wr=>ro.has(Wr.id)).map(Wr=>Wr.name).slice(0,5).join(", "),Nn=ro.size>5?` and ${ro.size-5} more`:"";if(!await mo(`Are you sure you want to delete ${ro.size} users (${Vt}${Nn})? This action cannot be undone.`))return;ml(!0);let nr=0,na=0;try{const{data:{session:Wr}}=await q.auth.getSession();for(const Ca of ro)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Wr==null?void 0:Wr.access_token}`},body:JSON.stringify({userId:Ca})})).ok?nr++:na++}catch{na++}i({title:"Bulk Delete Complete",description:`Deleted ${nr} users${na>0?`, ${na} failed`:""}`}),La(),ws()}catch(Wr){i({title:"Error",description:Wr.message||"Failed to delete users",variant:"destructive"})}finally{ml(!1)}},Ul=async()=>{mu(!0);try{const{data:{session:Vt}}=await q.auth.getSession(),Nn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vt==null?void 0:Vt.access_token}`}});if(!Nn.ok){const na=await Nn.json();throw new Error(na.error||"Failed to sync phones")}const nr=await Nn.json();i({title:"Phone Sync Complete",description:`Pulled ${nr.summary.pulledFromGHL} from GHL, pushed ${nr.summary.pushedToGHL} to GHL, ${nr.summary.alreadySynced} already synced`}),ws()}catch(Vt){i({title:"Error",description:Vt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{mu(!1)}},fo=async(Vt,Nn)=>{nd(Vt);try{const{data:{session:nr}}=await q.auth.getSession(),{data:na}=await q.from("profiles").select("phone").eq("id",Vt).single(),Wr=(na==null?void 0:na.phone)||"",Ca=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nr==null?void 0:nr.access_token}`},body:JSON.stringify({email:Nn,action:"update",phone:Wr||void 0})});if(!Ca.ok){const Ia=await Ca.json();throw new Error(Ia.error||"Failed to sync with GHL")}const gi=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(Nn)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:Wr?`Phone ${Wr} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),ws()}catch(nr){i({title:"Error",description:nr.message||"Failed to sync phone",variant:"destructive"})}finally{nd(null)}},nl=async Vt=>{await r(Vt)},Pl=()=>{if(ro.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const Vt=l.filter(Ia=>ro.has(Ia.id)),Nn=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],nr=Vt.map(Ia=>[Ia.name,Ia.email,Ia.phone||"",Ia.brokerage_name||"",Ia.roles.join("; "),Ia.claimed?"Claimed":"Unclaimed",new Date(Ia.created_at).toLocaleDateString()]),na=[Nn.join(","),...nr.map(Ia=>Ia.map(el=>`"${(el||"").replace(/"/g,'""')}"`).join(","))].join(` `),Wr=new Blob([na],{type:"text/csv"}),Ca=URL.createObjectURL(Wr),gi=document.createElement("a");gi.href=Ca,gi.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,gi.click(),URL.revokeObjectURL(Ca),i({title:"Export complete",description:`Exported ${Vt.length} member(s)`})},Cd=()=>{if($t.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const Vt=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],Nn=$t.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():""]),nr=[Vt.join(","),...Nn.map(Ia=>Ia.map(el=>`"${(el||"").replace(/"/g,'""')}"`).join(","))].join(` `),na=new Blob([nr],{type:"text/csv"}),Wr=URL.createObjectURL(na),Ca=document.createElement("a"),gi=Ie!=="all"?`-last-${Ie}days`:"";Ca.href=Wr,Ca.download=`members-export${gi}-${new Date().toISOString().split("T")[0]}.csv`,Ca.click(),URL.revokeObjectURL(Wr),i({title:"Export complete",description:`Exported ${$t.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(Dm,{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(Al,{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:Ul,disabled:Co,children:[Co?e.jsx(Ct,{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:()=>Tc(!0),children:[e.jsx(KN,{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(Os,{open:E,onOpenChange:I,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(lc,{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(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Create New User"}),e.jsx(Er,{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:Vt=>A({...S,name:Vt.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:Vt=>A({...S,email:Vt.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:Vt=>A({...S,password:Vt.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:Vt=>A({...S,phone:Vt.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:Vt=>A({...S,brokerage_id:Vt==="none"?"":Vt}),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(Vt=>e.jsx(Ge,{value:Vt.id,children:Vt.name},Vt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"role",children:"Role"}),e.jsxs(ms,{value:S.role,onValueChange:Vt=>A({...S,role:Vt}),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:Vt=>A({...S,trial_days:Vt==="none"?"":Vt}),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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>I(!1),children:"Cancel"}),e.jsx($,{onClick:qi,disabled:b,children:b?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(pa,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"members",children:"Members"}),e.jsx(Xt,{value:"brokerages",children:"Brokerages"}),e.jsx(Xt,{value:"teams",children:"Teams"}),e.jsx(Xt,{value:"trials",children:"Trial Users"}),e.jsx(Xt,{value:"access",children:"Access Matrix"}),e.jsx(Xt,{value:"celebrations",children:"Celebrations"}),e.jsx(Xt,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(Qt,{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:Vt=>er(Vt.target.value),className:"pl-10 h-9"})]}),e.jsxs(ms,{value:V,onValueChange:Vt=>gr(G,Vt),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:ve,onValueChange:Vt=>gr(fe,Vt),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:Vt=>gr(be,Vt),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:Vt=>gr(ke,Vt),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(Vt=>e.jsx(Ge,{value:Vt.id,children:Vt.name},Vt.id))]})]}),e.jsxs(ms,{value:Ie,onValueChange:Vt=>gr(Fe,Vt),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:Cd,title:"Export currently filtered members to CSV",children:[e.jsx(ji,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-9",disabled:Ms.filter(Vt=>!Vt.claimed&&Vt.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(pn,{className:"h-4 w-4 mr-1"}),"Email Pending (",Ms.filter(Vt=>!Vt.claimed&&Vt.email).length,")"]}),e.jsx(Os,{open:Z,onOpenChange:Vt=>{ae||X(Vt)},children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Email pending members"}),e.jsx(Er,{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… ",re.done," of ",re.total]}),J&&!ae&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm",children:[J.filter(Vt=>Vt.ok).length," sent",J.some(Vt=>!Vt.ok)&&`, ${J.filter(Vt=>!Vt.ok).length} failed`]}),J.some(Vt=>!Vt.ok)&&e.jsx("div",{className:"max-h-48 overflow-y-auto rounded border p-2 text-xs space-y-1",children:J.filter(Vt=>!Vt.ok).map(Vt=>e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:Vt.email}),e.jsx("span",{className:"text-muted-foreground truncate",children:Vt.reason})]},Vt.email))})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",disabled:ae,onClick:()=>X(!1),children:"Close"}),!J&&e.jsx($,{disabled:ae,onClick:()=>io(Ms.filter(Vt=>!Vt.claimed&&Vt.email).map(Vt=>({id:Vt.id,email:Vt.email,name:Vt.name}))),children:ae?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}),"Sending…"]}):`Send to ${Ms.filter(Vt=>!Vt.claimed&&Vt.email).length} members`})]})]})}),(P||V!=="all"||ve!=="all"||ue!=="all"||Ee!=="all"||Ie!=="all")&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{R(""),G("all"),fe("all"),be("all"),ke("all"),Fe("all"),O(1)},children:[e.jsx(mr,{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:fn?`Showing all ${hn} members`:`Showing ${Mn+1}-${Math.min(ar,hn)} of ${hn} members`}),e.jsxs(ms,{value:U.toString(),onValueChange:Vt=>xr(Number(Vt)),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"})]})]})]})]}),ro.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[Jn.length>0&&Jn.every(Vt=>ro.has(Vt.id))&&Ms.length>ro.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 ",ro.size," on this page are selected."]}),e.jsxs($,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>ea(new Set(Ms.map(Vt=>Vt.id))),children:["Select all ",Ms.length," filtered members"]})]}),Ms.length>0&&ro.size===Ms.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",Ms.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(qj,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[ro.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:eo,disabled:pc,children:[pc?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(pn,{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:pc,children:[pc?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(__,{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:()=>Be(!0),disabled:pc,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(ZS,{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:Pl,children:[e.jsx(ji,{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:pc,children:[pc?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(qn,{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:pc,children:e.jsx(mr,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"w-[50px]",children:e.jsx(ai,{checked:Jn.length>0&&Jn.every(Vt=>ro.has(Vt.id)),onCheckedChange:Na,"aria-label":"Select all on page"})}),e.jsx(Mm,{sortKey:"name",currentSortKey:Wt,currentDirection:js,onSort:Ts,children:"Name"}),e.jsx(Mm,{sortKey:"brokerage",currentSortKey:Wt,currentDirection:js,onSort:Ts,children:"Brokerage"}),e.jsx(Mm,{sortKey:"status",currentSortKey:Wt,currentDirection:js,onSort:Ts,children:"Status"}),e.jsx(Mm,{sortKey:"role",currentSortKey:Wt,currentDirection:js,onSort:Ts,children:"Role"}),e.jsx(Mm,{sortKey:"last_login",currentSortKey:Wt,currentDirection:js,onSort:Ts,children:"Last Login"}),e.jsx(Mm,{sortKey:"created_at",currentSortKey:Wt,currentDirection:js,onSort:Ts,children:"Member Since"}),e.jsx(Dt,{className:"w-[100px]"})]})}),e.jsx(fi,{children:Jn.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):Jn.map(Vt=>e.jsxs(An,{className:`hover:bg-muted/30 ${ro.has(Vt.id)?"bg-primary/5":""}`,children:[e.jsx(wt,{children:e.jsx(ai,{checked:ro.has(Vt.id),onCheckedChange:()=>$a(Vt.id),"aria-label":`Select ${Vt.name}`})}),e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>sr(Vt),className:"text-primary hover:underline font-medium text-left",children:Vt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Vt.email})]})}),e.jsx(wt,{className:"text-muted-foreground",children:Vt.brokerage_name||"—"}),e.jsx(wt,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const Nn=Vt.trial_expires_at||Vt.subscription_end_date;if((Vt.is_trial||Vt.subscription_status==="trialing")&&Nn){const na=Math.ceil((new Date(Nn).getTime()-Date.now())/864e5),Wr=na<=0,Ca=na<=3;return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($e,{variant:"outline",className:Pt("w-fit",Wr?"border-destructive text-destructive":Ca?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:Wr?"Trial Expired":`Trial · ${na}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 gi="https://dashboard.relevelup.com/upgrade";try{await navigator.clipboard.writeText(gi),i({title:"Upgrade link copied",description:gi})}catch{window.prompt("Copy this upgrade link:",gi)}},children:e.jsx(Za,{className:"h-3.5 w-3.5"})})]})}return e.jsx($e,{variant:Vt.claimed?"default":"secondary",className:Vt.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:Vt.claimed?"Active":"Pending"})})()})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex flex-col",children:[Vt.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:Vt.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),Vt.roles.includes("assistant")&&Mh[Vt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",Mh[Vt.id].agent_name||Mh[Vt.id].agent_email]})]})}),e.jsx(wt,{className:"text-muted-foreground",children:Vt.last_sign_in_at?new Date(Vt.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(wt,{className:"text-muted-foreground",children:Vt.created_at?new Date(Vt.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:()=>{Bc(Vt),Hi(!0)},title:"Send celebration",children:e.jsx(kx,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>sr(Vt),title:"Edit member",children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>fo(Vt.id,Vt.email),disabled:cc===Vt.id,title:"Sync phone with GHL",children:cc===Vt.id?e.jsx(Ct,{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(Vt.id),title:"Resend welcome email",children:e.jsx(pn,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>ao(Vt.email,Vt.name),title:"Send password reset",children:e.jsx(VI,{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(Vt.id),disabled:a||Vt.id===(t==null?void 0:t.id),title:Vt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Vt.name}`,children:a?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):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:()=>ko(Vt.id,Vt.name),title:"Delete user",children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Vt.id))})]})}),gn>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 ",gn]}),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(Vt=>Math.max(1,Vt-1)),disabled:D===1,children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,gn)},(Vt,Nn)=>{let nr;return gn<=5||D<=3?nr=Nn+1:D>=gn-2?nr=gn-4+Nn:nr=D-2+Nn,e.jsx($,{variant:D===nr?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>O(nr),children:nr},nr)})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(Vt=>Math.min(gn,Vt+1)),disabled:D===gn,children:e.jsx(Di,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>O(gn),disabled:D===gn,children:"Last"})]})]})]}),e.jsx(Os,{open:ft,onOpenChange:gt,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Edit Member"}),e.jsx(Er,{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:es.name,onChange:Vt=>Ht({...es,name:Vt.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:es.email,onChange:Vt=>Ht({...es,email:Vt.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:es.phone,onChange:Vt=>Ht({...es,phone:Vt.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:es.brokerage_id||"none",onValueChange:Vt=>Ht({...es,brokerage_id:Vt==="none"?"":Vt}),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(Vt=>e.jsx(Ge,{value:Vt.id,children:Vt.name},Vt.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(Vt=>e.jsxs($e,{variant:"default",className:"gap-1",children:[e.jsx(Tf,{className:"h-3 w-3"}),Vt,Vt==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>cm(Ke.id,Vt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(mr,{className:"h-3 w-3"})})]},Vt)),Ke.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(ms,{onValueChange:Vt=>cm(Ke.id,Vt,"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"})]}),(gc.length>0||sg.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(Yn,{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(Ct,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[gc.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:"}),gc.map(Vt=>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:Vt.assistant_name}),e.jsx($e,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Vt.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Vt.permissions).filter(([,Nn])=>Nn).map(([Nn])=>e.jsx($e,{variant:"secondary",className:"text-[10px] capitalize",children:Nn},Nn))})]},Vt.id))]}),sg.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:"}),sg.map(Vt=>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:Vt.agent_name}),e.jsx($e,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Vt.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Vt.permissions).filter(([,Nn])=>Nn).map(([Nn])=>e.jsx($e,{variant:"secondary",className:"text-[10px] capitalize",children:Nn},Nn))})]},Vt.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(Vt=>{const Nn=Zo(Ke.tags,Vt.required_tags),nr=`${Ke.id}-${Vt.id}`,na=as===nr,Wr=Vt.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:Vt.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:Vt.name}),Wr&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:na?e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):Wr?e.jsx($e,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(jn,{checked:Nn,onCheckedChange:()=>vo(Ke.id,Vt,Nn)})})]},Vt.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:()=>et(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:Vt=>Ve(Vt.target.value)}),e.jsx($,{size:"sm",variant:"destructive",onClick:async()=>{await et(Ke.id,!0,ze),Ve("")},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(ca,{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(Cwt,{expiresAt:Ke.trial_expires_at}),!Ke.trial_expires_at&&Ke.subscription_status==="trialing"&&Ke.subscription_end_date&&e.jsx(Cwt,{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:()=>qa(Ke.id,7),disabled:Se,children:[e.jsx(vv,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>qa(Ke.id,14),disabled:Se,children:[e.jsx(vv,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>qa(Ke.id,30),disabled:Se,children:[e.jsx(vv,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs($,{size:"sm",variant:"default",onClick:()=>Gt(Ke.id),disabled:ht,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(u2,{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(ca,{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(Vt=>e.jsxs($,{size:"sm",variant:"outline",onClick:()=>en(Ke.id,Vt),disabled:Es,children:[e.jsx(vv,{className:"h-4 w-4 mr-1"}),Vt,"-day trial"]},Vt))})]})]}),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(Nr,{children:[e.jsx($,{variant:"outline",onClick:Xr,children:"Cancel"}),e.jsx($,{onClick:sa,children:"Save Changes"})]})]})}),e.jsxs(Qt,{value:"access",children:[c.length===0?e.jsx(je,{children:e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Et,{children:"Member Access Matrix"}),e.jsx(Vn,{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:Vt=>{R(Vt.target.value),O(1)},className:"pl-9"})]})]}),e.jsxs(Le,{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(Vt=>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:Vt.icon}),e.jsx("span",{className:"text-sm",children:Vt.name})]})},Vt.id))]})}),e.jsxs("tbody",{children:[Jn.map(Vt=>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:Vt.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Vt.email})]})}),c.map(Nn=>{const nr=Zo(Vt.tags,Nn.required_tags),na=`${Vt.id}-${Nn.id}`,Wr=as===na;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:Wr?e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(jn,{checked:nr,onCheckedChange:()=>vo(Vt.id,Nn,nr),disabled:Nn.required_tags.length===0})})},Nn.id)})]},Vt.id)),Jn.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"})})]})]})}),gn>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 ",Mn+1,"-",Math.min(ar,hn)," of ",hn," • Page ",D," of ",gn]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(Vt=>Math.max(1,Vt-1)),disabled:D===1,children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(Vt=>Math.min(gn,Vt+1)),disabled:D===gn,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(Qt,{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:Fd,onChange:Vt=>Nl(Vt.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter(Vt=>Vt.name.toLowerCase().includes(Fd.toLowerCase())).length," of ",u.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{const Vt=[];for(const gi of u){const Ia=m[gi.id]??[];for(const el of Ia){const zo=l.find(Pc=>Pc.id===el);if(zo){const Pc=(zo.name||"").trim().split(/\s+/),Eu=Pc[0]||"",iu=Pc.slice(1).join(" ")||"";Vt.push({firstName:Eu,lastName:iu,email:zo.email,brokerageName:gi.name})}}}if(Vt.length===0){i({title:"No managers found to export"});return}const nr=[["First Name","Last Name","Email","Brokerage Name"].join(","),...Vt.map(gi=>[gi.firstName,gi.lastName,gi.email,gi.brokerageName].map(Ia=>`"${(Ia||"").replace(/"/g,'""')}"`).join(","))].join(` `),na=new Blob([nr],{type:"text/csv"}),Wr=URL.createObjectURL(na),Ca=document.createElement("a");Ca.href=Wr,Ca.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,Ca.click(),URL.revokeObjectURL(Wr),i({title:`Exported ${Vt.length} managers`})},children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(Os,{open:Ut,onOpenChange:Ft,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(wi,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Create New Brokerage"}),e.jsx(Er,{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:is,onChange:Vt=>jt(Vt.target.value),maxLength:100})]})}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>Ft(!1),children:"Cancel"}),e.jsx($,{onClick:Gg,disabled:zs,children:zs?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:(()=>{const Vt=u.filter(Nn=>Nn.name.toLowerCase().includes(Fd.toLowerCase()));return Vt.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:Fd?"No brokerages match your search":"No brokerages found"})}):Vt.map(Nn=>{const nr=l.filter(gi=>gi.brokerage_id===Nn.id),Wr=(m[Nn.id]??[]).map(gi=>l.find(Ia=>Ia.id===gi)).filter(Boolean),Ca=nr.length;return e.jsxs(An,{className:"hover:bg-muted/30",children:[e.jsx(wt,{children:e.jsx("button",{onClick:()=>Fl(Nn),className:"text-primary hover:underline font-medium",children:Nn.name})}),e.jsx(wt,{children:Wr.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Wr.map(gi=>e.jsx($e,{variant:"secondary",className:"text-xs",children:gi.name},gi.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(wt,{children:[Ca," member",Ca!==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:()=>Wy(Nn),children:[e.jsx(Yn,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Fl(Nn),title:"Edit brokerage",children:e.jsx(pi,{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:()=>Vh(Nn),title:"Delete brokerage",children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Nn.id)})})()})]})}),e.jsx(Os,{open:gs,onOpenChange:Ss,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Edit Brokerage"}),e.jsx(Er,{children:"Update brokerage details and manage managers"})]}),Ds&&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:zt,onChange:Vt=>vs(Vt.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 Nn=(m[Ds.id]??[]).map(nr=>l.find(na=>na.id===nr)).filter(Boolean);return Nn.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):Nn.map(nr=>e.jsxs($e,{variant:"default",className:"gap-1",children:[e.jsx(Tf,{className:"h-3 w-3"}),nr.name,e.jsx("button",{onClick:()=>cm(nr.id,"brokerage_manager","remove",Ds.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(mr,{className:"h-3 w-3"})})]},nr.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(Gd,{open:Ho,onOpenChange:ti,children:[e.jsx(Wd,{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(Dd,{className:"w-full p-0",align:"start",children:e.jsxs(N2,{children:[e.jsx(k2,{placeholder:"Search by name or email..."}),e.jsxs(S2,{className:"max-h-[200px]",children:[e.jsx(C2,{children:"No members found."}),e.jsx(Rw,{children:(()=>{const Vt=new Set(m[Ds.id]??[]);return l.filter(Nn=>!Vt.has(Nn.id)&&(n||Nn.brokerage_id===Ds.id)).map(Nn=>e.jsxs(h1,{value:`${Nn.name} ${Nn.email}`,onSelect:()=>{Kd(Nn.id,Ds.id),ti(!1)},children:[Nn.name," (",Nn.email,")"]},Nn.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(Vt=>Vt.brokerage_id===Ds.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(Vt=>Vt.brokerage_id===Ds.id).map(Vt=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:Vt.name}),Vt.roles.includes("brokerage_manager")&&e.jsx($e,{variant:"outline",className:"text-xs",children:"Manager"})]},Vt.id))})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:Ol,children:"Cancel"}),e.jsx($,{onClick:fy,disabled:dn,children:dn?"Saving...":"Save Changes"})]})]})}),e.jsx(Os,{open:Cn,onOpenChange:Rr,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(Er,{children:['Are you sure you want to delete "',ia==null?void 0:ia.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 "',ia==null?void 0:ia.name,'"']}),e.jsxs("li",{children:["All ",l.filter(Vt=>Vt.brokerage_id===(ia==null?void 0:ia.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>Rr(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:cf,disabled:Br,children:Br?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(Os,{open:Wn,onOpenChange:Sn,children:e.jsxs(Fs,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(wi,{className:"h-5 w-5"}),"Manage ",Fn==null?void 0:Fn.name]}),e.jsx(Er,{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:Vt=>Tr(Vt.target.value),className:"pl-10 h-9"})]}),e.jsxs(Os,{open:Lr,onOpenChange:la,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(lc,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Add New Agent"}),e.jsxs(Er,{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:Xn.name,onChange:Vt=>wr({...Xn,name:Vt.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:Xn.email,onChange:Vt=>wr({...Xn,email:Vt.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:Xn.password,onChange:Vt=>wr({...Xn,password:Vt.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:Xn.phone,onChange:Vt=>wr({...Xn,phone:Vt.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:Ka,children:[e.jsx(us,{id:"agent-package",children:e.jsx(fs,{placeholder:"Select a package"})}),e.jsxs(hs,{children:[$i.map(Vt=>e.jsx(Ge,{value:Vt.id,children:Vt.name},Vt.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.":((au=$i.find(Vt=>Vt.id===xa))==null?void 0:au.description)||"Entitlements and the welcome email reflect this package."})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>la(!1),children:"Cancel"}),e.jsx($,{onClick:We,disabled:Bn,children:Bn?"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(Gd,{open:Yr,onOpenChange:Eo,children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":Yr,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(Dd,{className:"w-[300px] p-0",align:"start",children:e.jsxs(N2,{children:[e.jsx(k2,{placeholder:"Search users...",value:Th,onValueChange:rh}),e.jsxs(S2,{children:[e.jsx(C2,{children:"No users found."}),e.jsx(Rw,{children:Rt(Fn.id).filter(Vt=>Th===""||Vt.name.toLowerCase().includes(Th.toLowerCase())||Vt.email.toLowerCase().includes(Th.toLowerCase())).map(Vt=>e.jsxs(h1,{value:`${Vt.name} ${Vt.email}`,onSelect:()=>{xt(Vt.id,Fn.id),Eo(!1),rh("")},children:[Vt.name," (",Vt.email,")"]},Vt.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:Nt(Fn.id).length===0?e.jsx(An,{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"})}):Nt(Fn.id).map(Vt=>e.jsxs(An,{className:"hover:bg-muted/30",children:[e.jsx(wt,{className:"font-medium",children:Vt.name}),e.jsx(wt,{className:"text-muted-foreground",children:Vt.email}),e.jsx(wt,{children:Vt.claimed?e.jsx($e,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx($e,{variant:"secondary",children:"Pending"})}),e.jsx(wt,{children:Vt.roles.includes("brokerage_manager")?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(Tf,{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:[!Vt.claimed&&e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ba(Vt.id),title:"Resend welcome email",children:e.jsx(pn,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>gh(Vt.id),title:"Remove from brokerage",children:e.jsx(mr,{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(Vt.id),disabled:a||Vt.id===(t==null?void 0:t.id),title:Vt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Vt.name}`,children:a?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):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:()=>ko(Vt.id,Vt.name),title:"Delete user",children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Vt.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[ct(Fn.id).length," total member",ct(Fn.id).length!==1?"s":""," •",ct(Fn.id).filter(Vt=>Vt.roles.includes("brokerage_manager")).length," manager",ct(Fn.id).filter(Vt=>Vt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(Nr,{children:e.jsx($,{variant:"outline",onClick:ah,children:"Close"})})]})})]}),e.jsx(Qt,{value:"teams",children:e.jsx(Shn,{})}),e.jsx(Qt,{value:"trials",children:e.jsx(uhn,{})}),e.jsx(Qt,{value:"celebrations",children:e.jsx(dhn,{})}),e.jsx(Qt,{value:"deletions",children:e.jsx(mhn,{})})]})]}),e.jsx(bWt,{open:uo,onOpenChange:Tc,brokerages:u,onSuccess:ws}),zc&&e.jsx(_Wt,{open:Dr,onOpenChange:Vt=>{Hi(Vt),Vt||Bc(null)},userId:zc.id,userName:zc.name}),e.jsx(Chn,{open:Ne,onOpenChange:Be,recipients:l.filter(Vt=>ro.has(Vt.id)).map(Vt=>({id:Vt.id,name:Vt.name,email:Vt.email}))})]})};function Ehn(){const{toast:s}=Bi(),t=Zt(),[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}=st({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:v=[]}=st({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||[]}}),y=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===y.length?i(new Set):i(new Set(y.map(P=>P.id)))},A=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(Dm,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"})," Orphan members"]})}),e.jsx(Le,{children:e.jsx("div",{className:"text-3xl font-bold",children:g.length})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(wi,{className:"h-4 w-4"})," Selected"]})}),e.jsx(Le,{children:e.jsx("div",{className:"text-3xl font-bold",children:a.size})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(wn,{className:"h-4 w-4"})," Top email domains"]})}),e.jsx(Le,{children:e.jsx("div",{className:"text-3xl font-bold",children:b.length})})]})]}),b.length>0&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Domain suggestions"})}),e.jsx(Le,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(([P,R])=>{const D=v.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($e,{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:v.map(O=>e.jsx(Ge,{value:O.id,children:O.name},O.id))})]})]},P)})})})]}),e.jsxs(je,{children:[e.jsxs(St,{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:v.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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Assign ",a.size||""]})]})]}),e.jsx(Le,{children:x?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):y.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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{className:"w-10",children:e.jsx(ai,{checked:a.size===y.length&&y.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(fi,{children:y.map(P=>{const R=l[P.id]||"";return e.jsxs(An,{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:hu(new Date(P.created_at),{addSuffix:!0})}),e.jsx(wt,{children:e.jsx($e,{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:v.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:()=>A(P.id,R),children:c[P.id]?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):"Assign"})})]},P.id)})})]})})})]})]})})}const Thn=()=>{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:A,error:E}=await q.from("invite_codes").select("*").order("created_at",{ascending:!1});E?(ne.error("Failed to load invite codes"),console.error(E)):t(A||[]),r(!1)},x=async A=>{if(A.preventDefault(),!l.trim()){ne.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"?ne.error("This code already exists"):(ne.error("Failed to create invite code"),console.error(E)):(ne.success("Invite code created"),o(""),d(""),h(""),f(""),g()),i(!1)},v=async(A,E)=>{const{error:I}=await q.from("invite_codes").update({is_active:!E}).eq("id",A);I?ne.error("Failed to update code"):t(s.map(P=>P.id===A?{...P,is_active:!E}:P))},y=async A=>{const{error:E}=await q.from("invite_codes").delete().eq("id",A);E?ne.error("Failed to delete code"):(ne.success("Code deleted"),t(s.filter(I=>I.id!==A)))},b="https://dashboard.relevelup.com",w=A=>{const E=`${b}/join?code=${A}`;navigator.clipboard.writeText(E),ne.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(Dm,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Create New Code"}),e.jsxs(Vn,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:S})]})]}),e.jsx(Le,{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:A=>o(A.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:A=>d(A.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:A=>h(A.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:A=>f(A.target.value),className:"w-28"})]}),e.jsxs($,{type:"submit",disabled:a,children:[a?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Active Codes"})}),e.jsx(Le,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:s.map(A=>e.jsxs(An,{children:[e.jsx(wt,{className:"font-mono font-medium",children:A.code}),e.jsx(wt,{className:"text-muted-foreground",children:A.description||"—"}),e.jsxs(wt,{children:[A.uses_count,A.max_uses&&` / ${A.max_uses}`]}),e.jsx(wt,{children:A.trial_days?e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:[A.trial_days," days"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(wt,{className:"text-muted-foreground",children:Js(new Date(A.created_at),"MMM d, yyyy")}),e.jsx(wt,{children:e.jsx(jn,{checked:A.is_active,onCheckedChange:()=>v(A.id,A.is_active)})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>w(A.code),title:"Copy invite link",children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>y(A.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},A.id))})]})})]})]})})},bE=q;function nSr(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 Mhn(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}const Phn="https://dashboard.relevelup.com";function rSr(s,t){const r=`${typeof window<"u"&&window.location.hostname==="localhost"?window.location.origin:Phn}/live/${s}`;return t?`${r}?i=${t}`:r}function aSr(){const s=Zt(),t=st({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await bE.from("live_events").select("*").order("starts_at",{ascending:!1});if(l)throw l;return i||[]}}),n=mt({mutationFn:async i=>{var d;const{data:l}=await q.auth.getUser(),{data:o,error:c}=await bE.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"]}),ne.success("Live event created")},onError:i=>ne.error((i==null?void 0:i.message)||"Could not create event")}),r=mt({mutationFn:async({id:i,...l})=>{const{error:o}=await bE.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]}),ne.success("Saved")},onError:i=>ne.error((i==null?void 0:i.message)||"Could not save")}),a=mt({mutationFn:async i=>{const{error:l}=await bE.from("live_events").delete().eq("id",i);if(l)throw l},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),ne.success("Event deleted")},onError:i=>ne.error((i==null?void 0:i.message)||"Could not delete")});return{list:t,create:n,update:r,remove:a}}function iSr(s){return st({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await bE.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function oSr(s){return st({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await bE.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function lSr(s){const t=Zt(),n=st({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await bE.from("live_invites").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(l)throw l;return i||[]}}),r=mt({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 bE.from("live_invites").insert(o).select();if(d)throw d;return c||[]},onSuccess:i=>{t.invalidateQueries({queryKey:["live-invites",s]}),ne.success(`${i.length} invite link${i.length===1?"":"s"} created`)},onError:i=>ne.error((i==null?void 0:i.message)||"Could not create invites")}),a=mt({mutationFn:async i=>{const{error:l}=await bE.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 vie=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}},yK=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}}},Ihn=async(s,t)=>await vie("new_templates")?yK({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}),Lhn=async(s,t)=>yK({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),Rhn=async(s,t)=>await vie("new_events")?yK({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),Dhn=async(s,t)=>await vie("new_toolbox")?yK({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),OWe=async(s,t)=>await vie("new_social_swag")?yK({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}),Fhn=async(s,t)=>await vie("new_newsletters")?yK({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),ZBe=400;function Ohn(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 zhn(){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 Z=!1;return(async()=>{h(!0);try{const[X,ae,le]=await Promise.all([zhn(),Twt("event_registrations",n.id),Twt("event_attendees",n.id)]);if(Z)return;f(X),x(ae),y(le)}catch(X){Z||r({title:"Could not load audience",description:X instanceof Error?X.message:"Unknown error",variant:"destructive"})}finally{Z||h(!1)}})(),()=>{Z=!0}},[s,n,r]),j.useEffect(()=>{s||(A(null),d(""),o(""),i("not_registered"))},[s]);const D=j.useMemo(()=>a==="all"?m:a==="not_registered"?m.filter(Z=>!g.has(Z.id)):m.filter(Z=>g.has(Z.id)&&!v.has(Z.id)),[a,m,g,v]),O={all:m.length,not_registered:m.filter(Z=>!g.has(Z.id)).length,registered_never_attended:m.filter(Z=>g.has(Z.id)&&!v.has(Z.id)).length},U=async(Z,X=!1)=>{const{data:{session:ae}}=await q.auth.getSession(),le=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:Z.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})}),re=await le.json().catch(()=>({}));if(!le.ok)throw new Error((re==null?void 0:re.error)||`HTTP ${le.status}`);return{sent:(re==null?void 0:re.sent)??0,failed:(re==null?void 0:re.failed)??0,alreadyInvited:(re==null?void 0:re.already_invited)??0}},W=async()=>{var Z;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 le=await U([{id:ae.id,name:((Z=ae.user_metadata)==null?void 0:Z.name)||"",email:ae.email}],!0);r({title:"Test sent",description:`Sent to ${ae.email} · Sent: ${le.sent} · Failed: ${le.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),A({done:0,total:D.length,sent:0,failed:0});try{let Z=0,X=0,ae=0;for(let le=0;le!b&&t(Z),children:e.jsxs(Fs,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-5 w-5 text-primary"}),"Invite Members to Event"]}),e.jsx(Er,{children:n?e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Su,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Ohn(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(Yn,{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(Ct,{className:"h-4 w-4 animate-spin"})," Loading members..."]}):e.jsxs(yw,{value:a,onValueChange:Z=>i(Z),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(Km,{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(Km,{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(Km,{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:Z=>o(Z.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:Z=>d(Z.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(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Sending test..."]}):e.jsxs(e.Fragment,{children:[e.jsx(pn,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"})," Send to ",D.length.toLocaleString()]})})]})]})}),e.jsx(fc,{open:E,onOpenChange:I,children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Send event invite?"}),e.jsxs(ic,{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(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsxs(Yl,{onClick:V,children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const Rde={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 $hn(){const s=Zn(),t=Zt(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState(Rde),[c,d]=j.useState(null),[u,h]=j.useState(null),[m,f]=j.useState(!1),g=j.useRef(null),[x,v]=j.useState(!1),[y,b]=j.useState(null),[w,S]=j.useState(!1),[A,E]=j.useState(null),[I,P]=j.useState(null),[R,D]=j.useState(!0),[O,U]=j.useState(""),[W,V]=j.useState(!1),[G,Z]=j.useState(null),{data:X,isLoading:ae}=st({queryKey:["admin-events"],queryFn:async()=>{const{data:Ke,error:Je}=await q.from("events").select("*").order("event_date",{ascending:!0});if(Je)throw Je;return Ke}}),{data:le}=st({queryKey:["event-registrations-count"],queryFn:async()=>{let Ke=[],Je=0;const ft=1e3;for(;;){const{data:es,error:Ht}=await q.from("event_registrations").select("event_id").range(Je,Je+ft-1);if(Ht)throw Ht;if(!es||es.length===0||(Ke=Ke.concat(es),es.length{gt[es.event_id]=(gt[es.event_id]||0)+1}),gt}}),{data:re,isLoading:te}=st({queryKey:["event-registrations-details",y==null?void 0:y.id],queryFn:async()=>{if(!y)return[];const{data:Ke,error:Je}=await q.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",y.id).order("registered_at",{ascending:!1});if(Je)throw Je;if(!Ke||Ke.length===0)return[];const ft=Ke.map(Ht=>Ht.user_id).filter(Boolean);let gt=[];if(ft.length>0){const{data:Ht,error:as}=await q.from("profiles").select("id, name, email").in("id",ft);if(as)throw as;gt=Ht||[]}const es=new Map((gt==null?void 0:gt.map(Ht=>[Ht.id,Ht]))||[]);return Ke.map(Ht=>({...Ht,profiles:Ht.user_id&&es.get(Ht.user_id)||null}))},enabled:!!y}),{data:J,isLoading:ce}=st({queryKey:["event-attendees-details",y==null?void 0:y.id],queryFn:async()=>{if(!y)return[];const{data:Ke,error:Je}=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",y.id).order("created_at",{ascending:!1});if(Je)throw Je;if(!Ke||Ke.length===0)return[];const ft=Ke.map(bs=>bs.user_id).filter(Boolean);let gt=[];if(ft.length>0){const{data:bs,error:Ut}=await q.from("profiles").select("id, name, email").in("id",ft);if(Ut)throw Ut;gt=bs||[]}const{data:es}=await q.from("agent_points").select("user_id").eq("event_id",y.id),Ht=new Set((es==null?void 0:es.map(bs=>bs.user_id))||[]),as=new Map((gt==null?void 0:gt.map(bs=>[bs.id,bs]))||[]);return Ke.map(bs=>({...bs,profiles:bs.user_id&&as.get(bs.user_id)||null,points_awarded:bs.user_id?Ht.has(bs.user_id):!1}))},enabled:!!y}),ve=Ke=>{b(Ke),v(!0)},fe=mt({mutationFn:async Ke=>{const{data:{session:Je}}=await q.auth.getSession();if(!Je)throw new Error("Not authenticated");const ft=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Je.access_token}`},body:JSON.stringify({event_id:Ke})}),gt=await ft.json();if(!ft.ok){const es=new Error(gt.error||"Failed to sync");throw es.scopeError=!!gt.scope_error,es.details=gt.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,es}return gt},onSuccess:Ke=>{if(t.invalidateQueries({queryKey:["event-registrations-details",y==null?void 0:y.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),Ke!=null&&Ke.scope_error||(Ke==null?void 0:Ke.success)===!1){ne.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}ne.success(Ke.message)},onError:Ke=>{ne.error("Failed to sync Zoom registrations",{description:Ke.scopeError&&Ke.details||Ke.message,duration:Ke.scopeError?2e4:5e3})}}),ue=mt({mutationFn:async Ke=>{const{data:{session:Je}}=await q.auth.getSession();if(!Je)throw new Error("Not authenticated");const ft=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Je.access_token}`},body:JSON.stringify({event_id:Ke})}),gt=await ft.json();if(!ft.ok)throw new Error(gt.error||"Failed to sync attendees");return gt},onSuccess:Ke=>{if(t.invalidateQueries({queryKey:["event-attendees-details",y==null?void 0:y.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),Ke!=null&&Ke.scope_error||(Ke==null?void 0:Ke.success)===!1){ne.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?ne.success(Ke.message):ne.success(`Synced ${Ke.synced||0} attendees. ${Ke.points_awarded||0} points awarded!`)},onError:Ke=>{ne.error("Failed to sync attendees: "+Ke.message)}}),be=mt({mutationFn:async()=>{const{data:Ke,error:Je}=await q.functions.invoke("zoom-retry-registrations",{body:{}});if(Je)throw Je;return Ke},onSuccess:Ke=>{t.invalidateQueries({queryKey:["event-registrations-details",y==null?void 0:y.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ne.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=>{ne.error("Retry failed: "+Ke.message)}}),Ee=mt({mutationFn:async({eventId:Ke,testMode:Je})=>{const{data:{session:ft}}=await q.auth.getSession();if(!ft)throw new Error("Not authenticated");const gt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ft.access_token}`},body:JSON.stringify({event_id:Ke,test_mode:Je})}),es=await gt.json();if(!gt.ok)throw new Error(es.error||"Failed to send reminders");return es},onSuccess:Ke=>{Ke.test?ne.success(Ke.message||"Test email sent!"):ne.success(Ke.message||`Reminder emails sent to ${Ke.sent} registrants!`)},onError:Ke=>{ne.error("Failed to send reminders: "+Ke.message)}}),{data:ke}=st({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let Ke=[],Je=0;const ft=1e3;for(;;){const{data:gt,error:es}=await q.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(Je,Je+ft-1);if(es)throw es;if(!gt||gt.length===0||(Ke=[...Ke,...gt],gt.length{const{error:es}=await q.from("event_attendees").update({user_id:Je}).eq("id",Ke);if(es)throw es;if(gt&&ft){const{error:as}=await q.from("zoom_email_aliases").upsert({user_id:Je,zoom_email:ft.toLowerCase()},{onConflict:"zoom_email"});as&&console.error("Failed to save alias:",as)}const Ht=y==null?void 0:y.id;if(Ht){const{data:as}=await q.from("user_roles").select("id").eq("user_id",Je).eq("role","admin").single();if(!as){const{data:bs}=await q.from("agent_points").select("id").eq("user_id",Je).eq("event_id",Ht).single();bs||(await q.rpc("award_attendance_points",{p_user_id:Je,p_event_id:Ht,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await q.rpc("check_and_award_badges",{p_user_id:Je}))}}return{userId:Je,zoomEmail:ft,shouldSaveAlias:gt}},onSuccess:Ke=>{t.invalidateQueries({queryKey:["event-attendees-details",y==null?void 0:y.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let Je="Attendee linked and points awarded!";Ke.shouldSaveAlias&&Ke.zoomEmail&&(Je+=` Email "${Ke.zoomEmail}" will be auto-matched in the future.`),ne.success(Je),S(!1),E(null),P(null),U("")},onError:Ke=>{ne.error("Failed to link attendee: "+Ke.message)}}),Fe=Ke=>{E(Ke),P(null),D(!0),U(""),S(!0)},Ne=()=>{!A||!I||Ie.mutate({attendeeId:A.id,userId:I,zoomEmail:A.zoom_email,shouldSaveAlias:R})},Be=(ke==null?void 0:ke.filter(Ke=>{var ft,gt;if(!O)return!0;const Je=O.toLowerCase();return((ft=Ke.name)==null?void 0:ft.toLowerCase().includes(Je))||((gt=Ke.email)==null?void 0:gt.toLowerCase().includes(Je))}))||[],Se=async Ke=>{const Je=Ke.name.split(".").pop(),gt=`${`${crypto.randomUUID()}.${Je}`}`,{error:es}=await q.storage.from("event-images").upload(gt,Ke);if(es)throw es;const{data:{publicUrl:Ht}}=q.storage.from("event-images").getPublicUrl(gt);return Ht},Ae=Ke=>{var ft;const Je=(ft=Ke.target.files)==null?void 0:ft[0];if(Je){if(Je.size>5*1024*1024){ne.error("Image must be less than 5MB");return}d(Je),h(URL.createObjectURL(Je))}},Ce=()=>{d(null),h(null),o({...l,image_url:""}),g.current&&(g.current.value="")},qe=mt({mutationFn:async Ke=>{f(!0);let Je=Ke.image_url;c&&(Je=await Se(c)||"");const ft=new Date(Ke.event_date),[gt,es]=Ke.event_time.split(":");ft.setHours(parseInt(gt),parseInt(es));const Ht=[new Date(ft)];if(Ke.is_recurring&&Ke.recurrence_end_date){let Ft=new Date(ft);for(;Ke.recurrence_pattern==="weekly"?Ft=s8(Ft,1):Ke.recurrence_pattern==="biweekly"?Ft=s8(Ft,2):Ft=Av(Ft,1),!(Ft>Ke.recurrence_end_date);)Ht.push(new Date(Ft))}const as=Ht.map(Ft=>({title:Ke.title,description:Ke.description||null,image_url:Je||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:bs,error:Ut}=await q.from("events").insert(as).select();if(Ut)throw Ut;return bs&&bs.length>0&&Rhn(Ke.title,bs[0].id),Ht.length},onSuccess:Ke=>{t.invalidateQueries({queryKey:["admin-events"]}),ne.success(Ke>1?`${Ke} recurring events created successfully`:"Event created successfully"),r(!1),o(Rde),d(null),h(null),f(!1)},onError:Ke=>{ne.error("Failed to create event: "+Ke.message),f(!1)}}),ze=mt({mutationFn:async({id:Ke,data:Je})=>{f(!0);let ft=Je.image_url;c&&(ft=await Se(c)||"");const gt=new Date(Je.event_date),[es,Ht]=Je.event_time.split(":");gt.setHours(parseInt(es),parseInt(Ht));const{error:as}=await q.from("events").update({title:Je.title,description:Je.description||null,image_url:ft||null,video_url:Je.video_url||null,event_date:gt.toISOString(),zoom_link:Je.zoom_link,zoom_meeting_id:Je.zoom_meeting_id||null,capacity:Je.capacity?parseInt(Je.capacity):null,is_published:Je.is_published}).eq("id",Ke);if(as)throw as},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ne.success("Event updated successfully"),r(!1),i(null),o(Rde),d(null),h(null),f(!1)},onError:Ke=>{ne.error("Failed to update event: "+Ke.message),f(!1)}}),Ve=mt({mutationFn:async Ke=>{const{error:Je}=await q.from("events").delete().eq("id",Ke);if(Je)throw Je},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ne.success("Event deleted successfully")},onError:Ke=>{ne.error("Failed to delete event: "+Ke.message)}}),ht=mt({mutationFn:async Ke=>{var Ft;const{data:Je}=await q.auth.getUser(),ft=new Date(Ke.event_date),gt=new Date(ft.getTime()+60*60*1e3),es=Mhn(Ke.title),Ht=Math.random().toString(36).slice(2,7),as=`${es}-${Ht}`,{data:bs,error:Ut}=await q.from("live_events").insert({slug:as,title:Ke.title,description:Ke.description||null,hero_image_url:Ke.image_url||null,starts_at:Ke.event_date,ends_at:gt.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=Je.user)==null?void 0:Ft.id,agenda:[],offer_bullets:[]}).select().single();if(Ut)throw Ut;return bs},onSuccess:Ke=>{t.invalidateQueries({queryKey:["live-events"]}),ne.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${Ke.id}`)},onError:Ke=>{ne.error("Failed to clone to LevelUp Live: "+Ke.message)}}),Qe=Ke=>{var ft;const Je=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:Je,event_time:Js(Je,"HH:mm"),zoom_link:Ke.zoom_link,zoom_meeting_id:Ke.zoom_meeting_id||"",capacity:((ft=Ke.capacity)==null?void 0:ft.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)},at=Ke=>{if(Ke.preventDefault(),!l.event_date){ne.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){ne.error("Please select an end date for recurring events");return}a?ze.mutate({id:a.id,data:l}):qe.mutate(l)},rt=()=>{r(!1),i(null),o(Rde),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(Dm,{title:"Event Management",description:"Create and manage upcoming events"}),e.jsxs(je,{className:"mb-6",children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsx(Et,{children:"All Events"}),e.jsxs(Os,{open:n,onOpenChange:Ke=>!Ke&&rt(),children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:()=>r(!0),children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:at,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(kk,{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(mr,{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(Gd,{children:[e.jsx(Wd,{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(Ea,{className:"mr-2 h-4 w-4"}),l.event_date?Js(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(Dd,{className:"w-auto p-0",align:"start",children:e.jsx(A2,{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(DE,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(jn,{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(Gd,{children:[e.jsx(Wd,{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(Ea,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?Js(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(Dd,{className:"w-auto p-0",align:"start",children:e.jsx(A2,{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,Je=new Date(l.event_date);for(;Je=l.recurrence_pattern==="weekly"?s8(Je,1):l.recurrence_pattern==="biweekly"?s8(Je,2):Av(Je,1),!(Je>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(jn,{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:rt,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(Le,{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,Je=[...X||[]],ft=Je.filter(bs=>new Date(bs.event_date)>=Ke).sort((bs,Ut)=>new Date(bs.event_date).getTime()-new Date(Ut.event_date).getTime()),gt=Je.filter(bs=>new Date(bs.event_date)new Date(Ut.event_date).getTime()-new Date(bs.event_date).getTime()),es=ft[0],Ht=bs=>e.jsxs(An,{children:[e.jsx(wt,{className:"font-medium",children:bs.title}),e.jsx(wt,{className:"whitespace-nowrap",children:Js(new Date(bs.event_date),"PPP p")}),e.jsx(wt,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>ve(bs),children:[e.jsx(Yn,{className:"h-4 w-4"}),(le==null?void 0:le[bs.id])||0,bs.capacity&&` / ${bs.capacity}`]})}),e.jsx(wt,{children:e.jsx("span",{className:Pt("px-2 py-1 rounded-full text-xs font-medium",bs.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:bs.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:()=>{Z(bs),V(!0)},title:"Send invite email to members",children:[e.jsx(Zr,{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:()=>ht.mutate(bs),disabled:ht.isPending,title:"Clone to LevelUp Live",children:[e.jsx(bb,{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(bs.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(Ir,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Qe(bs),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await mo("Are you sure you want to delete this event?")&&Ve.mutate(bs.id)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},bs.id),as=(bs,Ut)=>bs.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:Ut}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:bs.map(Ht)})]});return e.jsxs("div",{className:"space-y-6",children:[es&&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(ca,{className:"h-3.5 w-3.5"}),"Next Upcoming Event"]}),e.jsx("h3",{className:"text-xl font-bold truncate",children:es.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Js(new Date(es.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(le==null?void 0:le[es.id])||0," registered",es.capacity?` of ${es.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>{Z(es),V(!0)},children:[e.jsx(Zr,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>ve(es),children:[e.jsx(Yn,{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:()=>ht.mutate(es),disabled:ht.isPending,children:[e.jsx(bb,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open(es.zoom_link,"_blank"),children:[e.jsx(Ir,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs(pa,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"upcoming",className:"gap-2",children:[e.jsx(ca,{className:"h-4 w-4"}),"Upcoming",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:ft.length})]}),e.jsxs(Xt,{value:"past",className:"gap-2",children:[e.jsx(Vr,{className:"h-4 w-4"}),"Past",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:gt.length})]})]}),e.jsx(Qt,{value:"upcoming",className:"mt-4",children:as(ft,"No upcoming events scheduled.")}),e.jsx(Qt,{value:"past",className:"mt-4",children:as(gt,"No past events.")})]})]})})()})]}),e.jsx(Bhn,{open:W,onOpenChange:V,event:G}),e.jsx(Os,{open:x,onOpenChange:v,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),y==null?void 0:y.title]}),e.jsx(Er,{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:y.id,testMode:!0}),disabled:Ee.isPending,children:[e.jsx(pn,{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:y.id}),disabled:Ee.isPending||!(re!=null&&re.length),children:[e.jsx(pn,{className:Pt("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),Ee.isPending?"Sending...":"Send Reminder to All"]}),(y==null?void 0:y.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>fe.mutate(y.id),disabled:fe.isPending,children:[e.jsx(co,{className:Pt("h-4 w-4 mr-2",fe.isPending&&"animate-spin")}),fe.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>be.mutate(),disabled:be.isPending,children:[e.jsx(co,{className:Pt("h-4 w-4 mr-2",be.isPending&&"animate-spin")}),be.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs($,{variant:"default",size:"sm",onClick:()=>ue.mutate(y.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(pa,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(ga,{className:"grid w-full grid-cols-2",children:[e.jsxs(Xt,{value:"registrations",className:"gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Registrations (",(re==null?void 0:re.length)||0,")"]}),e.jsxs(Xt,{value:"attendees",className:"gap-2",children:[e.jsx(Vr,{className:"h-4 w-4"}),"Attendees (",(J==null?void 0:J.length)||0,")"]})]}),e.jsx(Qt,{value:"registrations",className:"mt-4",children:te?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(re==null?void 0:re.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(y==null?void 0:y.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Registered"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(fi,{children:re==null?void 0:re.map(Ke=>{var es,Ht;const Je=((es=Ke.profiles)==null?void 0:es.name)||Ke.zoom_name||"Unknown",ft=((Ht=Ke.profiles)==null?void 0:Ht.email)||Ke.zoom_email||null,gt=!Ke.user_id;return e.jsxs(An,{children:[e.jsx(wt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Je,gt&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(wt,{children:ft?e.jsxs("a",{href:`mailto:${ft}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(pn,{className:"h-3 w-3"}),ft]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(wt,{className:"text-muted-foreground text-sm",children:Js(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(Qt,{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."}),(y==null?void 0:y.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(vl,{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(nu,{className:"h-3 w-3"}),"Link to Profile"]})]},Ke.id))})]}),e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Duration"}),e.jsx(Dt,{children:"Points"})]})}),e.jsx(fi,{children:J==null?void 0:J.filter(Ke=>Ke.user_id).map(Ke=>{var gt,es;const Je=((gt=Ke.profiles)==null?void 0:gt.name)||Ke.zoom_name||"Unknown",ft=((es=Ke.profiles)==null?void 0:es.email)||Ke.zoom_email||null;return e.jsxs(An,{children:[e.jsx(wt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Je,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:ft?e.jsxs("a",{href:`mailto:${ft}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(pn,{className:"h-3 w-3"}),ft]}):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(ca,{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(Os,{open:w,onOpenChange:S,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(nu,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(Er,{children:"Link this Zoom attendee to an existing member profile to award them points."})]}),A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-3 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium",children:A.zoom_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:A.zoom_email||"No email"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:Be.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:Be.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))})}),A.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:Ne,disabled:!I||Ie.isPending,children:Ie.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const Uhn={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 qhn(){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(Dm,{title:"MCP Audit Log",description:"Recent LevelUp MCP tool calls — ChatGPT / Claude / Codex activity, denials, and rate limits."}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Qq,{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(co,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(Le,{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($e,{className:Uhn[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 Vhn({selectedKitIds:s,onChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l=[]}=st({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(ym,{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($e,{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(mr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(Gd,{open:a,onOpenChange:i,children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(ym,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(Dd,{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(ym,{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 Hhn=()=>{const{user:s}=_s(),{toast:t}=Bi(),n=Zt(),[r,a]=Nc(),[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,v]=j.useState(!1),[y,b]=j.useState(null),[w,S]=j.useState(""),[A,E]=j.useState([]),[I,P]=j.useState(""),[R,D]=j.useState(""),[O,U]=j.useState(!1),[W,V]=j.useState(!1),{data:G=[]}=st({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:Z=[]}=st({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}=st({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:Ve}=await q.from("template_links").select("*").order("sort_order");if(Ve)throw Ve;const{data:ht,error:Qe}=await q.from("template_guides").select("*").order("sort_order");if(Qe)throw Qe;return Ce.map(rt=>({...rt,links:(ze==null?void 0:ze.filter(Ke=>Ke.template_id===rt.id))||[],guides:(ht==null?void 0:ht.filter(Ke=>Ke.template_id===rt.id))||[]}))}});j.useEffect(()=>{const Ce=r.get("edit");if(Ce&&X.length>0){const qe=X.find(ze=>ze.id===Ce);qe&&(fe(qe),a({},{replace:!0}))}},[X,r]);const le=mt({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"})}}),re=mt({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=mt({mutationFn:async Ce=>{var Qe;let qe=Ce.existingImageUrl;if(Ce.image){const at=Ce.image.name.split(".").pop(),rt=`${Date.now()}-${Math.random().toString(36).substring(7)}.${at}`,{error:Ke}=await q.storage.from("template-previews").upload(rt,Ce.image);if(Ke)throw Ke;const{data:Je}=q.storage.from("template-previews").getPublicUrl(rt);qe=Je.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 Ve=Ce.templateId;if(Ve){const{error:at}=await q.from("canva_templates").update(ze).eq("id",Ve);if(at)throw at;const{error:rt}=await q.from("template_links").delete().eq("template_id",Ve);if(rt)throw rt;const Ke=((Qe=Ce.existingGuides)==null?void 0:Qe.map(gt=>gt.id).filter(Boolean))||[],Je=Ce.template.guides.map(gt=>gt.id).filter(Boolean),ft=Ke.filter(gt=>!Je.includes(gt));ft.length>0&&await q.from("template_guides").delete().in("id",ft)}else{const{data:at,error:rt}=await q.from("canva_templates").insert(ze).select().single();if(rt)throw rt;Ve=at.id,Ihn(Ce.template.name,at.id)}const ht=Ce.template.links.filter(at=>at.title.trim()&&at.canva_share_link.trim());if(ht.length>0){const at=ht.map((Ke,Je)=>({template_id:Ve,title:Ke.title.trim(),canva_share_link:Ke.canva_share_link.trim(),sort_order:Je})),{error:rt}=await q.from("template_links").insert(at);if(rt)throw rt}for(let at=0;at0)){const{error:at}=await q.from("resource_kit_templates").insert(Ce.linkedKitIds.map(rt=>({template_id:Ve,kit_id:rt})));if(at)throw at}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),ve(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Ce=>{t({title:"Error saving template",description:Ce.message,variant:"destructive"})}}),J=mt({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=mt({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"})}}),ve=()=>{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),v(!1),E([])},fe=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(Ve=>({id:Ve.id,title:Ve.title,canva_share_link:Ve.canva_share_link,sort_order:Ve.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((ze=Ce.guides)==null?void 0:ze.map(Ve=>({id:Ve.id,name:Ve.name,file_url:Ve.file_url,file_type:Ve.file_type,file_size:Ve.file_size,sort_order:Ve.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(Ve=>Ve.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)))},be=()=>{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,Ve)=>Ve!==Ce);u({...d,links:qe})},ke=(Ce,qe,ze)=>{const Ve=[...d.links];Ve[Ce]={...Ve[Ce],[qe]:ze},u({...d,links:Ve})},Ie=Ce=>{const qe=Ce.target.files;if(!qe)return;const ze=Array.from(qe).map((Ve,ht)=>({name:Ve.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:Ve.type,file_size:Ve.size,sort_order:d.guides.length+ht,file:Ve}));u({...d,guides:[...d.guides,...ze]}),Ce.target.value=""},Fe=Ce=>{const qe=d.guides.filter((ze,Ve)=>Ve!==Ce);u({...d,guides:qe})},Ne=(Ce,qe)=>{const ze=[...d.guides];ze[Ce]={...ze[Ce],name:qe},u({...d,guides:ze})},Be=async()=>{if(!h)return null;v(!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:Ve}=Ce,{data:ht,error:Qe}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ze}});if(Qe)throw new Error(Qe.message);const at=new XMLHttpRequest;return await new Promise((Ke,Je)=>{at.upload.addEventListener("progress",ft=>{if(ft.lengthComputable){const gt=Math.round(ft.loaded/ft.total*100);g(gt)}}),at.addEventListener("load",()=>{at.status>=200&&at.status<300?Ke():Je(new Error(`Upload failed with status ${at.status}`))}),at.addEventListener("error",()=>Je(new Error("Upload failed"))),at.open("PUT",ht.uploadUrl),at.setRequestHeader("AccessKey",ht.apiKey),at.send(h)}),`https://player.mediadelivery.net/embed/${Ve}/${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{v(!1)}},Se=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(Ve=>Ve.title.trim()&&Ve.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 Ve=await Be();if(!Ve)return;ze=Ve}te.mutate({template:d,image:y,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:A})};return e.jsx(Vs,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Dm,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:X.length})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:G.length})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:Z.length})})]})]}),e.jsxs(Os,{open:i,onOpenChange:Ce=>{l(Ce),Ce||ve()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(cn,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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(kk,{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:be,className:"gap-1",children:[e.jsx(cn,{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=>ke(qe,"title",ze.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(pe,{value:Ce.canva_share_link,onChange:ze=>ke(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(mr,{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()&&le.mutate(I.trim()),disabled:le.isPending,children:"Add"}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:()=>{U(!1),P("")},children:e.jsx(mr,{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(cn,{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()&&re.mutate(R.trim()),disabled:re.isPending,children:"Add"}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:()=>{V(!1),D("")},children:e.jsx(mr,{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:Z.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(cn,{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(mr,{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(Hc,{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(fa,{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(Ct,{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(fa,{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(mr,{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:Se,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(fa,{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:Ie,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(Qr,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(pe,{value:Ce.name,onChange:ze=>Ne(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(mr,{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(Vhn,{selectedKitIds:A,onChange:E}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>{l(!1),ve()},children:"Cancel"}),e.jsx($,{type:"submit",disabled:te.isPending,children:te.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(je,{children:e.jsx(Le,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:X.map(Ce=>{var qe,ze,Ve,ht,Qe;return e.jsxs(An,{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(Hc,{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($e,{variant:"secondary",children:[((qe=Ce.links)==null?void 0:qe.length)||0," link",(((ze=Ce.links)==null?void 0:ze.length)||0)!==1?"s":""]}),(((Ve=Ce.guides)==null?void 0:Ve.length)||0)>0&&e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(Qr,{className:"h-3 w-3"}),(ht=Ce.guides)==null?void 0:ht.length," guide",(((Qe=Ce.guides)==null?void 0:Qe.length)||0)!==1?"s":""]})]})}),e.jsx(wt,{children:Ce.category?e.jsx($e,{variant:"secondary",children:Ce.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(wt,{children:Ce.type?e.jsx($e,{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(ei,{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:()=>fe(Ce),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:async()=>{await mo("Delete this template?")&&J.mutate(Ce.id)},children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Ce.id)})})]})})})]})})};function CWt({selectedTemplateIds:s,onChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l=[]}=st({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(o2,{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($e,{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(mr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(Gd,{open:a,onOpenChange:i,children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(o2,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(Dd,{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(o2,{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 Ghn=[{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"}],Mwt=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),Pwt=s=>{const[t,n,r]=s.split(/[-/T]/);return`${Number(n)}/${Number(r)}/${t}`},Whn=()=>{const{user:s}=_s(),[t,n]=Nc(),{toast:r}=Bi(),a=Zt(),[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,v]=j.useState([]),[y,b]=j.useState([]),[w,S]=j.useState([]),[A,E]=j.useState([]),[I,P]=j.useState(""),[R,D]=j.useState(!1),[O,U]=j.useState(null),[W,V]=j.useState(0),[G,Z]=j.useState(!1),[X,ae]=j.useState(null),{data:le=[]}=st({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:re=[],isLoading:te}=st({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:Ve}=await q.from("academy_resources").select("*").order("sort_order");if(Ve)throw Ve;return Ce.map(Qe=>({...Qe,resources:(ze==null?void 0:ze.filter(at=>at.video_id===Qe.id))||[]}))}});j.useEffect(()=>{const Ce=t.get("edit");if(Ce&&re.length>0){const qe=re.find(ze=>ze.id===Ce);qe&&(ke(qe),n({},{replace:!0}))}},[re,t]);const J=mt({mutationFn:async Ce=>{const{data:qe,error:ze}=await q.from("academy_categories").insert({name:Ce,sort_order:le.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=mt({mutationFn:async Ce=>{let qe=Ce.existingThumbnailUrl;if(Ce.thumbnail){const ht=Ce.thumbnail.name.split(".").pop(),Qe=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${ht}`,{error:at}=await q.storage.from("academy-resources").upload(Qe,Ce.thumbnail);if(at)throw at;const{data:rt}=q.storage.from("academy-resources").getPublicUrl(Qe);qe=rt.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 Ve=Ce.videoId;if(Ve){const{error:ht}=await q.from("academy_videos").update(ze).eq("id",Ve);if(ht)throw ht}else{const{data:ht,error:Qe}=await q.from("academy_videos").insert(ze).select().single();if(Qe)throw Qe;Ve=ht.id,Lhn(Ce.video.title,ht.id)}if(Ce.resourcesToDelete.length>0){const{error:ht}=await q.from("academy_resources").delete().in("id",Ce.resourcesToDelete);if(ht)throw ht}for(let ht=0;ht0){const{error:ht}=await q.from("academy_video_templates").insert(A.map(Qe=>({video_id:Ve,template_id:Qe})));if(ht)throw ht}},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"})}}),ve=mt({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"})}}),fe=mt({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 ht=(Ce.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!qe){let at=ht;const{data:rt}=await q.from("academy_videos").select("id").eq("public_slug",at).maybeSingle();rt&&rt.id!==Ce.id&&(at=`${ht}-${Ce.id.slice(0,6)}`),qe=at}const{error:Qe}=await q.from("academy_videos").update({public_slug:qe,is_public:!0}).eq("id",Ce.id);if(Qe)throw Qe;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const Ve=`${window.location.origin}/watch/${qe}`;await navigator.clipboard.writeText(Ve),r({title:"Public link copied",description:Ve})}catch(qe){r({title:"Could not copy link",description:qe.message,variant:"destructive"})}},be=async Ce=>{if(!await mo("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(""),v([]),b([]),S([]),c(null),E([]),P(""),U(null),V(0),Z(!1),ae(null)},ke=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||[]),v([]),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)},Ie=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(Ve=>({file:Ve,title:Ve.name.replace(/\.[^/.]+$/,"")}));v([...x,...ze])}Ce.target.value=""},Ne=Ce=>{v(x.filter((qe,ze)=>ze!==Ce))},Be=Ce=>{S([...w,Ce]),b(y.filter(qe=>qe.id!==Ce))},Se=async()=>{if(!O)return null;Z(!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:Ve}=Ce;ae(ze);const{data:ht,error:Qe}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ze}});if(Qe)throw new Error(Qe.message);const at=new XMLHttpRequest;return await new Promise((Ke,Je)=>{at.upload.addEventListener("progress",ft=>{if(ft.lengthComputable){const gt=Math.round(ft.loaded/ft.total*100);V(gt)}}),at.addEventListener("load",()=>{at.status>=200&&at.status<300?Ke():Je(new Error(`Upload failed with status ${at.status}`))}),at.addEventListener("error",()=>Je(new Error("Upload failed"))),at.open("PUT",ht.uploadUrl),at.setRequestHeader("AccessKey",ht.apiKey),at.send(O)}),`https://player.mediadelivery.net/embed/${Ve}/${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{Z(!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 Se();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(Dm,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:re.length})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:re.filter(Ce=>Ce.is_published).length})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:re.filter(Ce=>Ce.is_public).length})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Total Public Views"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:re.reduce((Ce,qe)=>Ce+(qe.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(Os,{open:i,onOpenChange:Ce=>{l(Ce),Ce||Ee()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(cn,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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(kk,{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:Ghn.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(fa,{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(Ct,{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(mr,{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:le.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(cn,{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:Ie,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"})]})})]}),(y.length>0||x.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[y.map(Ce=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Qr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:Ce.title}),e.jsx($e,{variant:"outline",className:"text-xs",children:Ce.file_type}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>Be(Ce.id),className:"text-destructive hover:text-destructive",children:e.jsx(mr,{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(Qr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:Ce.title,onChange:ze=>{const Ve=[...x];Ve[qe].title=ze.target.value,v(Ve)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx($e,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>Ne(qe),className:"text-destructive hover:text-destructive",children:e.jsx(mr,{className:"h-4 w-4"})})]},qe))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(CWt,{selectedTemplateIds:A,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(jn,{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>Mwt?`Scheduled — goes live automatically on ${Pwt(d.publish_date)}.`:"Live now for members.":"Draft — hidden from members until you turn this on."})]}),e.jsxs(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):ce.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(je,{children:e.jsx(Le,{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"})}):re.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(fa,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:re.map(Ce=>e.jsxs(An,{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(fa,{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($e,{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($e,{variant:"secondary",children:[Ce.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(wt,{children:Pwt(Ce.publish_date)}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{checked:Ce.is_published,onCheckedChange:qe=>fe.mutate({id:Ce.id,is_published:qe})}),Ce.is_published?Ce.publish_date.slice(0,10)>Mwt?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(ca,{className:"h-3 w-3"})," Scheduled"]}):e.jsx($e,{variant:"secondary",children:"Live"}):e.jsx($e,{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(Ta,{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(Za,{className:"h-4 w-4 text-primary"}):e.jsx(Hd,{className:"h-4 w-4"})}),Ce.is_public&&e.jsx($,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>be(Ce),children:e.jsx(cl,{className:"h-4 w-4 text-emerald-500"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ke(Ce),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ve.mutate(Ce.id),className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Ce.id))})]})})})]})})},BZ=s=>s.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),Iwt={public_enabled:!1,public_slug:"",public_headline:"",public_subheadline:"",public_cta_text:"",public_benefits:"",public_hero_image_url:""};function Khn(){var ve,fe,ue;const s=Zt(),[t,n]=Nc(),[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,...Iwt}),[d,u]=j.useState(null),[h,m]=j.useState(""),[f,g]=j.useState([]),[x,v]=j.useState([]),[y,b]=j.useState([]),[w,S]=j.useState(null),{data:A,isLoading:E}=st({queryKey:["resource-kits"],queryFn:async()=>{const{data:be,error:Ee}=await q.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Ee)throw Ee;return be}}),{data:I}=st({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:be,error:Ee}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Ee)throw Ee;return be}}),{data:P}=st({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:be,error:Ee}=await q.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Ee)throw Ee;return be}}),{data:R}=st({queryKey:["resource-kit-leads"],queryFn:async()=>{const{data:be,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 be}});j.useEffect(()=>{const be=t.get("edit");if(be&&A&&A.length>0&&I&&P){const Ee=A.find(ke=>ke.id===be);Ee&&(O(Ee),n({},{replace:!0}))}},[A,I,P,t]);const D=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,...Iwt}),u(null),m(""),g([]),v([]),b([]),l(null)},O=async be=>{l(be),c({name:be.name,description:be.description||"",publish_date:be.publish_date.split("T")[0],is_published:be.is_published,public_enabled:!!be.public_enabled,public_slug:be.public_slug||"",public_headline:be.public_headline||"",public_subheadline:be.public_subheadline||"",public_cta_text:be.public_cta_text||"",public_benefits:Array.isArray(be.public_benefits)?be.public_benefits.join(` `):"",public_hero_image_url:be.public_hero_image_url||""}),m(be.featured_image_url||"");const Ee=(I==null?void 0:I.filter(Fe=>Fe.kit_id===be.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 ke=(P==null?void 0:P.filter(Fe=>Fe.kit_id===be.id))||[];v(ke.map(Fe=>({id:Fe.id,title:Fe.title,canva_share_link:Fe.canva_share_link,sort_order:Fe.sort_order})));const{data:Ie}=await q.from("resource_kit_templates").select("template_id").eq("kit_id",be.id);b((Ie||[]).map(Fe=>Fe.template_id)),a(!0)},U=be=>{var ke;const Ee=(ke=be.target.files)==null?void 0:ke[0];Ee&&(u(Ee),m(URL.createObjectURL(Ee)))},W=()=>{g([...f,{name:"",file_url:"",sort_order:f.length}])},V=be=>{g(f.filter((Ee,ke)=>ke!==be))},G=(be,Ee,ke)=>{const Ie=[...f];Ie[be]={...Ie[be],[Ee]:ke},g(Ie)},Z=()=>{v([...x,{title:"",canva_share_link:"",sort_order:x.length}])},X=be=>{v(x.filter((Ee,ke)=>ke!==be))},ae=(be,Ee,ke)=>{const Ie=[...x];Ie[be]={...Ie[be],[Ee]:ke},v(Ie)},le=(be,Ee)=>{var Ie;const ke=(Ie=Ee.target.files)==null?void 0:Ie[0];if(ke){const Fe=[...f],Ne=ke.name.replace(/\.[^/.]+$/,"");Fe[be]={...Fe[be],file:ke,file_type:ke.type,file_size:ke.size,name:Fe[be].name||Ne},g(Fe)}},re=mt({mutationFn:async()=>{let be=(i==null?void 0:i.featured_image_url)||null;if(d){const Be=d.name.split(".").pop(),Se=`${Date.now()}.${Be}`,{error:Ae}=await q.storage.from("resource-kits").upload(`featured/${Se}`,d);if(Ae)throw Ae;const{data:Ce}=q.storage.from("resource-kits").getPublicUrl(`featured/${Se}`);be=Ce.publicUrl}const Ee=o.public_enabled?o.public_slug?BZ(o.public_slug):BZ(o.name):o.public_slug?BZ(o.public_slug):null,ke={name:o.name,description:o.description||null,featured_image_url:be,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(Be=>Be.trim()).filter(Boolean),public_hero_image_url:o.public_hero_image_url||null};let Ie;const Fe=!i,Ne=(i==null?void 0:i.is_published)||!1;if(i){const{error:Be}=await q.from("resource_kits").update(ke).eq("id",i.id);if(Be)throw Be;Ie=i.id;const Se=(I==null?void 0:I.filter(ht=>ht.kit_id===i.id).map(ht=>ht.id))||[],Ae=f.filter(ht=>ht.id).map(ht=>ht.id),Ce=Se.filter(ht=>!Ae.includes(ht));Ce.length>0&&await q.from("resource_kit_files").delete().in("id",Ce);const qe=(P==null?void 0:P.filter(ht=>ht.kit_id===i.id).map(ht=>ht.id))||[],ze=x.filter(ht=>ht.id).map(ht=>ht.id),Ve=qe.filter(ht=>!ze.includes(ht));Ve.length>0&&await q.from("resource_kit_links").delete().in("id",Ve)}else{const{data:Be,error:Se}=await q.from("resource_kits").insert(ke).select().single();if(Se)throw Se;Ie=Be.id}for(let Be=0;Be0){const{error:Be}=await q.from("resource_kit_templates").insert(y.map(Se=>({kit_id:Ie,template_id:Se})));if(Be)throw Be}return{kitId:Ie,kitName:o.name,isNewKit:Fe,wasPublished:Ne,isPublished:o.is_published}},onSuccess:be=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),ne.success(i?"Resource kit updated":"Resource kit created"),be.isPublished&&(be.isNewKit||!be.wasPublished)&&Dhn(be.kitName,be.kitId),a(!1),D()},onError:be=>{ne.error("Failed to save resource kit: "+be.message)}}),te=mt({mutationFn:async be=>{const{error:Ee}=await q.from("resource_kits").delete().eq("id",be);if(Ee)throw Ee},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),ne.success("Resource kit deleted")},onError:be=>{ne.error("Failed to delete: "+be.message)}}),J=be=>{if(be.preventDefault(),!o.name){ne.error("Please enter a name");return}re.mutate()},ce=be=>(I==null?void 0:I.filter(Ee=>Ee.kit_id===be).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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(A==null?void 0:A.length)||0})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(A==null?void 0:A.filter(be=>be.is_published).length)||0})})]})]}),e.jsxs($,{onClick:()=>{D(),a(!0)},children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(je,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:E?e.jsx(An,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(A==null?void 0:A.length)===0?e.jsx(An,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):A==null?void 0:A.map(be=>e.jsxs(An,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[be.featured_image_url?e.jsx("img",{src:be.featured_image_url,alt:be.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(ym,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:be.name}),be.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:be.description})]})]})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Qr,{className:"h-4 w-4 text-muted-foreground"}),ce(be.id)]})}),e.jsx(wt,{children:Js(new Date(be.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 ${be.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:be.is_published?"Published":"Draft"})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[be.public_enabled&&be.public_slug&&e.jsx($,{variant:"ghost",size:"icon",title:"Copy public landing page link",onClick:()=>{navigator.clipboard.writeText(`${window.location.origin}/resources/${be.public_slug}`),ne.success("Public link copied")},children:e.jsx(cl,{className:"h-4 w-4 text-emerald-600"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{const Ee=(I==null?void 0:I.filter(Ie=>Ie.kit_id===be.id))||[],ke=(P==null?void 0:P.filter(Ie=>Ie.kit_id===be.id))||[];S({...be,files:Ee,links:ke})},children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>O(be),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await mo("Delete this resource kit?")&&te.mutate(be.id)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},be.id))})]})})}),e.jsxs(je,{className:"mt-6",children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Yn,{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(Le,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:R.map(be=>{var Ee;return e.jsxs(An,{children:[e.jsx(wt,{className:"font-medium",children:be.full_name}),e.jsx(wt,{children:be.email}),e.jsx(wt,{children:be.brokerage||"—"}),e.jsx(wt,{children:((Ee=A==null?void 0:A.find(ke=>ke.id===be.kit_id))==null?void 0:Ee.name)||"—"}),e.jsx(wt,{children:Js(new Date(be.created_at),"MMM d, yyyy")})]},be.id)})})]})})]}),e.jsx(Os,{open:r,onOpenChange:a,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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(ym,{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:be=>c({...o,name:be.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(kk,{content:o.description,onChange:be=>c({...o,description:be}),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:be=>c({...o,publish_date:be.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(jn,{checked:o.is_published,onCheckedChange:be=>c({...o,is_published:be})}),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(jn,{checked:o.public_enabled,onCheckedChange:be=>c({...o,public_enabled:be,public_slug:o.public_slug||BZ(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:be=>c({...o,public_slug:be.target.value}),placeholder:"listing-checklist"}),e.jsxs($,{type:"button",variant:"outline",onClick:()=>{const be=BZ(o.public_slug||o.name);navigator.clipboard.writeText(`${window.location.origin}/resources/${be}`),ne.success("Public link copied")},children:[e.jsx(Sd,{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:be=>c({...o,public_headline:be.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:be=>c({...o,public_subheadline:be.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:be=>c({...o,public_cta_text:be.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:be=>c({...o,public_hero_image_url:be.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:be=>c({...o,public_benefits:be.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(cn,{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((be,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(mr,{className:"h-4 w-4"})})]}),e.jsx(pe,{placeholder:"File name (e.g., Getting Started Guide)",value:be.name,onChange:ke=>G(Ee,"name",ke.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"file",onChange:ke=>le(Ee,ke),className:"flex-1"}),be.file_url&&!be.file&&e.jsx("a",{href:be.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),be.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:Z,children:[e.jsx(cn,{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((be,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(mr,{className:"h-4 w-4"})})]}),e.jsx(pe,{placeholder:"Link title (e.g., Social Media Post Template)",value:be.title,onChange:ke=>ae(Ee,"title",ke.target.value)}),e.jsx(pe,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:be.canva_share_link,onChange:ke=>ae(Ee,"canva_share_link",ke.target.value)})]},Ee))})]}),e.jsx(CWt,{selectedTemplateIds:y,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:re.isPending,children:re.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(Os,{open:!!w,onOpenChange:()=>S(null),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx($s,{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 (",((ve=w==null?void 0:w.files)==null?void 0:ve.length)||0,")"]}),((fe=w==null?void 0:w.files)==null?void 0:fe.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(be=>e.jsxs("a",{href:be.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(Qr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:be.name})]},be.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(be=>e.jsxs("a",{href:be.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(Sd,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:be.title})]},be.id))})]})]})]})})]})})}const Yhn=()=>{const{user:s}=_s(),{toast:t}=Bi(),n=Zt(),[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}=st({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=mt({mutationFn:async P=>{let R=P.existingImageUrl;if(P.image){const G=P.image.name.split(".").pop(),Z=`${Date.now()}-${Math.random().toString(36).substring(7)}.${G}`,{error:X}=await q.storage.from("template-previews").upload(Z,P.image);if(X)throw X;const{data:ae}=q.storage.from("template-previews").getPublicUrl(Z);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:Z}=await q.from("social_swag").insert(D).select().single();if(Z)throw Z;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:Z}=await q.from("social_swag_links").insert(G);if(Z)throw Z}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)&&OWe(P.itemTitle,P.itemId),a(!1),y()},onError:P=>{t({title:"Error saving item",description:P.message,variant:"destructive"})}}),v=mt({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"})}}),y=()=>{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}]})},A=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(Dm,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.length})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(P=>P.is_published).length})})]})]}),e.jsxs(Os,{open:r,onOpenChange:P=>{a(P),P||y()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(cn,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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(kk,{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(jn,{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(mr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(Hc,{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(cn,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((P,R)=>e.jsx(je,{children:e.jsxs(Le,{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:()=>A(R),children:e.jsx(mr,{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(je,{children:e.jsx(Le,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:f.map(P=>{var R;return e.jsxs(An,{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(Hc,{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($e,{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(Ta,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>b(P),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await mo("Are you sure you want to delete this item?")&&v.mutate(P.id)},children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},P.id)})})]})})})]})})};function Zhn({item:s,onEdit:t,onDelete:n,onDateChange:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=p6e({id:s.id}),u={transform:TL.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(je,{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(zg,{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(pi,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>n(s),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs($e,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(Ea,{className:"h-2.5 w-2.5"}),Js(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Le,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(Gd,{children:[e.jsx(Wd,{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(Ea,{className:"h-3 w-3"}),s.post_date?Js(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(Dd,{className:"w-auto p-0",align:"start",children:[e.jsx(A2,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:h=>r(s.id,h?Js(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 Xhn=()=>{const s=Zt(),[t,n]=j.useState("all"),[r,a]=j.useState(!1),[i,l]=j.useState(Js(new Date,"yyyy-MM")),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState(null),[x,v]=j.useState(""),[y,b]=j.useState(null),[w,S]=j.useState(!1),[A,E]=j.useState(!1),[I,P]=j.useState(Js(new Date,"yyyy-MM")),[R,D]=j.useState(null),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Z]=j.useState(""),[X,ae]=j.useState(!1),le=i6e(CG(lK,{activationConstraint:{distance:5}}),CG(c6e,{coordinateGetter:eUt})),{data:re=[],isLoading:te}=st({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:rt,error:Ke}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(Ke)throw Ke;return rt}}),{data:J=[]}=st({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:rt,error:Ke}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(Ke)throw Ke;return rt}}),{data:ce=[]}=st({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:rt,error:Ke}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(Ke)throw Ke;return rt}}),ve=[...new Set(re.map(rt=>rt.month))].sort((rt,Ke)=>Ke.localeCompare(rt)),fe=t==="all"?re:re.filter(rt=>rt.month===t),ue=rt=>{const Ke=wtt(rt,"yyyy-MM",new Date);return Js(Ke,"MMMM yyyy")},be=rt=>{g(rt),v(rt.caption),b(rt.post_date)},Ee=async()=>{if(f){S(!0);try{const{error:rt}=await q.from("social_swag_2").update({caption:x,post_date:y}).eq("id",f.id);if(rt)throw rt;ne.success("Image updated"),g(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{ne.error("Failed to update image")}finally{S(!1)}}},ke=async rt=>{const{active:Ke,over:Je}=rt;if(!Je||Ke.id===Je.id)return;const ft=fe,gt=ft.findIndex(as=>as.id===Ke.id),es=ft.findIndex(as=>as.id===Je.id);if(gt===-1||es===-1)return;const Ht=m6e(ft,gt,es);s.setQueryData(["admin-social-swag-2"],as=>{if(!as)return as;const bs={};return Ht.forEach((Ut,Ft)=>{bs[Ut.id]=Ft}),as.map(Ut=>bs[Ut.id]!==void 0?{...Ut,sort_order:bs[Ut.id]}:Ut).sort((Ut,Ft)=>Ut.month!==Ft.month?Ft.month.localeCompare(Ut.month):Ut.sort_order-Ft.sort_order)});try{await Promise.all(Ht.map((as,bs)=>q.from("social_swag_2").update({sort_order:bs}).eq("id",as.id)))}catch{ne.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Ie=rt=>{const Je=Array.from(rt.target.files||[]).sort((ft,gt)=>ft.name.localeCompare(gt.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(ft=>({file:ft,preview:URL.createObjectURL(ft),caption:""}));c(ft=>[...ft,...Je].slice(0,16))},Fe=rt=>{c(Ke=>{const Je=[...Ke];return URL.revokeObjectURL(Je[rt].preview),Je.splice(rt,1),Je})},Ne=(rt,Ke)=>{c(Je=>{const ft=[...Je];return ft[rt]={...ft[rt],caption:Ke},ft})},Be=async()=>{var Ke;if(o.length===0){ne.error("Please add at least one image");return}if(o.filter(Je=>!Je.caption.trim()).length>0){ne.error("Please add captions to all images");return}u(!0);try{const{data:Je}=await q.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),ft=(((Ke=Je==null?void 0:Je[0])==null?void 0:Ke.sort_order)??-1)+1;for(let gt=0;gt{const Ke=rt.image_url.split("/social-swag-2/");Ke[1]&&await q.storage.from("social-swag-2").remove([Ke[1]]);const{error:Je}=await q.from("social_swag_2").delete().eq("id",rt.id);if(Je)throw Je},onSuccess:()=>{ne.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>ne.error("Failed to delete image")}),Ae=mt({mutationFn:async({id:rt,postDate:Ke})=>{const{error:Je}=await q.from("social_swag_2").update({post_date:Ke}).eq("id",rt);if(Je)throw Je},onSuccess:()=>{ne.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>ne.error("Failed to update post date")}),Ce=mt({mutationFn:async({month:rt,link:Ke})=>{const{error:Je}=await q.from("social_swag_2_months").upsert({month:rt,canva_link:Ke||null},{onConflict:"month"});if(Je)throw Je},onSuccess:()=>{ne.success("Canva link updated"),m(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>ne.error("Failed to update Canva link")}),qe=rt=>{var Ke;return((Ke=J.find(Je=>Je.month===rt))==null?void 0:Ke.canva_link)||""},ze=rt=>ce.find(Ke=>Ke.month===rt)||null,Ve=rt=>{var Je;const Ke=(Je=rt.target.files)==null?void 0:Je[0];Ke&&(D(Ke),U(URL.createObjectURL(Ke)))},ht=()=>{O&&URL.revokeObjectURL(O),D(null),U(""),V(""),Z("")},Qe=async()=>{if(!R){ne.error("Please select an image");return}ae(!0);try{const rt=R.name.split(".").pop(),Ke=`reels/${I}-${Date.now()}.${rt}`,{error:Je}=await q.storage.from("social-swag-2").upload(Ke,R);if(Je)throw Je;const{data:{publicUrl:ft}}=q.storage.from("social-swag-2").getPublicUrl(Ke),{error:gt}=await q.from("social_swag_2_reels").upsert({month:I,image_url:ft,canva_link:G||null,caption:W||null},{onConflict:"month"});if(gt)throw gt;ne.success("Reel uploaded successfully!"),OWe(`${ue(I)} Reel`,"social-swag-2"),ht(),E(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(rt){console.error("Reel upload error:",rt),ne.error("Failed to upload reel")}finally{ae(!1)}},at=mt({mutationFn:async rt=>{const Ke=rt.image_url.split("/social-swag-2/");Ke[1]&&await q.storage.from("social-swag-2").remove([Ke[1]]);const{error:Je}=await q.from("social_swag_2_reels").delete().eq("id",rt.id);if(Je)throw Je},onSuccess:()=>{ne.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>ne.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(Os,{open:r,onOpenChange:a,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(cn,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(Fs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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:rt=>l(rt.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:Ie,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((rt,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:rt.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(mr,{className:"h-3 w-3"})})]}),e.jsx(Rs,{placeholder:"Caption...",value:rt.caption,onChange:Je=>Ne(Ke,Je.target.value),className:"text-xs h-20"})]},Ke))}),e.jsx($,{onClick:Be,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{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(Os,{open:A,onOpenChange:rt=>{E(rt),rt||ht()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"gap-2",children:[e.jsx(nf,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(Fs,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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:rt=>P(rt.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(mr,{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:Ve,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(nf,{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:rt=>Z(rt.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:rt=>V(rt.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx($,{onClick:Qe,disabled:X||!R,className:"w-full gap-2",children:X?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{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(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:re.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ve.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(pa,{value:t,onValueChange:n,children:e.jsxs(ga,{children:[e.jsx(Xt,{value:"all",children:"All"}),ve.map(rt=>e.jsx(Xt,{value:rt,children:ue(rt)},rt))]})}),t!=="all"&&e.jsx(je,{children:e.jsx(Le,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Sd,{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:rt=>m({...h,link:rt.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(je,{children:e.jsx(Le,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(nf,{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 rt=ze(t);return rt?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:rt.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:rt.caption||"No caption"}),rt.canva_link&&e.jsx("a",{href:rt.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:()=>at.mutate(rt),children:e.jsx(qn,{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..."}):fe.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Hc,{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(h6e,{sensors:le,collisionDetection:o6e,onDragEnd:ke,children:e.jsx(f6e,{items:fe.map(rt=>rt.id),strategy:Qae,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:fe.map(rt=>e.jsx(Zhn,{item:rt,onEdit:be,onDelete:Ke=>Se.mutate(Ke),onDateChange:(Ke,Je)=>Ae.mutate({id:Ke,postDate:Je})},rt.id))})})})]}),e.jsx(Os,{open:!!f,onOpenChange:rt=>{rt||g(null)},children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{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:rt=>v(rt.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(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("flex-1 justify-start gap-2 font-normal",!y&&"text-muted-foreground"),children:[e.jsx(Ea,{className:"h-4 w-4"}),y?Js(new Date(y+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(Dd,{className:"w-auto p-0",align:"start",children:e.jsx(A2,{mode:"single",selected:y?new Date(y+"T00:00:00"):void 0,onSelect:rt=>b(rt?Js(rt,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),y&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>b(null),children:e.jsx(mr,{className:"h-4 w-4"})})]})]})]}),e.jsxs(Nr,{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(Ct,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},Qhn=()=>{const{toast:s}=Bi(),t=Zt(),[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:""}),[v,y]=j.useState(!1),[b,w]=j.useState(null),[S,A]=j.useState(""),{data:E=[],isLoading:I}=st({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:ke,error:Ie}=await q.from("community_categories").select("*").order("sort_order");if(Ie)throw Ie;return ke}}),{data:P=[],isLoading:R}=st({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:ke,error:Ie}=await q.from("community_private_groups").select("*").order("sort_order");if(Ie)throw Ie;return ke}}),{data:D=[]}=st({queryKey:["admin-group-members",b==null?void 0:b.id],queryFn:async()=>{if(!b)return[];const{data:ke,error:Ie}=await q.from("community_private_group_members").select("*").eq("group_id",b.id);if(Ie)throw Ie;return ke},enabled:!!b}),{data:O=[]}=st({queryKey:["admin-all-profiles"],queryFn:async()=>{let Ie=[],Fe=0,Ne=!0;for(;Ne;){const{data:Be,error:Se}=await q.from("profiles").select("id, name, email, brokerage_id").order("name").range(Fe,Fe+1e3-1);if(Se)throw Se;Be&&Be.length>0?(Ie=[...Ie,...Be],Fe+=1e3,Ne=Be.length===1e3):Ne=!1}return Ie}}),{data:U=[]}=st({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:ke,error:Ie}=await q.from("brokerages").select("*").order("name");if(Ie)throw Ie;return ke}}),W=mt({mutationFn:async ke=>{if(ke.id){const{error:Ie}=await q.from("community_categories").update({name:ke.name,description:ke.description||null,icon:ke.icon||null}).eq("id",ke.id);if(Ie)throw Ie}else{const Ie=Math.max(...E.map(Ne=>Ne.sort_order),0),{error:Fe}=await q.from("community_categories").insert({name:ke.name,description:ke.description||null,icon:ke.icon||null,sort_order:Ie+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:ke=>{s({title:"Error",description:ke.message,variant:"destructive"})}}),V=mt({mutationFn:async ke=>{const{error:Ie}=await q.from("community_categories").delete().eq("id",ke);if(Ie)throw Ie},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),G=mt({mutationFn:async({id:ke,direction:Ie})=>{const Fe=E.findIndex(Ne=>Ne.id===ke);if(Ie==="up"&&Fe>0){const Ne=E[Fe-1],Be=E[Fe];await q.from("community_categories").update({sort_order:Be.sort_order}).eq("id",Ne.id),await q.from("community_categories").update({sort_order:Ne.sort_order}).eq("id",Be.id)}else if(Ie==="down"&&Fet.invalidateQueries({queryKey:["admin-community-categories"]})}),Z=mt({mutationFn:async ke=>{if(ke.id){const{error:Ie}=await q.from("community_private_groups").update({name:ke.name,description:ke.description||null,icon:ke.icon||null}).eq("id",ke.id);if(Ie)throw Ie}else{const Ie=Math.max(...P.map(Ne=>Ne.sort_order),0),{error:Fe}=await q.from("community_private_groups").insert({name:ke.name,description:ke.description||null,icon:ke.icon||null,sort_order:Ie+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:ke=>{s({title:"Error",description:ke.message,variant:"destructive"})}}),X=mt({mutationFn:async ke=>{const{error:Ie}=await q.from("community_private_groups").delete().eq("id",ke);if(Ie)throw Ie},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),ae=mt({mutationFn:async({id:ke,direction:Ie})=>{const Fe=P.findIndex(Ne=>Ne.id===ke);if(Ie==="up"&&Fe>0){const Ne=P[Fe-1],Be=P[Fe];await q.from("community_private_groups").update({sort_order:Be.sort_order}).eq("id",Ne.id),await q.from("community_private_groups").update({sort_order:Ne.sort_order}).eq("id",Be.id)}else if(Ie==="down"&&Fet.invalidateQueries({queryKey:["admin-private-groups"]})}),le=mt({mutationFn:async({groupId:ke,userId:Ie,isMember:Fe})=>{if(Fe){const{error:Ne}=await q.from("community_private_group_members").delete().eq("group_id",ke).eq("user_id",Ie);if(Ne)throw Ne}else{const{error:Ne}=await q.from("community_private_group_members").insert({group_id:ke,user_id:Ie});if(Ne)throw Ne}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),re=mt({mutationFn:async({groupId:ke,brokerageId:Ie,isMember:Fe})=>{if(Fe){const{error:Ne}=await q.from("community_private_group_members").delete().eq("group_id",ke).eq("brokerage_id",Ie);if(Ne)throw Ne}else{const{error:Ne}=await q.from("community_private_group_members").insert({group_id:ke,brokerage_id:Ie});if(Ne)throw Ne}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),te=ke=>{o(ke),d({name:ke.name,description:ke.description||"",icon:ke.icon||""}),i(!0)},J=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},ce=ke=>{f(ke),x({name:ke.name,description:ke.description||"",icon:ke.icon||""}),h(!0)},ve=()=>{f(null),x({name:"",description:"",icon:""}),h(!0)},fe=ke=>{w(ke),A(""),y(!0)},ue=ke=>D.some(Ie=>Ie.user_id===ke),be=ke=>D.some(Ie=>Ie.brokerage_id===ke),Ee=O.filter(ke=>ke.name.toLowerCase().includes(S.toLowerCase())||ke.email.toLowerCase().includes(S.toLowerCase()));return e.jsx(Vs,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Dm,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(pa,{value:n,onValueChange:r,children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"categories",children:"Public Categories"}),e.jsxs(Xt,{value:"private-groups",children:[e.jsx(jc,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(Qt,{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(cn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(je,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:I?e.jsx(An,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):E.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):E.map((ke,Ie)=>e.jsxs(An,{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:Ie===0,onClick:()=>G.mutate({id:ke.id,direction:"up"}),children:"↑"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===E.length-1,onClick:()=>G.mutate({id:ke.id,direction:"down"}),children:"↓"})]})}),e.jsx(wt,{className:"text-2xl",children:ke.icon||"📁"}),e.jsx(wt,{className:"font-medium",children:ke.name}),e.jsx(wt,{className:"text-muted-foreground",children:ke.description||"—"}),e.jsx(wt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>te(ke),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await mo("Delete this category? Posts will be uncategorized.")&&V.mutate(ke.id)},children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},ke.id))})]})})})]}),e.jsxs(Qt,{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(wi,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs($,{onClick:ve,children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(je,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:R?e.jsx(An,{children:e.jsx(wt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):P.length===0?e.jsx(An,{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((ke,Ie)=>e.jsxs(An,{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:Ie===0,onClick:()=>ae.mutate({id:ke.id,direction:"up"}),children:"↑"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===P.length-1,onClick:()=>ae.mutate({id:ke.id,direction:"down"}),children:"↓"})]})}),e.jsx(wt,{className:"text-2xl",children:ke.icon||"🔒"}),e.jsx(wt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[ke.name,ke.brokerage_id?e.jsxs($e,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(wi,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs($e,{variant:"secondary",className:"text-xs",children:[e.jsx(jc,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(wt,{className:"text-muted-foreground",children:ke.description||"—"}),e.jsx(wt,{children:e.jsxs($,{variant:"outline",size:"sm",onClick:()=>fe(ke),children:[e.jsx(Yn,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex gap-1",children:[!ke.brokerage_id&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ce(ke),children:e.jsx(pi,{className:"h-4 w-4"})}),!ke.brokerage_id&&e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await mo("Delete this private group? All posts in this group will be deleted.")&&X.mutate(ke.id)},children:e.jsx(qn,{className:"h-4 w-4"})}),ke.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},ke.id))})]})})})]})]}),e.jsx(Os,{open:a,onOpenChange:i,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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:ke=>d(Ie=>({...Ie,icon:ke.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:ke=>d(Ie=>({...Ie,name:ke.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:ke=>d(Ie=>({...Ie,description:ke.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(Os,{open:u,onOpenChange:h,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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:ke=>x(Ie=>({...Ie,icon:ke.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:ke=>x(Ie=>({...Ie,name:ke.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:ke=>x(Ie=>({...Ie,description:ke.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:()=>Z.mutate({...g,id:m==null?void 0:m.id}),disabled:!g.name.trim(),children:m?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(Os,{open:v,onOpenChange:y,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs($s,{children:["Manage Members: ",b==null?void 0:b.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(pa,{defaultValue:"brokerages",children:[e.jsxs(ga,{className:"w-full",children:[e.jsx(Xt,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(Xt,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(Qt,{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(go,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[U.map(ke=>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:be(ke.id),onCheckedChange:()=>{b&&re.mutate({groupId:b.id,brokerageId:ke.id,isMember:be(ke.id)})}}),e.jsx("span",{className:"font-medium",children:ke.name})]}),e.jsxs($e,{variant:"secondary",children:[O.filter(Ie=>Ie.brokerage_id===ke.id).length," agents"]})]},ke.id)),U.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(Qt,{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:ke=>A(ke.target.value),className:"pl-9"})]}),e.jsx(go,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[Ee.map(ke=>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(ke.id),onCheckedChange:()=>{b&&le.mutate({groupId:b.id,userId:ke.id,isMember:ue(ke.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ke.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:ke.email})]})]})},ke.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:()=>y(!1),children:"Done"})})]})]})})]})})},Lwt=s=>{switch(s){case"academy_video":return e.jsx(Ou,{className:"h-3 w-3"});case"template":return e.jsx(Qr,{className:"h-3 w-3"});case"toolbox":return e.jsx(ym,{className:"h-3 w-3"});case"newsletter":return e.jsx(XN,{className:"h-3 w-3"});case"social_swag":return e.jsx(wn,{className:"h-3 w-3"});default:return e.jsx(Ir,{className:"h-3 w-3"})}},Jhn=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}},emn=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}},tmn=()=>{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,v]=j.useState([]);j.useEffect(()=>{y()},[]);const y=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),Z=new Map((G==null?void 0:G.map(te=>[te.id,te]))||[]),X=(D==null?void 0:D.map(te=>{var J,ce,ve,fe;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:((fe=(ve=te.profiles)==null?void 0:ve.brokerages)==null?void 0:fe.name)||null}}))||[],ae=(U==null?void 0:U.map(te=>{var ce;const J=Z.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 le=new Map;X.forEach(te=>{if(!le.has(te.user_id))le.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=le.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(!le.has(te.user_id))le.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=le.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 re=Array.from(le.values()).sort((te,J)=>new Date(J.last_activity_at).getTime()-new Date(te.last_activity_at).getTime());l(re)}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),v(U)},w=()=>{m(null),g([]),v([])},{sortKey:S,sortDirection:A,handleSort:E,sortData:I}=yie("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(je,{children:e.jsx(Le,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"User Activity"}),e.jsx(Vn,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Le,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Mm,{sortKey:"user",currentSortKey:S,currentDirection:A,onSort:E,children:"User"}),e.jsx(Mm,{sortKey:"brokerage",currentSortKey:S,currentDirection:A,onSort:E,children:"Brokerage"}),e.jsx(Dt,{children:"Last Activity"}),e.jsx(Mm,{sortKey:"last_activity_at",currentSortKey:S,currentDirection:A,onSort:E,children:"Last Active"}),e.jsx(Mm,{sortKey:"apps",currentSortKey:S,currentDirection:A,onSort:E,className:"text-right",children:"Apps"}),e.jsx(Mm,{sortKey:"content",currentSortKey:S,currentDirection:A,onSort:E,className:"text-right",children:"Content"})]})}),e.jsx(fi,{children:R.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):R.map(D=>e.jsxs(An,{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($e,{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($e,{variant:"secondary",children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),D.last_activity_name]}):e.jsxs($e,{variant:"outline",className:"flex items-center gap-1",children:[Lwt(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:hu(new Date(D.last_activity_at),{addSuffix:!0})}),e.jsx(wt,{className:"text-right",children:e.jsx($e,{variant:"outline",children:D.total_app_launches})}),e.jsx(wt,{className:"text-right",children:e.jsx($e,{variant:"outline",children:D.total_content_views})})]},D.user_id))})]})})]})]}),e.jsx(Os,{open:!!h,onOpenChange:D=>!D&&w(),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs($s,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(Er,{children:h==null?void 0:h.email})]}),e.jsxs(pa,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ga,{className:"grid w-full grid-cols-2",children:[e.jsxs(Xt,{value:"content",children:["Content (",x.length,")"]}),e.jsxs(Xt,{value:"apps",children:["App Launches (",f.length,")"]})]}),e.jsx(Qt,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Resource"}),e.jsx(Dt,{children:"Action"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(fi,{children:x.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):x.map(D=>e.jsxs(An,{children:[e.jsx(wt,{children:e.jsxs($e,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[Lwt(D.resource_type),Jhn(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($e,{variant:"secondary",children:emn(D.action_type)})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:hu(new Date(D.created_at),{addSuffix:!0})})]},D.id))})]})})}),e.jsx(Qt,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{children:"App"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(fi,{children:f.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):f.map(D=>e.jsxs(An,{children:[e.jsx(wt,{children:e.jsx($e,{variant:"secondary",children:D.app_name})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:hu(new Date(D.launched_at),{addSuffix:!0})})]},D.id))})]})})})]})]})})]})},smn=()=>{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()),v=new Set(x==null?void 0:x.map(y=>y.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:v})}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(je,{children:e.jsx(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Wl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(ca,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(wi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(rf,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(rf,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(rf,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(Zl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},Rwt={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},Dwt={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 AWt({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}=yie("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}),v=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()}),y=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,A=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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(xn,{className:"h-4 w-20"})}),e.jsx(Le,{children:e.jsx(xn,{className:"h-8 w-16"})})]},I))}),e.jsx(je,{children:e.jsx(Le,{className:"p-6",children:e.jsx(xn,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(Hd,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:y})})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:b})})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(Zl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:w})})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(Qr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[S,"%"]})})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Le,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(A).map(([E,I])=>e.jsxs($e,{variant:"secondary",className:Dwt[E],children:[Rwt[E],": ",I]},E)),Object.keys(A).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Share History"}),e.jsxs(Vn,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Le,{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(go,{className:"h-[400px]",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Mm,{sortKey:"resource",currentSortKey:h,currentDirection:m,onSort:f,children:"Resource"}),e.jsx(Mm,{sortKey:"type",currentSortKey:h,currentDirection:m,onSort:f,children:"Type"}),e.jsx(Mm,{sortKey:"sender",currentSortKey:h,currentDirection:m,onSort:f,children:"Sender"}),e.jsx(Mm,{sortKey:"recipient",currentSortKey:h,currentDirection:m,onSort:f,children:"Recipient"}),e.jsx(Mm,{sortKey:"status",currentSortKey:h,currentDirection:m,onSort:f,children:"Status"}),e.jsx(Mm,{sortKey:"created_at",currentSortKey:h,currentDirection:m,onSort:f,children:"Date"})]})}),e.jsx(fi,{children:v.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):v.map(E=>{var I,P;return e.jsxs(An,{children:[e.jsx(wt,{className:"font-medium max-w-[200px] truncate",children:E.resource_title}),e.jsx(wt,{children:e.jsx($e,{variant:"secondary",className:Dwt[E.resource_type],children:Rwt[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($e,{variant:E.is_read?"default":"outline",children:E.is_read?"Read":"Unread"})}),e.jsx(wt,{className:"text-muted-foreground",children:Js(new Date(E.created_at),"MMM d, yyyy")})]},E.id)})})]})})]})]})]})}const XBe={academy_video:{label:"Academy Videos",icon:fa,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:Ta},template:{label:"Templates",icon:IA,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:lb},toolbox:{label:"Toolkit",icon:I4,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:ji},newsletter:{label:"Newsletters",icon:pn,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:lb},social_swag:{label:"Social Swag",icon:yd,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:lb},event:{label:"Events",icon:Ea,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:lb}};function Fwt(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function nmn(s,t){return s==="toolbox"?t.downloads:t.clicks}function rmn(){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}=yie("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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(xn,{className:"h-4 w-20"})}),e.jsx(Le,{children:e.jsx(xn,{className:"h-8 w-16"})})]},P))}),e.jsx(je,{children:e.jsx(Le,{className:"py-8",children:e.jsx(xn,{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),v=s.length,y=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=>Fwt(I),unique_users:I=>I.unique_users,last_activity:I=>I.last_engaged_at?new Date(I.last_engaged_at).getTime():0}),S=a?XBe[a]||{label:a,icon:Ta,actionLabel:"Actions"}:null,A=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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(Ta,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(lb,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(ji,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(Zl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(lb,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(Vn,{children:"Click a category to see individual asset performance"})]}),e.jsx(Le,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(y).map(([I,P])=>{const R=XBe[I]||{label:I,icon:Ta,color:"bg-muted text-muted-foreground",actionIcon:lb},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(Ta,{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"})," ",nmn(I,P)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"})," ",P.uniqueUsers]})]})]}),e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:[P.assets," items"]})]},I)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Et,{className:"text-sm font-medium flex items-center gap-2",children:S&&A?e.jsxs(e.Fragment,{children:[e.jsx(A,{className:"h-4 w-4"}),S.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(Vn,{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(Va,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(Le,{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(go,{className:"h-[400px]",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{className:"w-[40px]",children:"#"}),e.jsx(Mm,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(Mm,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(Mm,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(Mm,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:S?S.actionLabel:"Actions"}),e.jsx(Mm,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(Mm,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(fi,{children:w.map((I,P)=>{const R=XBe[I.resource_type]||{label:I.resource_type,color:"bg-muted text-muted-foreground"};return e.jsxs(An,{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($e,{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:Fwt(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?hu(new Date(I.last_engaged_at),{addSuffix:!0}):"—"})]},`${I.resource_type}-${I.resource_id}`)})})]})})})]})})]})}var amn=Array.isArray,qw=amn,imn=typeof kp=="object"&&kp&&kp.Object===Object&&kp,EWt=imn,omn=EWt,lmn=typeof self=="object"&&self&&self.Object===Object&&self,cmn=omn||lmn||Function("return this")(),u3=cmn,dmn=u3,umn=dmn.Symbol,bie=umn,Owt=bie,TWt=Object.prototype,hmn=TWt.hasOwnProperty,mmn=TWt.toString,$Z=Owt?Owt.toStringTag:void 0;function fmn(s){var t=hmn.call(s,$Z),n=s[$Z];try{s[$Z]=void 0;var r=!0}catch{}var a=mmn.call(s);return r&&(t?s[$Z]=n:delete s[$Z]),a}var pmn=fmn,gmn=Object.prototype,xmn=gmn.toString;function ymn(s){return xmn.call(s)}var vmn=ymn,zwt=bie,bmn=pmn,_mn=vmn,wmn="[object Null]",jmn="[object Undefined]",Bwt=zwt?zwt.toStringTag:void 0;function Nmn(s){return s==null?s===void 0?jmn:wmn:Bwt&&Bwt in Object(s)?bmn(s):_mn(s)}var IT=Nmn;function kmn(s){return s!=null&&typeof s=="object"}var LT=kmn,Smn=IT,Cmn=LT,Amn="[object Symbol]";function Emn(s){return typeof s=="symbol"||Cmn(s)&&Smn(s)==Amn}var vK=Emn,Tmn=qw,Mmn=vK,Pmn=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Imn=/^\w*$/;function Lmn(s,t){if(Tmn(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||Mmn(s)?!0:Imn.test(s)||!Pmn.test(s)||t!=null&&s in Object(t)}var Irt=Lmn;function Rmn(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var v6=Rmn;const bK=ru(v6);var Dmn=IT,Fmn=v6,Omn="[object AsyncFunction]",zmn="[object Function]",Bmn="[object GeneratorFunction]",$mn="[object Proxy]";function Umn(s){if(!Fmn(s))return!1;var t=Dmn(s);return t==zmn||t==Bmn||t==Omn||t==$mn}var Lrt=Umn;const hc=ru(Lrt);var qmn=u3,Vmn=qmn["__core-js_shared__"],Hmn=Vmn,QBe=Hmn,$wt=function(){var s=/[^.]+$/.exec(QBe&&QBe.keys&&QBe.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function Gmn(s){return!!$wt&&$wt in s}var Wmn=Gmn,Kmn=Function.prototype,Ymn=Kmn.toString;function Zmn(s){if(s!=null){try{return Ymn.call(s)}catch{}try{return s+""}catch{}}return""}var MWt=Zmn,Xmn=Lrt,Qmn=Wmn,Jmn=v6,efn=MWt,tfn=/[\\^$.*+?()[\]{}|]/g,sfn=/^\[object .+?Constructor\]$/,nfn=Function.prototype,rfn=Object.prototype,afn=nfn.toString,ifn=rfn.hasOwnProperty,ofn=RegExp("^"+afn.call(ifn).replace(tfn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function lfn(s){if(!Jmn(s)||Qmn(s))return!1;var t=Xmn(s)?ofn:sfn;return t.test(efn(s))}var cfn=lfn;function dfn(s,t){return s==null?void 0:s[t]}var ufn=dfn,hfn=cfn,mfn=ufn;function ffn(s,t){var n=mfn(s,t);return hfn(n)?n:void 0}var GB=ffn,pfn=GB,gfn=pfn(Object,"create"),aRe=gfn,Uwt=aRe;function xfn(){this.__data__=Uwt?Uwt(null):{},this.size=0}var yfn=xfn;function vfn(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var bfn=vfn,_fn=aRe,wfn="__lodash_hash_undefined__",jfn=Object.prototype,Nfn=jfn.hasOwnProperty;function kfn(s){var t=this.__data__;if(_fn){var n=t[s];return n===wfn?void 0:n}return Nfn.call(t,s)?t[s]:void 0}var Sfn=kfn,Cfn=aRe,Afn=Object.prototype,Efn=Afn.hasOwnProperty;function Tfn(s){var t=this.__data__;return Cfn?t[s]!==void 0:Efn.call(t,s)}var Mfn=Tfn,Pfn=aRe,Ifn="__lodash_hash_undefined__";function Lfn(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=Pfn&&t===void 0?Ifn:t,this}var Rfn=Lfn,Dfn=yfn,Ffn=bfn,Ofn=Sfn,zfn=Mfn,Bfn=Rfn;function _K(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var npn=spn,rpn=iRe;function apn(s,t){var n=this.__data__,r=rpn(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var ipn=apn,opn=qfn,lpn=Xfn,cpn=epn,dpn=npn,upn=ipn;function wK(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},h8=function(t){return Q7(t)&&t.indexOf("%")===t.length-1},xi=function(t){return Mgn(t)&&!NK(t)},Rgn=function(t){return Gc(t)},N0=function(t){return xi(t)||Q7(t)},Dgn=0,WB=function(t){var n=++Dgn;return"".concat(t||"").concat(n)},y_=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(!xi(t)&&!Q7(t))return r;var i;if(h8(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return NK(i)&&(i=r),a&&i>n&&(i=n),i},kP=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},Fgn=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 Vgn(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 BWe(s){"@babel/helpers - typeof";return BWe=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},BWe(s)}var Ywt={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"},qE=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},Zwt=null,e9e=null,Vrt=function s(t){if(t===Zwt&&Array.isArray(e9e))return e9e;var n=[];return j.Children.forEach(t,function(r){Gc(r)||(Sgn.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),e9e=n,Zwt=t,n};function x2(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return qE(a)}):r=[qE(t)],Vrt(s).forEach(function(a){var i=g2(a,"type.displayName")||g2(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function Bj(s,t){var n=x2(s,t);return n&&n[0]}var Xwt=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,a=n.height;return!(!xi(r)||r<=0||!xi(a)||a<=0)},Hgn=["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"],Ggn=function(t){return t&&t.type&&Q7(t.type)&&Hgn.indexOf(t.type)>=0},$Wt=function(t){return t&&BWe(t)==="object"&&"clipDot"in t},Wgn=function(t,n,r,a){var i,l=(i=JBe==null?void 0:JBe[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!hc(t)&&(a&&l.includes(n)||Bgn.includes(n))||r&&qrt.includes(n)},ll=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(j.isValidElement(t)&&(a=t.props),!bK(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;Wgn((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},$We=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 Qwt(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 Qgn(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 qWe(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=Xgn(s,Zgn),u=a||{width:n,height:r,x:0,y:0},h=sd("recharts-surface",i);return Kt.createElement("svg",UWe({},ll(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),Kt.createElement("title",null,o),Kt.createElement("desc",null,c),t)}var Jgn=["children","className"];function VWe(){return VWe=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 txn(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 ku=Kt.forwardRef(function(s,t){var n=s.children,r=s.className,a=exn(s,Jgn),i=sd("recharts-layer",r);return Kt.createElement("g",VWe({className:i},ll(a,!0),{ref:t}),n)}),iC=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:rxn(s,t,n)}var ixn=axn,oxn="\\ud800-\\udfff",lxn="\\u0300-\\u036f",cxn="\\ufe20-\\ufe2f",dxn="\\u20d0-\\u20ff",uxn=lxn+cxn+dxn,hxn="\\ufe0e\\ufe0f",mxn="\\u200d",fxn=RegExp("["+mxn+oxn+uxn+hxn+"]");function pxn(s){return fxn.test(s)}var UWt=pxn;function gxn(s){return s.split("")}var xxn=gxn,qWt="\\ud800-\\udfff",yxn="\\u0300-\\u036f",vxn="\\ufe20-\\ufe2f",bxn="\\u20d0-\\u20ff",_xn=yxn+vxn+bxn,wxn="\\ufe0e\\ufe0f",jxn="["+qWt+"]",HWe="["+_xn+"]",GWe="\\ud83c[\\udffb-\\udfff]",Nxn="(?:"+HWe+"|"+GWe+")",VWt="[^"+qWt+"]",HWt="(?:\\ud83c[\\udde6-\\uddff]){2}",GWt="[\\ud800-\\udbff][\\udc00-\\udfff]",kxn="\\u200d",WWt=Nxn+"?",KWt="["+wxn+"]?",Sxn="(?:"+kxn+"(?:"+[VWt,HWt,GWt].join("|")+")"+KWt+WWt+")*",Cxn=KWt+WWt+Sxn,Axn="(?:"+[VWt+HWe+"?",HWe,HWt,GWt,jxn].join("|")+")",Exn=RegExp(GWe+"(?="+GWe+")|"+Axn+Cxn,"g");function Txn(s){return s.match(Exn)||[]}var Mxn=Txn,Pxn=xxn,Ixn=UWt,Lxn=Mxn;function Rxn(s){return Ixn(s)?Lxn(s):Pxn(s)}var Dxn=Rxn,Fxn=ixn,Oxn=UWt,zxn=Dxn,Bxn=RWt;function $xn(s){return function(t){t=Bxn(t);var n=Oxn(t)?zxn(t):void 0,r=n?n[0]:t.charAt(0),a=n?Fxn(n,1).join(""):t.slice(1);return r[s]()+a}}var Uxn=$xn,qxn=Uxn,Vxn=qxn("toUpperCase"),Hxn=Vxn;const bRe=ru(Hxn);function Vf(s){return function(){return s}}const YWt=Math.cos,qTe=Math.sin,NC=Math.sqrt,VTe=Math.PI,_Re=2*VTe,WWe=Math.PI,KWe=2*WWe,MO=1e-6,Gxn=KWe-MO;function ZWt(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return ZWt;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;aMO)if(!(Math.abs(h*c-d*u)>MO)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let f=r-l,g=a-o,x=c*c+d*d,v=f*f+g*g,y=Math.sqrt(x),b=Math.sqrt(m),w=i*Math.tan((WWe-Math.acos((x+m-v)/(2*y*b)))/2),S=w/b,A=w/y;Math.abs(S-1)>MO&&this._append`L${t+S*u},${n+S*h}`,this._append`A${i},${i},0,0,${+(h*f>u*g)},${this._x1=t+A*c},${this._y1=n+A*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)>MO||Math.abs(this._y1-u)>MO)&&this._append`L${d},${u}`,r&&(m<0&&(m=m%KWe+KWe),m>Gxn?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>MO&&this._append`A${r},${r},0,${+(m>=WWe)},${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 Hrt(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 Kxn(t)}function Grt(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function XWt(s){this._context=s}XWt.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 wRe(s){return new XWt(s)}function QWt(s){return s[0]}function JWt(s){return s[1]}function eKt(s,t){var n=Vf(!0),r=null,a=wRe,i=null,l=Hrt(o);s=typeof s=="function"?s:s===void 0?QWt:Vf(s),t=typeof t=="function"?t:t===void 0?JWt:Vf(t);function o(c){var d,u=(c=Grt(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()}y&&(w[m]=+s(v,m,h),S[m]=+t(v,m,h),o.point(r?+r(v,m,h):w[m],n?+n(v,m,h):S[m]))}if(b)return o=null,b+""||null}function u(){return eKt().defined(a).curve(l).context(i)}return d.x=function(h){return arguments.length?(s=typeof h=="function"?h:Vf(+h),r=null,d):s},d.x0=function(h){return arguments.length?(s=typeof h=="function"?h:Vf(+h),d):s},d.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:Vf(+h),d):r},d.y=function(h){return arguments.length?(t=typeof h=="function"?h:Vf(+h),n=null,d):t},d.y0=function(h){return arguments.length?(t=typeof h=="function"?h:Vf(+h),d):t},d.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:Vf(+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:Vf(!!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 tKt{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 Yxn(s){return new tKt(s,!0)}function Zxn(s){return new tKt(s,!1)}const Wrt={draw(s,t){const n=NC(t/VTe);s.moveTo(n,0),s.arc(0,0,n,0,_Re)}},Xxn={draw(s,t){const n=NC(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()}},sKt=NC(1/3),Qxn=sKt*2,Jxn={draw(s,t){const n=NC(t/Qxn),r=n*sKt;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},eyn={draw(s,t){const n=NC(t),r=-n/2;s.rect(r,r,n,n)}},tyn=.8908130915292852,nKt=qTe(VTe/10)/qTe(7*VTe/10),syn=qTe(_Re/10)*nKt,nyn=-YWt(_Re/10)*nKt,ryn={draw(s,t){const n=NC(t*tyn),r=syn*n,a=nyn*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=_Re*i/5,o=YWt(l),c=qTe(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},t9e=NC(3),ayn={draw(s,t){const n=-NC(t/(t9e*3));s.moveTo(0,n*2),s.lineTo(-t9e*n,-n),s.lineTo(t9e*n,-n),s.closePath()}},eN=-.5,tN=NC(3)/2,YWe=1/NC(12),iyn=(YWe/2+1)*3,oyn={draw(s,t){const n=NC(t/iyn),r=n/2,a=n*YWe,i=r,l=n*YWe+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(eN*r-tN*a,tN*r+eN*a),s.lineTo(eN*i-tN*l,tN*i+eN*l),s.lineTo(eN*o-tN*c,tN*o+eN*c),s.lineTo(eN*r+tN*a,eN*a-tN*r),s.lineTo(eN*i+tN*l,eN*l-tN*i),s.lineTo(eN*o+tN*c,eN*c-tN*o),s.closePath()}};function lyn(s,t){let n=null,r=Hrt(a);s=typeof s=="function"?s:Vf(s||Wrt),t=typeof t=="function"?t:Vf(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:Vf(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:Vf(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function HTe(){}function GTe(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 rKt(s){this._context=s}rKt.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:GTe(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:GTe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function cyn(s){return new rKt(s)}function aKt(s){this._context=s}aKt.prototype={areaStart:HTe,areaEnd:HTe,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:GTe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function dyn(s){return new aKt(s)}function iKt(s){this._context=s}iKt.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:GTe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function uyn(s){return new iKt(s)}function oKt(s){this._context=s}oKt.prototype={areaStart:HTe,areaEnd:HTe,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 hyn(s){return new oKt(s)}function ejt(s){return s<0?-1:1}function tjt(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(ejt(i)+ejt(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function sjt(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function s9e(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 WTe(s){this._context=s}WTe.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:s9e(this,this._t0,sjt(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,s9e(this,sjt(this,n=tjt(this,s,t)),n);break;default:s9e(this,this._t0,n=tjt(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function lKt(s){this._context=new cKt(s)}(lKt.prototype=Object.create(WTe.prototype)).point=function(s,t){WTe.prototype.point.call(this,t,s)};function cKt(s){this._context=s}cKt.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 myn(s){return new WTe(s)}function fyn(s){return new lKt(s)}function dKt(s){this._context=s}dKt.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=njt(s),a=njt(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 jRe(s,.5)}function xyn(s){return new jRe(s,0)}function yyn(s){return new jRe(s,1)}function FG(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 vyn(s,t){return s[t]}function byn(s){const t=[];return t.key=s,t}function _yn(){var s=Vf([]),t=ZWe,n=FG,r=vyn;function a(i){var l=Array.from(s.apply(this,arguments),byn),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 Tyn(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 uKt={symbolCircle:Wrt,symbolCross:Xxn,symbolDiamond:Jxn,symbolSquare:eyn,symbolStar:ryn,symbolTriangle:ayn,symbolWye:oyn},Myn=Math.PI/180,Pyn=function(t){var n="symbol".concat(bRe(t));return uKt[n]||Wrt},Iyn=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*Myn;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}},Lyn=function(t,n){uKt["symbol".concat(bRe(t))]=n},Krt=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=Eyn(t,kyn),d=ajt(ajt({},c),{},{type:r,size:i,sizeType:o}),u=function(){var v=Pyn(r),y=lyn().type(v).size(Iyn(i,o,r));return y()},h=d.className,m=d.cx,f=d.cy,g=ll(d,!0);return m===+m&&f===+f&&i===+i?Kt.createElement("path",XWe({},g,{className:sd("recharts-symbols",h),transform:"translate(".concat(m,", ").concat(f,")"),d:u()})):null};Krt.registerSymbol=Lyn;function OG(s){"@babel/helpers - typeof";return OG=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},OG(s)}function QWe(){return QWe=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var b=f.inactive?d:f.color;return Kt.createElement("li",QWe({className:v,style:h,key:"legend-item-".concat(g)},J7(r.props,f,g)),Kt.createElement(qWe,{width:l,height:l,viewBox:u,style:m},r.renderIcon(f)),Kt.createElement("span",{className:"recharts-legend-item-text",style:{color:b}},x?x(y,f,g):y))})}},{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 Kt.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(j.PureComponent);Ase(Yrt,"displayName","Legend");Ase(Yrt,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var Vyn=oRe;function Hyn(){this.__data__=new Vyn,this.size=0}var Gyn=Hyn;function Wyn(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var Kyn=Wyn;function Yyn(s){return this.__data__.get(s)}var Zyn=Yyn;function Xyn(s){return this.__data__.has(s)}var Qyn=Xyn,Jyn=oRe,e0n=Drt,t0n=Frt,s0n=200;function n0n(s,t){var n=this.__data__;if(n instanceof Jyn){var r=n.__data__;if(!e0n||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&k0n?new _0n:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=Evn}var Jrt=Tvn,Mvn=IT,Pvn=Jrt,Ivn=LT,Lvn="[object Arguments]",Rvn="[object Array]",Dvn="[object Boolean]",Fvn="[object Date]",Ovn="[object Error]",zvn="[object Function]",Bvn="[object Map]",$vn="[object Number]",Uvn="[object Object]",qvn="[object RegExp]",Vvn="[object Set]",Hvn="[object String]",Gvn="[object WeakMap]",Wvn="[object ArrayBuffer]",Kvn="[object DataView]",Yvn="[object Float32Array]",Zvn="[object Float64Array]",Xvn="[object Int8Array]",Qvn="[object Int16Array]",Jvn="[object Int32Array]",ebn="[object Uint8Array]",tbn="[object Uint8ClampedArray]",sbn="[object Uint16Array]",nbn="[object Uint32Array]",yp={};yp[Yvn]=yp[Zvn]=yp[Xvn]=yp[Qvn]=yp[Jvn]=yp[ebn]=yp[tbn]=yp[sbn]=yp[nbn]=!0;yp[Lvn]=yp[Rvn]=yp[Wvn]=yp[Dvn]=yp[Kvn]=yp[Fvn]=yp[Ovn]=yp[zvn]=yp[Bvn]=yp[$vn]=yp[Uvn]=yp[qvn]=yp[Vvn]=yp[Hvn]=yp[Gvn]=!1;function rbn(s){return Ivn(s)&&Pvn(s.length)&&!!yp[Mvn(s)]}var abn=rbn;function ibn(s){return function(t){return s(t)}}var wKt=ibn,XTe={exports:{}};XTe.exports;(function(s,t){var n=EWt,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})(XTe,XTe.exports);var obn=XTe.exports,lbn=abn,cbn=wKt,hjt=obn,mjt=hjt&&hjt.isTypedArray,dbn=mjt?cbn(mjt):lbn,jKt=dbn,ubn=fvn,hbn=Xrt,mbn=qw,fbn=_Kt,pbn=Qrt,gbn=jKt,xbn=Object.prototype,ybn=xbn.hasOwnProperty;function vbn(s,t){var n=mbn(s),r=!n&&hbn(s),a=!n&&!r&&fbn(s),i=!n&&!r&&!a&&gbn(s),l=n||r||a||i,o=l?ubn(s.length,String):[],c=o.length;for(var d in s)(t||ybn.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||pbn(d,c)))&&o.push(d);return o}var bbn=vbn,_bn=Object.prototype;function wbn(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||_bn;return s===n}var jbn=wbn;function Nbn(s,t){return function(n){return s(t(n))}}var NKt=Nbn,kbn=NKt,Sbn=kbn(Object.keys,Object),Cbn=Sbn,Abn=jbn,Ebn=Cbn,Tbn=Object.prototype,Mbn=Tbn.hasOwnProperty;function Pbn(s){if(!Abn(s))return Ebn(s);var t=[];for(var n in Object(s))Mbn.call(s,n)&&n!="constructor"&&t.push(n);return t}var Ibn=Pbn,Lbn=Lrt,Rbn=Jrt;function Dbn(s){return s!=null&&Rbn(s.length)&&!Lbn(s)}var _ie=Dbn,Fbn=bbn,Obn=Ibn,zbn=_ie;function Bbn(s){return zbn(s)?Fbn(s):Obn(s)}var NRe=Bbn,$bn=svn,Ubn=hvn,qbn=NRe;function Vbn(s){return $bn(s,qbn,Ubn)}var Hbn=Vbn,fjt=Hbn,Gbn=1,Wbn=Object.prototype,Kbn=Wbn.hasOwnProperty;function Ybn(s,t,n,r,a,i){var l=n&Gbn,o=fjt(s),c=o.length,d=fjt(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var m=o[h];if(!(l?m in t:Kbn.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 v=l;++h-1}var W_n=G_n;function K_n(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=cwn){var d=t?null:own(s);if(d)return lwn(d);l=!1,a=iwn,c=new nwn}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function kwn(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 Swn(s){return s.value}function Cwn(s,t){if(Kt.isValidElement(s))return Kt.cloneElement(s,t);if(typeof s=="function")return Kt.createElement(s,t);t.ref;var n=Nwn(t,gwn);return Kt.createElement(Yrt,n)}var Tjt=1,kV=function(s){function t(){var n;xwn(this,t);for(var r=arguments.length,a=new Array(r),i=0;iTjt||Math.abs(a.height-this.lastBoundingBox.height)>Tjt)&&(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?tA({},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 tA(tA({},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=tA(tA({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return Kt.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(f){r.wrapperNode=f}},Cwn(i,tA(tA({},this.props),{},{payload:MKt(u,d,Swn)})))}}],[{key:"getWithHeight",value:function(r,a){var i=tA(tA({},this.defaultProps),r.props),l=i.layout;return l==="vertical"&&xi(r.props.height)?{height:r.props.height}:l==="horizontal"?{width:r.props.width||a}:null}}])}(j.PureComponent);kRe(kV,"displayName","Legend");kRe(kV,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var Mjt=bie,Awn=Xrt,Ewn=qw,Pjt=Mjt?Mjt.isConcatSpreadable:void 0;function Twn(s){return Ewn(s)||Awn(s)||!!(Pjt&&s&&s[Pjt])}var Mwn=Twn,Pwn=vKt,Iwn=Mwn;function LKt(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=Iwn),a||(a=[]);++i0&&n(o)?t>1?LKt(o,t-1,n,r,a):Pwn(a,o):r||(a[a.length]=o)}return a}var RKt=LKt;function Lwn(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 Rwn=Lwn,Dwn=Rwn,Fwn=Dwn(),Own=Fwn,zwn=Own,Bwn=NRe;function $wn(s,t){return s&&zwn(s,t,Bwn)}var DKt=$wn,Uwn=_ie;function qwn(s,t){return function(n,r){if(n==null)return n;if(!Uwn(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 njn=sjn,i9e=zrt,rjn=Brt,ajn=h3,ijn=FKt,ojn=Qwn,ljn=wKt,cjn=njn,djn=CK,ujn=qw;function hjn(s,t,n){t.length?t=i9e(t,function(i){return ujn(i)?function(l){return rjn(l,i.length===1?i[0]:i)}:i}):t=[djn];var r=-1;t=i9e(t,ljn(ajn));var a=ijn(s,function(i,l,o){var c=i9e(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return ojn(a,function(i,l){return cjn(i,l,n)})}var mjn=hjn;function fjn(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 pjn=fjn,gjn=pjn,Ljt=Math.max;function xjn(s,t,n){return t=Ljt(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=Ljt(r.length-t,0),l=Array(i);++a0){if(++t>=Cjn)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var Mjn=Tjn,Pjn=Sjn,Ijn=Mjn,Ljn=Ijn(Pjn),Rjn=Ljn,Djn=CK,Fjn=yjn,Ojn=Rjn;function zjn(s,t){return Ojn(Fjn(s,t,Djn),s+"")}var Bjn=zjn,$jn=Rrt,Ujn=_ie,qjn=Qrt,Vjn=v6;function Hjn(s,t,n){if(!Vjn(n))return!1;var r=typeof t;return(r=="number"?Ujn(n)&&qjn(t,n.length):r=="string"&&t in n)?$jn(n[t],s):!1}var SRe=Hjn,Gjn=RKt,Wjn=mjn,Kjn=Bjn,Djt=SRe,Yjn=Kjn(function(s,t){if(s==null)return[];var n=t.length;return n>1&&Djt(s,t[0],t[1])?t=[]:n>2&&Djt(t[0],t[1],t[2])&&(t=[t[0]]),Wjn(s,Gjn(t,1),[])}),Zjn=Yjn;const sat=ru(Zjn);function Ese(s){"@babel/helpers - typeof";return Ese=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},Ese(s)}function iKe(){return iKe=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(UZ,"-left"),xi(n)&&t&&xi(t.x)&&n=t.y),"".concat(UZ,"-top"),xi(r)&&t&&xi(t.y)&&rx?Math.max(u,c[r]):Math.max(h,c[r])}function u2n(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 h2n(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=zjt({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=zjt({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=u2n({translateX:u,translateY:h,useTranslate3d:o})):d=c2n,{cssProperties:d,cssClasses:d2n({translateX:u,translateY:h,coordinate:n})}}function BG(s){"@babel/helpers - typeof";return BG=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},BG(s)}function Bjt(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 $jt(s){for(var t=1;tUjt||Math.abs(r.height-this.state.lastBoundingBox.height)>Ujt)&&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,v=a.useTranslate3d,y=a.viewBox,b=a.wrapperStyle,w=h2n({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:f,position:g,reverseDirection:x,tooltipBox:this.state.lastBoundingBox,useTranslate3d:v,viewBox:y}),S=w.cssClasses,A=w.cssProperties,E=$jt($jt({transition:m&&i?"transform ".concat(o,"ms ").concat(c):void 0},A),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&h?"visible":"hidden",position:"absolute",top:0,left:0},b);return Kt.createElement("div",{tabIndex:-1,className:S,style:E,ref:function(P){r.wrapperNode=P}},d)}}])}(j.PureComponent),w2n=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},b6={isSsr:w2n()};function $G(s){"@babel/helpers - typeof";return $G=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},$G(s)}function qjt(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 Vjt(s){for(var t=1;t0;return Kt.createElement(_2n,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:m,active:i,coordinate:u,hasPayload:E,offset:f,position:v,reverseDirection:y,useTranslate3d:b,viewBox:w,wrapperStyle:S},P2n(d,Vjt(Vjt({},this.props),{},{payload:A})))}}])}(j.PureComponent);nat(kg,"displayName","Tooltip");nat(kg,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!b6.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 I2n=u3,L2n=function(){return I2n.Date.now()},R2n=L2n,D2n=/\s/;function F2n(s){for(var t=s.length;t--&&D2n.test(s.charAt(t)););return t}var O2n=F2n,z2n=O2n,B2n=/^\s+/;function $2n(s){return s&&s.slice(0,z2n(s)+1).replace(B2n,"")}var U2n=$2n,q2n=U2n,Hjt=v6,V2n=vK,Gjt=NaN,H2n=/^[-+]0x[0-9a-f]+$/i,G2n=/^0b[01]+$/i,W2n=/^0o[0-7]+$/i,K2n=parseInt;function Y2n(s){if(typeof s=="number")return s;if(V2n(s))return Gjt;if(Hjt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Hjt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=q2n(s);var n=G2n.test(s);return n||W2n.test(s)?K2n(s.slice(2),n?2:8):H2n.test(s)?Gjt:+s}var qKt=Y2n,Z2n=v6,l9e=R2n,Wjt=qKt,X2n="Expected a function",Q2n=Math.max,J2n=Math.min;function eNn(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(X2n);t=Wjt(t)||0,Z2n(n)&&(u=!!n.leading,h="maxWait"in n,i=h?Q2n(Wjt(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(y,t),u?f(E):l}function x(E){var I=E-c,P=E-d,R=t-I;return h?J2n(R,i-P):R}function v(E){var I=E-c,P=E-d;return c===void 0||I>=t||I<0||h&&P>=i}function y(){var E=l9e();if(v(E))return b(E);o=setTimeout(y,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(l9e())}function A(){var E=l9e(),I=v(E);if(r=arguments,a=this,c=E,I){if(o===void 0)return g(c);if(h)return clearTimeout(o),o=setTimeout(y,t),f(c)}return o===void 0&&(o=setTimeout(y,t)),l}return A.cancel=w,A.flush=S,A}var tNn=eNn,sNn=tNn,nNn=v6,rNn="Expected a function";function aNn(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(rNn);return nNn(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),sNn(s,t,{leading:r,maxWait:t,trailing:a})}var iNn=aNn;const VKt=ru(iNn);function Mse(s){"@babel/helpers - typeof";return Mse=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},Mse(s)}function Kjt(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 zde(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(W=VKt(W,x,{trailing:!0,leading:!1}));var V=new ResizeObserver(W),G=A.current.getBoundingClientRect(),Z=G.width,X=G.height;return O(Z,X),V.observe(A.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;iC(h8(l)||h8(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),iC(!n||n>0,"The aspect(%s) must be greater than zero.",n);var G=h8(l)?W:l,Z=h8(c)?V:c;n&&n>0&&(G?Z=G/n:Z&&(G=Z*n),m&&Z>m&&(Z=m)),iC(G>0||Z>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,Z,l,c,u,h,n);var X=!Array.isArray(f)&&qE(f.type).endsWith("Chart");return Kt.Children.map(f,function(ae){return Kt.isValidElement(ae)?j.cloneElement(ae,zde({width:G,height:Z},X?{style:zde({height:"100%",width:"100%",maxHeight:Z,maxWidth:G},ae.props.style)}:{})):ae})},[n,f,c,m,h,u,R,l]);return Kt.createElement("div",{id:v?"".concat(v):void 0,className:sd("recharts-responsive-container",y),style:zde(zde({},S),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:m}),ref:A},U)}),KB=function(t){return null};KB.displayName="Cell";function Pse(s){"@babel/helpers - typeof";return Pse=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},Pse(s)}function Zjt(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 dKe(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||b6.isSsr)return{width:0,height:0};var r=bNn(n),a=JSON.stringify({text:t,copyStyle:r});if(M$.widthCache[a])return M$.widthCache[a];try{var i=document.getElementById(Xjt);i||(i=document.createElement("span"),i.setAttribute("id",Xjt),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=dKe(dKe({},vNn),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return M$.widthCache[a]=c,++M$.cacheCount>yNn&&(M$.cacheCount=0,M$.widthCache={}),c}catch{return{width:0,height:0}}},_Nn=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function Ise(s){"@babel/helpers - typeof";return Ise=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},Ise(s)}function tMe(s,t){return kNn(s)||NNn(s,t)||jNn(s,t)||wNn()}function wNn(){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 Qjt(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 Qjt(s,t)}}function Qjt(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 zNn(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 r2t(s,t){return qNn(s)||UNn(s,t)||$Nn(s,t)||BNn()}function BNn(){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 $Nn(s,t){if(s){if(typeof s=="string")return a2t(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 a2t(s,t)}}function a2t(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(Z,X){var ae=X.word,le=X.width,re=Z[Z.length-1];if(re&&(a==null||i||re.width+le+rX.width?Z:X})};if(!u)return f;for(var x="…",v=function(G){var Z=h.slice(0,G),X=KKt({breakAll:d,style:c,children:Z+x}).wordsWithComputedWidth,ae=m(X),le=ae.length>l||g(ae).width>Number(a);return[le,ae]},y=0,b=h.length-1,w=0,S;y<=b&&w<=h.length-1;){var A=Math.floor((y+b)/2),E=A-1,I=v(E),P=r2t(I,2),R=P[0],D=P[1],O=v(A),U=r2t(O,1),W=U[0];if(!R&&!W&&(y=A+1),R&&W&&(b=A-1),!R&&W){S=D;break}w++}return S||f},i2t=function(t){var n=Gc(t)?[]:t.toString().split(WKt);return[{words:n}]},HNn=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!b6.isSsr){var c,d,u=KKt({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,m=u.spaceWidth;c=h,d=m}else return i2t(a);return VNn({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return i2t(a)},o2t="#808080",eB=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,v=t.fill,y=v===void 0?o2t:v,b=n2t(t,FNn),w=j.useMemo(function(){return HNn({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,A=b.dy,E=b.angle,I=b.className,P=b.breakAll,R=n2t(b,ONn);if(!N0(r)||!N0(i))return null;var D=r+(xi(S)?S:0),O=i+(xi(A)?A:0),U;switch(x){case"start":U=c9e("calc(".concat(d,")"));break;case"middle":U=c9e("calc(".concat((w.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:U=c9e("calc(".concat(w.length-1," * -").concat(o,")"));break}var W=[];if(h){var V=w[0].width,G=b.width;W.push("scale(".concat((xi(G)?G/V:1)/V,")"))}return E&&W.push("rotate(".concat(E,", ").concat(D,", ").concat(O,")")),W.length&&(R.transform=W.join(" ")),Kt.createElement("text",uKe({},ll(R,!0),{x:D,y:O,className:sd("recharts-text",I),textAnchor:f,fill:y.includes("url")?o2t:y}),w.map(function(Z,X){var ae=Z.words.join(P?"":" ");return Kt.createElement("tspan",{x:D,dy:X===0?U:o,key:"".concat(ae,"-").concat(X)},ae)}))};function dL(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function GNn(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function rat(s){let t,n,r;s.length!==2?(t=dL,n=(o,c)=>dL(s(o),c),r=(o,c)=>s(o)-c):(t=s===dL||s===GNn?s:WNn,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 WNn(){return 0}function YKt(s){return s===null?NaN:+s}function*KNn(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const YNn=rat(dL),wie=YNn.right;rat(YKt).center;class l2t extends Map{constructor(t,n=QNn){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(c2t(this,t))}has(t){return super.has(c2t(this,t))}set(t,n){return super.set(ZNn(this,t),n)}delete(t){return super.delete(XNn(this,t))}}function c2t({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function ZNn({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function XNn({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function QNn(s){return s!==null&&typeof s=="object"?s.valueOf():s}function JNn(s=dL){if(s===dL)return ZKt;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 ZKt(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const ekn=Math.sqrt(50),tkn=Math.sqrt(10),skn=Math.sqrt(2);function sMe(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>=ekn?10:i>=tkn?5:i>=skn?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 u2t(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function XKt(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?ZKt:JNn(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));XKt(s,t,f,g,a)}const i=s[t];let l=n,o=r;for(qZ(s,n,t),a(s[r],i)>0&&qZ(s,n,r);l0;)--o}a(s[n],i)===0?qZ(s,n,o):(++o,qZ(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function qZ(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function nkn(s,t,n){if(s=Float64Array.from(KNn(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return u2t(s);if(t>=1)return d2t(s);var r,a=(r-1)*t,i=Math.floor(a),l=d2t(XKt(s,i).subarray(0,i+1)),o=u2t(s.subarray(i+1));return l+(o-l)*(a-i)}}function rkn(s,t,n=YKt){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 akn(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?$de(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?$de(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=okn.exec(s))?new vw(t[1],t[2],t[3],1):(t=lkn.exec(s))?new vw(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=ckn.exec(s))?$de(t[1],t[2],t[3],t[4]):(t=dkn.exec(s))?$de(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=ukn.exec(s))?y2t(t[1],t[2]/100,t[3]/100,1):(t=hkn.exec(s))?y2t(t[1],t[2]/100,t[3]/100,t[4]):h2t.hasOwnProperty(s)?p2t(h2t[s]):s==="transparent"?new vw(NaN,NaN,NaN,0):null}function p2t(s){return new vw(s>>16&255,s>>8&255,s&255,1)}function $de(s,t,n,r){return r<=0&&(s=t=n=NaN),new vw(s,t,n,r)}function pkn(s){return s instanceof jie||(s=Fse(s)),s?(s=s.rgb(),new vw(s.r,s.g,s.b,s.opacity)):new vw}function gKe(s,t,n,r){return arguments.length===1?pkn(s):new vw(s,t,n,r??1)}function vw(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}iat(vw,gKe,JKt(jie,{brighter(s){return s=s==null?nMe:Math.pow(nMe,s),new vw(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?Rse:Math.pow(Rse,s),new vw(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new vw(p7(this.r),p7(this.g),p7(this.b),rMe(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:g2t,formatHex:g2t,formatHex8:gkn,formatRgb:x2t,toString:x2t}));function g2t(){return`#${m8(this.r)}${m8(this.g)}${m8(this.b)}`}function gkn(){return`#${m8(this.r)}${m8(this.g)}${m8(this.b)}${m8((isNaN(this.opacity)?1:this.opacity)*255)}`}function x2t(){const s=rMe(this.opacity);return`${s===1?"rgb(":"rgba("}${p7(this.r)}, ${p7(this.g)}, ${p7(this.b)}${s===1?")":`, ${s})`}`}function rMe(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function p7(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function m8(s){return s=p7(s),(s<16?"0":"")+s.toString(16)}function y2t(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new $S(s,t,n,r)}function eYt(s){if(s instanceof $S)return new $S(s.h,s.s,s.l,s.opacity);if(s instanceof jie||(s=Fse(s)),!s)return new $S;if(s instanceof $S)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 $S(l,o,c,s.opacity)}function xkn(s,t,n,r){return arguments.length===1?eYt(s):new $S(s,t,n,r??1)}function $S(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}iat($S,xkn,JKt(jie,{brighter(s){return s=s==null?nMe:Math.pow(nMe,s),new $S(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?Rse:Math.pow(Rse,s),new $S(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 vw(d9e(s>=240?s-240:s+120,a,r),d9e(s,a,r),d9e(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new $S(v2t(this.h),Ude(this.s),Ude(this.l),rMe(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=rMe(this.opacity);return`${s===1?"hsl(":"hsla("}${v2t(this.h)}, ${Ude(this.s)*100}%, ${Ude(this.l)*100}%${s===1?")":`, ${s})`}`}}));function v2t(s){return s=(s||0)%360,s<0?s+360:s}function Ude(s){return Math.max(0,Math.min(1,s||0))}function d9e(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 oat=s=>()=>s;function ykn(s,t){return function(n){return s+n*t}}function vkn(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 bkn(s){return(s=+s)==1?tYt:function(t,n){return n-t?vkn(t,n,s):oat(isNaN(t)?n:t)}}function tYt(s,t){var n=t-s;return n?ykn(s,n):oat(isNaN(s)?t:s)}const b2t=function s(t){var n=bkn(t);function r(a,i){var l=n((a=gKe(a)).r,(i=gKe(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=tYt(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 _kn(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:aMe(r,a)})),n=u9e.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function Pkn(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?Ikn:Pkn,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),aMe)))(m)))},h.domain=function(m){return arguments.length?(s=Array.from(m,iMe),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=lat,u()},h.clamp=function(m){return arguments.length?(l=m?!0:v_,u()):l!==v_},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 cat(){return CRe()(v_,v_)}function Lkn(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function oMe(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 UG(s){return s=oMe(Math.abs(s)),s?s[1]:NaN}function Rkn(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 Dkn(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var Fkn=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Ose(s){if(!(t=Fkn.exec(s)))throw new Error("invalid format: "+s);var t;return new dat({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]})}Ose.prototype=dat.prototype;function dat(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+""}dat.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 Okn(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 lMe;function zkn(s,t){var n=oMe(s,t);if(!n)return lMe=void 0,s.toPrecision(t);var r=n[0],a=n[1],i=a-(lMe=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")+oMe(s,Math.max(0,t+i-1))[0]}function w2t(s,t){var n=oMe(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 j2t={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:Lkn,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)=>w2t(s*100,t),r:w2t,s:zkn,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function N2t(s){return s}var k2t=Array.prototype.map,S2t=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Bkn(s){var t=s.grouping===void 0||s.thousands===void 0?N2t:Rkn(k2t.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?N2t:Dkn(k2t.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=Ose(h);var f=h.fill,g=h.align,x=h.sign,v=h.symbol,y=h.zero,b=h.width,w=h.comma,S=h.precision,A=h.trim,E=h.type;E==="n"?(w=!0,E="g"):j2t[E]||(S===void 0&&(S=12),A=!0,E="g"),(y||f==="0"&&g==="=")&&(y=!0,f="0",g="=");var I=(m&&m.prefix!==void 0?m.prefix:"")+(v==="$"?n:v==="#"&&/[boxX]/.test(E)?"0"+E.toLowerCase():""),P=(v==="$"?r:/[%p]/.test(E)?l:"")+(m&&m.suffix!==void 0?m.suffix:""),R=j2t[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,Z,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),A&&(U=Okn(U)),ae&&+U==0&&x!=="+"&&(ae=!1),W=(ae?x==="("?x:o:x==="-"||x==="("?"":x)+W,V=(E==="s"&&!isNaN(U)&&lMe!==void 0?S2t[8+lMe/3]:"")+V+(ae&&x==="("?")":""),D){for(G=-1,Z=U.length;++GX||X>57){V=(X===46?a+U.slice(G+1):U.slice(G))+V,U=U.slice(0,G);break}}}w&&!y&&(U=t(U,1/0));var le=W.length+U.length+V.length,re=le>1)+W+U+V+re.slice(le);break;default:U=re+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(UG(m)/3)))*3,g=Math.pow(10,-f),x=d((h=Ose(h),h.type="f",h),{suffix:S2t[8+f/3]});return function(v){return x(g*v)}}return{format:d,formatPrefix:u}}var qde,uat,sYt;$kn({thousands:",",grouping:[3],currency:["$",""]});function $kn(s){return qde=Bkn(s),uat=qde.format,sYt=qde.formatPrefix,qde}function Ukn(s){return Math.max(0,-UG(Math.abs(s)))}function qkn(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(UG(t)/3)))*3-UG(Math.abs(s)))}function Vkn(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,UG(t)-UG(s))+1}function nYt(s,t,n,r){var a=fKe(s,t,n),i;switch(r=Ose(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=qkn(a,l))&&(r.precision=i),sYt(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=Vkn(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=Ukn(a))&&(r.precision=i-(r.type==="%")*2);break}}return uat(r)}function _6(s){var t=s.domain;return s.ticks=function(n){var r=t();return hKe(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return nYt(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=mKe(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 cMe(){var s=cat();return s.copy=function(){return Nie(s,cMe())},Ck.apply(s,arguments),_6(s)}function rYt(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,iMe),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return rYt(s).unknown(t)},s=arguments.length?Array.from(s,iMe):[0,1],_6(n)}function aYt(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 Ykn(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 E2t(s){return(t,n)=>-s(-t,n)}function hat(s){const t=s(C2t,A2t),n=t.domain;let r=10,a,i;function l(){return a=Ykn(r),i=Kkn(r),n()[0]<0?(a=E2t(a),i=E2t(i),s(Hkn,Gkn)):s(C2t,A2t),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;y.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;y.push(x)}y.length*2{if(o==null&&(o=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=Ose(c)).precision==null&&(c.trim=!0),c=uat(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(aYt(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function iYt(){const s=hat(CRe()).domain([1,10]);return s.copy=()=>Nie(s,iYt()).base(s.base()),Ck.apply(s,arguments),s}function T2t(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function M2t(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function mat(s){var t=1,n=s(T2t(t),M2t(t));return n.constant=function(r){return arguments.length?s(T2t(t=+r),M2t(t)):t},_6(n)}function oYt(){var s=mat(CRe());return s.copy=function(){return Nie(s,oYt()).constant(s.constant())},Ck.apply(s,arguments)}function P2t(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function Zkn(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function Xkn(s){return s<0?-s*s:s*s}function fat(s){var t=s(v_,v_),n=1;function r(){return n===1?s(v_,v_):n===.5?s(Zkn,Xkn):s(P2t(n),P2t(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},_6(t)}function pat(){var s=fat(CRe());return s.copy=function(){return Nie(s,pat()).exponent(s.exponent())},Ck.apply(s,arguments),s}function Qkn(){return pat.apply(null,arguments).exponent(.5)}function I2t(s){return Math.sign(s)*s*s}function Jkn(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function lYt(){var s=cat(),t=[0,1],n=!1,r;function a(i){var l=Jkn(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(I2t(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,iMe)).map(I2t)),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 lYt(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},Ck.apply(a,arguments),_6(a)}function cYt(){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 dYt().domain([s,t]).range(a).unknown(i)},Ck.apply(_6(l),arguments)}function uYt(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[wie(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 uYt().domain(s).range(t).unknown(n)},Ck.apply(a,arguments)}const h9e=new Date,m9e=new Date;function z0(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(dz0(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)=>(h9e.setTime(+i),m9e.setTime(+l),s(h9e),s(m9e),Math.floor(n(h9e,m9e))),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 dMe=z0(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);dMe.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?z0(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):dMe);dMe.range;const _E=1e3,$N=_E*60,wE=$N*60,hT=wE*24,gat=hT*7,L2t=hT*30,f9e=hT*365,f8=z0(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*_E)},(s,t)=>(t-s)/_E,s=>s.getUTCSeconds());f8.range;const xat=z0(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*_E)},(s,t)=>{s.setTime(+s+t*$N)},(s,t)=>(t-s)/$N,s=>s.getMinutes());xat.range;const yat=z0(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*$N)},(s,t)=>(t-s)/$N,s=>s.getUTCMinutes());yat.range;const vat=z0(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*_E-s.getMinutes()*$N)},(s,t)=>{s.setTime(+s+t*wE)},(s,t)=>(t-s)/wE,s=>s.getHours());vat.range;const bat=z0(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*wE)},(s,t)=>(t-s)/wE,s=>s.getUTCHours());bat.range;const kie=z0(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*$N)/hT,s=>s.getDate()-1);kie.range;const ARe=z0(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/hT,s=>s.getUTCDate()-1);ARe.range;const hYt=z0(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/hT,s=>Math.floor(s/hT));hYt.range;function YB(s){return z0(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())*$N)/gat)}const ERe=YB(0),uMe=YB(1),eSn=YB(2),tSn=YB(3),qG=YB(4),sSn=YB(5),nSn=YB(6);ERe.range;uMe.range;eSn.range;tSn.range;qG.range;sSn.range;nSn.range;function ZB(s){return z0(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)/gat)}const TRe=ZB(0),hMe=ZB(1),rSn=ZB(2),aSn=ZB(3),VG=ZB(4),iSn=ZB(5),oSn=ZB(6);TRe.range;hMe.range;rSn.range;aSn.range;VG.range;iSn.range;oSn.range;const _at=z0(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());_at.range;const wat=z0(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());wat.range;const mT=z0(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());mT.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:z0(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)});mT.range;const fT=z0(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());fT.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:z0(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)});fT.range;function mYt(s,t,n,r,a,i){const l=[[f8,1,_E],[f8,5,5*_E],[f8,15,15*_E],[f8,30,30*_E],[i,1,$N],[i,5,5*$N],[i,15,15*$N],[i,30,30*$N],[a,1,wE],[a,3,3*wE],[a,6,6*wE],[a,12,12*wE],[r,1,hT],[r,2,2*hT],[n,1,gat],[t,1,L2t],[t,3,3*L2t],[s,1,f9e]];function o(d,u,h){const m=uv).right(l,m);if(f===l.length)return s.every(fKe(d/f9e,u/f9e,h));if(f===0)return dMe.every(Math.max(fKe(d,u,h),1));const[g,x]=l[m/l[f-1][2]53)return null;"w"in Ne||(Ne.w=1),"Z"in Ne?(Se=g9e(VZ(Ne.y,0,1)),Ae=Se.getUTCDay(),Se=Ae>4||Ae===0?hMe.ceil(Se):hMe(Se),Se=ARe.offset(Se,(Ne.V-1)*7),Ne.y=Se.getUTCFullYear(),Ne.m=Se.getUTCMonth(),Ne.d=Se.getUTCDate()+(Ne.w+6)%7):(Se=p9e(VZ(Ne.y,0,1)),Ae=Se.getDay(),Se=Ae>4||Ae===0?uMe.ceil(Se):uMe(Se),Se=kie.offset(Se,(Ne.V-1)*7),Ne.y=Se.getFullYear(),Ne.m=Se.getMonth(),Ne.d=Se.getDate()+(Ne.w+6)%7)}else("W"in Ne||"U"in Ne)&&("w"in Ne||(Ne.w="u"in Ne?Ne.u%7:"W"in Ne?1:0),Ae="Z"in Ne?g9e(VZ(Ne.y,0,1)).getUTCDay():p9e(VZ(Ne.y,0,1)).getDay(),Ne.m=0,Ne.d="W"in Ne?(Ne.w+6)%7+Ne.W*7-(Ae+5)%7:Ne.w+Ne.U*7-(Ae+6)%7);return"Z"in Ne?(Ne.H+=Ne.Z/100|0,Ne.M+=Ne.Z%100,g9e(Ne)):p9e(Ne)}}function P(ke,Ie,Fe,Ne){for(var Be=0,Se=Ie.length,Ae=Fe.length,Ce,qe;Be=Ae)return-1;if(Ce=Ie.charCodeAt(Be++),Ce===37){if(Ce=Ie.charAt(Be++),qe=A[Ce in R2t?Ie.charAt(Be++):Ce],!qe||(Ne=qe(ke,Fe,Ne))<0)return-1}else if(Ce!=Fe.charCodeAt(Ne++))return-1}return Ne}function R(ke,Ie,Fe){var Ne=d.exec(Ie.slice(Fe));return Ne?(ke.p=u.get(Ne[0].toLowerCase()),Fe+Ne[0].length):-1}function D(ke,Ie,Fe){var Ne=f.exec(Ie.slice(Fe));return Ne?(ke.w=g.get(Ne[0].toLowerCase()),Fe+Ne[0].length):-1}function O(ke,Ie,Fe){var Ne=h.exec(Ie.slice(Fe));return Ne?(ke.w=m.get(Ne[0].toLowerCase()),Fe+Ne[0].length):-1}function U(ke,Ie,Fe){var Ne=y.exec(Ie.slice(Fe));return Ne?(ke.m=b.get(Ne[0].toLowerCase()),Fe+Ne[0].length):-1}function W(ke,Ie,Fe){var Ne=x.exec(Ie.slice(Fe));return Ne?(ke.m=v.get(Ne[0].toLowerCase()),Fe+Ne[0].length):-1}function V(ke,Ie,Fe){return P(ke,t,Ie,Fe)}function G(ke,Ie,Fe){return P(ke,n,Ie,Fe)}function Z(ke,Ie,Fe){return P(ke,r,Ie,Fe)}function X(ke){return l[ke.getDay()]}function ae(ke){return i[ke.getDay()]}function le(ke){return c[ke.getMonth()]}function re(ke){return o[ke.getMonth()]}function te(ke){return a[+(ke.getHours()>=12)]}function J(ke){return 1+~~(ke.getMonth()/3)}function ce(ke){return l[ke.getUTCDay()]}function ve(ke){return i[ke.getUTCDay()]}function fe(ke){return c[ke.getUTCMonth()]}function ue(ke){return o[ke.getUTCMonth()]}function be(ke){return a[+(ke.getUTCHours()>=12)]}function Ee(ke){return 1+~~(ke.getUTCMonth()/3)}return{format:function(ke){var Ie=E(ke+="",w);return Ie.toString=function(){return ke},Ie},parse:function(ke){var Ie=I(ke+="",!1);return Ie.toString=function(){return ke},Ie},utcFormat:function(ke){var Ie=E(ke+="",S);return Ie.toString=function(){return ke},Ie},utcParse:function(ke){var Ie=I(ke+="",!0);return Ie.toString=function(){return ke},Ie}}}var R2t={"-":"",_:" ",0:"0"},Iv=/^\s*\d+/,mSn=/^%/,fSn=/[\\^$*+?|[\]().{}]/g;function qh(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=Iv.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function xSn(s,t,n){var r=Iv.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function ySn(s,t,n){var r=Iv.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function vSn(s,t,n){var r=Iv.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function bSn(s,t,n){var r=Iv.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function D2t(s,t,n){var r=Iv.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function F2t(s,t,n){var r=Iv.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function _Sn(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 wSn(s,t,n){var r=Iv.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=Iv.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function O2t(s,t,n){var r=Iv.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function NSn(s,t,n){var r=Iv.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function z2t(s,t,n){var r=Iv.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function kSn(s,t,n){var r=Iv.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function SSn(s,t,n){var r=Iv.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function CSn(s,t,n){var r=Iv.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function ASn(s,t,n){var r=Iv.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function ESn(s,t,n){var r=mSn.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function TSn(s,t,n){var r=Iv.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function MSn(s,t,n){var r=Iv.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function B2t(s,t){return qh(s.getDate(),t,2)}function PSn(s,t){return qh(s.getHours(),t,2)}function ISn(s,t){return qh(s.getHours()%12||12,t,2)}function LSn(s,t){return qh(1+kie.count(mT(s),s),t,3)}function fYt(s,t){return qh(s.getMilliseconds(),t,3)}function RSn(s,t){return fYt(s,t)+"000"}function DSn(s,t){return qh(s.getMonth()+1,t,2)}function FSn(s,t){return qh(s.getMinutes(),t,2)}function OSn(s,t){return qh(s.getSeconds(),t,2)}function zSn(s){var t=s.getDay();return t===0?7:t}function BSn(s,t){return qh(ERe.count(mT(s)-1,s),t,2)}function pYt(s){var t=s.getDay();return t>=4||t===0?qG(s):qG.ceil(s)}function $Sn(s,t){return s=pYt(s),qh(qG.count(mT(s),s)+(mT(s).getDay()===4),t,2)}function USn(s){return s.getDay()}function qSn(s,t){return qh(uMe.count(mT(s)-1,s),t,2)}function VSn(s,t){return qh(s.getFullYear()%100,t,2)}function HSn(s,t){return s=pYt(s),qh(s.getFullYear()%100,t,2)}function GSn(s,t){return qh(s.getFullYear()%1e4,t,4)}function WSn(s,t){var n=s.getDay();return s=n>=4||n===0?qG(s):qG.ceil(s),qh(s.getFullYear()%1e4,t,4)}function KSn(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+qh(t/60|0,"0",2)+qh(t%60,"0",2)}function $2t(s,t){return qh(s.getUTCDate(),t,2)}function YSn(s,t){return qh(s.getUTCHours(),t,2)}function ZSn(s,t){return qh(s.getUTCHours()%12||12,t,2)}function XSn(s,t){return qh(1+ARe.count(fT(s),s),t,3)}function gYt(s,t){return qh(s.getUTCMilliseconds(),t,3)}function QSn(s,t){return gYt(s,t)+"000"}function JSn(s,t){return qh(s.getUTCMonth()+1,t,2)}function eCn(s,t){return qh(s.getUTCMinutes(),t,2)}function tCn(s,t){return qh(s.getUTCSeconds(),t,2)}function sCn(s){var t=s.getUTCDay();return t===0?7:t}function nCn(s,t){return qh(TRe.count(fT(s)-1,s),t,2)}function xYt(s){var t=s.getUTCDay();return t>=4||t===0?VG(s):VG.ceil(s)}function rCn(s,t){return s=xYt(s),qh(VG.count(fT(s),s)+(fT(s).getUTCDay()===4),t,2)}function aCn(s){return s.getUTCDay()}function iCn(s,t){return qh(hMe.count(fT(s)-1,s),t,2)}function oCn(s,t){return qh(s.getUTCFullYear()%100,t,2)}function lCn(s,t){return s=xYt(s),qh(s.getUTCFullYear()%100,t,2)}function cCn(s,t){return qh(s.getUTCFullYear()%1e4,t,4)}function dCn(s,t){var n=s.getUTCDay();return s=n>=4||n===0?VG(s):VG.ceil(s),qh(s.getUTCFullYear()%1e4,t,4)}function uCn(){return"+0000"}function U2t(){return"%"}function q2t(s){return+s}function V2t(s){return Math.floor(+s/1e3)}var P$,yYt,vYt;hCn({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 hCn(s){return P$=hSn(s),yYt=P$.format,P$.parse,vYt=P$.utcFormat,P$.utcParse,P$}function mCn(s){return new Date(s)}function fCn(s){return s instanceof Date?+s:+new Date(+s)}function jat(s,t,n,r,a,i,l,o,c,d){var u=cat(),h=u.invert,m=u.domain,f=d(".%L"),g=d(":%S"),x=d("%I:%M"),v=d("%I %p"),y=d("%a %d"),b=d("%b %d"),w=d("%B"),S=d("%Y");function A(E){return(c(E)t(a/(s.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>nkn(s,i/r))},n.copy=function(){return jYt(t).domain(s)},RT.apply(n,arguments)}function PRe(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=v_,u,h=!1,m;function f(x){return isNaN(x=+x)?m:(x=.5+((x=+u(x))-i)*(r*xt}var CYt=_Cn,wCn=IRe,jCn=CYt,NCn=CK;function kCn(s){return s&&s.length?wCn(s,NCn,jCn):void 0}var SCn=kCn;const vI=ru(SCn);function CCn(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)*_p;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 VE(this,new this.constructor(s))};Io.dividedToIntegerBy=Io.idiv=function(s){var t=this,n=t.constructor;return Sf(VE(t,new n(s),0,1),n.precision)};Io.equals=Io.eq=function(s){return!this.cmp(s)};Io.exponent=function(){return Uy(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(Kj))throw Error(uk+"NaN");if(n.s<1)throw Error(uk+(n.s?"NaN":"-Infinity"));return n.eq(Kj)?new r(0):(Yp=!1,t=VE(zse(n,i),zse(s,i),i),Yp=!0,Sf(t,a))};Io.minus=Io.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?PYt(t,s):TYt(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(uk+"NaN");return n.s?(Yp=!1,t=VE(n,s,0,1).times(s),Yp=!0,n.minus(t)):Sf(new r(n),a)};Io.naturalExponential=Io.exp=function(){return MYt(this)};Io.naturalLogarithm=Io.ln=function(){return zse(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?TYt(t,s):PYt(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(g7+s);if(t=Uy(a)+1,r=a.d.length-1,n=r*_p+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(uk+"NaN")}for(s=Uy(o),Yp=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=g4(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=TK((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(VE(o,i,l+2)).times(.5),g4(i.d).slice(0,l)===(t=g4(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(Sf(i,n+1,0),i.times(i).eq(o)){r=i;break}}else if(t!="9999")break;l+=4}return Yp=!0,Sf(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%ov|0,t=o/ov|0;i[a]=(i[a]+t)%ov|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,Yp?Sf(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:(Z4(s,0,EK),t===void 0?t=r.rounding:Z4(t,0,8),Sf(n,s+Uy(n)+1,t))};Io.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=sB(r,!0):(Z4(s,0,EK),t===void 0?t=a.rounding:Z4(t,0,8),r=Sf(new a(r),s+1,t),n=sB(r,!0,s+1)),n};Io.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?sB(a):(Z4(s,0,EK),t===void 0?t=i.rounding:Z4(t,0,8),r=Sf(new i(a),s+Uy(a)+1,t),n=sB(r.abs(),!1,s+Uy(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};Io.toInteger=Io.toint=function(){var s=this,t=s.constructor;return Sf(new t(s),Uy(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(Kj);if(o=new c(o),!o.s){if(s.s<1)throw Error(uk+"Infinity");return o}if(o.eq(Kj))return o;if(r=c.precision,s.eq(Kj))return Sf(o,r);if(t=s.e,n=s.d.length-1,l=t>=n,i=o.s,l){if((n=u<0?-u:u)<=EYt){for(a=new c(Kj),t=Math.ceil(r/_p+4),Yp=!1;n%2&&(a=a.times(o),W2t(a.d,t)),n=TK(n/2),n!==0;)o=o.times(o),W2t(o.d,t);return Yp=!0,s.s<0?new c(Kj).div(a):Sf(a,r)}}else if(i<0)throw Error(uk+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,Yp=!1,a=s.times(zse(o,r+d)),Yp=!0,a=MYt(a),a.s=i,a};Io.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=Uy(a),r=sB(a,n<=i.toExpNeg||n>=i.toExpPos)):(Z4(s,1,EK),t===void 0?t=i.rounding:Z4(t,0,8),a=Sf(new i(a),s,t),n=Uy(a),r=sB(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):(Z4(s,1,EK),t===void 0?t=r.rounding:Z4(t,0,8)),Sf(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=Uy(s),n=s.constructor;return sB(s,t<=n.toExpNeg||t>=n.toExpPos)};function TYt(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)),Yp?Sf(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/_p),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)/ov|0,c[i]%=ov;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,Yp?Sf(t,h):t}function Z4(s,t,n){if(s!==~~s||sn)throw Error(g7+s)}function g4(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,v,y,b,w,S,A,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(uk+"Division by zero");for(c=r.e-a.e,I=U.length,A=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+(Uy(r)-Uy(a))+1:b=i,b<0)return new R(0);if(b=b/_p+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,A=O.length),S=I,x=O.slice(0,I),v=x.length;v=ov/2&&++E;do u=0,o=t(U,x,I,v),o<0?(y=x[0],I!=v&&(y=y*ov+(x[1]||0)),u=y/E|0,u>1?(u>=ov&&(u=ov-1),h=s(U,u),m=h.length,v=x.length,o=t(h,x,m,v),o==1&&(u--,n(h,I16)throw Error(Sat+Uy(s));if(!s.s)return new u(Kj);for(Yp=!1,o=h,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(IO(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(Kj),u.precision=o;;){if(a=Sf(a.times(s),o),n=n.times(++c),l=i.plus(VE(a,n,o)),g4(l.d).slice(0,o)===g4(i.d).slice(0,o)){for(;d--;)i=Sf(i.times(i),o);return u.precision=h,t==null?(Yp=!0,Sf(i,h)):i}i=l}}function Uy(s){for(var t=s.e*_p,n=s.d[0];n>=10;n/=10)t++;return t}function x9e(s,t,n){if(t>s.LN10.sd())throw Yp=!0,n&&(s.precision=n),Error(uk+"LN10 precision limit exceeded");return Sf(new s(s.LN10),t)}function fP(s){for(var t="";s--;)t+="0";return t}function zse(s,t){var n,r,a,i,l,o,c,d,u,h=1,m=10,f=s,g=f.d,x=f.constructor,v=x.precision;if(f.s<1)throw Error(uk+(f.s?"NaN":"-Infinity"));if(f.eq(Kj))return new x(0);if(t==null?(Yp=!1,d=v):d=t,f.eq(10))return t==null&&(Yp=!0),x9e(x,d);if(d+=m,x.precision=d,n=g4(g),r=n.charAt(0),i=Uy(f),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)f=f.times(s),n=g4(f.d),r=n.charAt(0),h++;i=Uy(f),r>1?(f=new x("0."+n),i++):f=new x(r+"."+n.slice(1))}else return c=x9e(x,d+2,v).times(i+""),f=zse(new x(r+"."+n.slice(1)),d-m).plus(c),x.precision=v,t==null?(Yp=!0,Sf(f,v)):f;for(o=l=f=VE(f.minus(Kj),f.plus(Kj),d),u=Sf(f.times(f),d),a=3;;){if(l=Sf(l.times(u),d),c=o.plus(VE(l,new x(a),d)),g4(c.d).slice(0,d)===g4(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(x9e(x,d+2,v).times(i+""))),o=VE(o,new x(h),d),x.precision=v,t==null?(Yp=!0,Sf(o,v)):o;o=c,a+=2}}function G2t(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=TK(n/_p),s.d=[],r=(n+1)%_p,n<0&&(r+=_p),rmMe||s.e<-mMe))throw Error(Sat+n)}else s.s=0,s.e=0,s.d=[0];return s}function Sf(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+=_p,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/_p),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=_p,a=r-_p+l}if(n!==void 0&&(i=IO(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/IO(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=Uy(s),h.length=1,t=t-i-1,h[0]=IO(10,(_p-t%_p)%_p),s.e=TK(-t/_p)||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=IO(10,_p-r),h[u]=a>0?(d/IO(10,l-a)%IO(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==ov&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=ov)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(Yp&&(s.e>mMe||s.e<-mMe))throw Error(Sat+Uy(s));return s}function PYt(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),Yp?Sf(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/_p),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)+fP(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+fP(-a-1)+i,n&&(r=n-l)>0&&(i+=fP(r))):a>=l?(i+=fP(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+fP(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=fP(r))),s.s<0?"-"+i:i}function W2t(s,t){if(s.length>t)return s.length=t,!0}function IYt(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(g7+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 G2t(l,i.toString())}else if(typeof i!="string")throw Error(g7+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,KCn.test(i))G2t(l,i);else throw Error(g7+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=IYt,a.config=a.set=YCn,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(g7+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(g7+n+": "+r);return this}var Cat=IYt(WCn);Kj=new Cat(1);const Ym=Cat;function ZCn(s){return e5n(s)||JCn(s)||QCn(s)||XCn()}function XCn(){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 QCn(s,t){if(s){if(typeof s=="string")return vKe(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 vKe(s,t)}}function JCn(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function e5n(s){if(Array.isArray(s))return vKe(s)}function vKe(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,K2t(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 p5n(s){if(Array.isArray(s))return s}function OYt(s){var t=Bse(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function zYt(s,t,n){if(s.lte(0))return new Ym(0);var r=DRe.getDigitCount(s.toNumber()),a=new Ym(10).pow(r),i=s.div(a),l=r!==1?.05:.1,o=new Ym(Math.ceil(i.div(l).toNumber())).add(n).mul(l),c=o.mul(a);return t?c:new Ym(Math.ceil(c))}function g5n(s,t,n){var r=1,a=new Ym(s);if(!a.isint()&&n){var i=Math.abs(s);i<1?(r=new Ym(10).pow(DRe.getDigitCount(s)-1),a=new Ym(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new Ym(Math.floor(s)))}else s===0?a=new Ym(Math.floor((t-1)/2)):n||(a=new Ym(Math.floor(s)));var l=Math.floor((t-1)/2),o=r5n(n5n(function(c){return a.add(new Ym(c-l).mul(r)).toNumber()}),bKe);return o(0,t)}function BYt(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 Ym(0),tickMin:new Ym(0),tickMax:new Ym(0)};var i=zYt(new Ym(t).sub(s).div(n-1),r,a),l;s<=0&&t>=0?l=new Ym(0):(l=new Ym(s).add(t).div(2),l=l.sub(new Ym(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new Ym(t).sub(l).div(i).toNumber()),d=o+c+1;return d>n?BYt(s,t,n,r,a+1):(d0?c+(n-d):c,o=t>0?o:o+(n-d)),{step:i,tickMin:l.sub(new Ym(o).mul(i)),tickMax:l.add(new Ym(c).mul(i))})}function x5n(s){var t=Bse(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=OYt([n,r]),c=Bse(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(wKe(bKe(0,a-1).map(function(){return 1/0}))):[].concat(wKe(bKe(0,a-1).map(function(){return-1/0})),[u]);return n>r?_Ke(h):h}if(d===u)return g5n(d,a,i);var m=BYt(d,u,l,i),f=m.step,g=m.tickMin,x=m.tickMax,v=DRe.rangeStep(g,x.add(new Ym(.1).mul(f)),f);return n>r?_Ke(v):v}function y5n(s,t){var n=Bse(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=OYt([r,a]),o=Bse(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=zYt(new Ym(d).sub(c).div(u-1),i,0),m=[].concat(wKe(DRe.rangeStep(new Ym(c),new Ym(d).sub(new Ym(.99).mul(h)),h)),[d]);return r>a?_Ke(m):m}var v5n=DYt(x5n),b5n=DYt(y5n),_5n="Invariant failed";function nB(s,t){throw new Error(_5n)}var w5n=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function HG(s){"@babel/helpers - typeof";return HG=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},HG(s)}function fMe(){return fMe=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 E5n(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 T5n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function M5n(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(x_(h-u)!==x_(m-h)){var g=[];if(x_(m-h)===x_(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 v=m+c[1]-c[0];g[0]=Math.min(h,(v+h)/2),g[1]=Math.max(h,(v+h)/2)}var y=[Math.min(h,(f+h)/2),Math.max(h,(f+h)/2)];if(t>y[0]&&t<=y[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},Aat=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?mx(mx({},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},K5n=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(y&&y.length){var b=y[0].type.defaultProps,w=b!==void 0?mx(mx({},b),y[0].props):y[0].props,S=w.barSize,A=w[v];l[A]||(l[A]=[]);var E=Gc(S)?n:S;l[A].push({item:y[0],stackList:y.slice(1),barSize:Gc(E)?void 0:y_(E,r,0)})}}return l},Y5n=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=y_(n,a,0,!0),u,h=[];if(l[0].barSize===+l[0].barSize){var m=!1,f=a/c,g=l.reduce(function(S,A){return S+A.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,v={offset:x-d,size:0};u=l.reduce(function(S,A){var E={item:A.item,position:{offset:v.offset+v.size+d,size:m?f:A.barSize}},I=[].concat(X2t(S),[E]);return v=I[I.length-1].position,A.stackList&&A.stackList.length&&A.stackList.forEach(function(P){I.push({item:P,position:v})}),I},h)}else{var y=y_(r,a,0,!0);a-2*y-(c-1)*d<=0&&(d=0);var b=(a-2*y-(c-1)*d)/c;b>1&&(b>>=0);var w=o===+o?Math.min(b,o):b;u=l.reduce(function(S,A,E){var I=[].concat(X2t(S),[{item:A.item,position:{offset:y+(b+d)*E+(b-w)/2,size:w}}]);return A.stackList&&A.stackList.length&&A.stackList.forEach(function(P){I.push({item:P,position:I[I.length-1].position})}),I},h)}return u},Z5n=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=VYt({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"&&xi(t[f]))return mx(mx({},t),{},CV({},f,t[f]+(h||0)));if((x==="horizontal"||x==="vertical"&&f==="center")&&g!=="middle"&&xi(t[g]))return mx(mx({},t),{},CV({},g,t[g]+(m||0)))}return t},X5n=function(t,n,r){return Gc(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},HYt=function(t,n,r,a,i){var l=n.props.children,o=x2(l,Sie).filter(function(d){return X5n(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=ny(u,r);if(Gc(h))return d;var m=Array.isArray(h)?[LRe(h),vI(h)]:[h,h],f=c.reduce(function(g,x){var v=ny(u,x,0),y=m[0]-Math.abs(Array.isArray(v)?v[0]:v),b=m[1]+Math.abs(Array.isArray(v)?v[1]:v);return[Math.min(y,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},Q5n=function(t,n,r,a,i){var l=n.map(function(o){return HYt(t,o,r,i,a)}).filter(function(o){return!Gc(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},GYt=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&HYt(t,c,d,a)||Bee(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?x_(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!NK(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}})},y9e=new WeakMap,Vde=function(t,n){if(typeof n!="function")return t;y9e.has(t)||y9e.set(t,new WeakMap);var r=y9e.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},YYt=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:Lse(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:cMe(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:zee(),realScaleType:"point"}:i==="category"?{scale:Lse(),realScaleType:"band"}:{scale:cMe(),realScaleType:"linear"};if(Q7(a)){var c="scale".concat(bRe(a));return{scale:(H2t[c]||zee)(),realScaleType:H2t[c]?c:"point"}}return hc(a)?{scale:a}:{scale:zee(),realScaleType:"point"}},J2t=1e-4,ZYt=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])-J2t,l=Math.max(a[0],a[1])+J2t,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},J5n=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])}},s4n=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)}},n4n={sign:t4n,expand:wyn,none:FG,silhouette:jyn,wiggle:Nyn,positive:s4n},r4n=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=n4n[r],l=_yn().keys(a).value(function(o,c){return+ny(o,c,0)}).order(ZWe).offset(i);return l(t)},a4n=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?mx(mx({},m.type.defaultProps),m.props):m.props,x=g.stackId,v=g.hide;if(v)return h;var y=g[r],b=h[y]||{hasStack:!1,stackGroups:{}};if(N0(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[WB("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[m]};return mx(mx({},h),{},CV({},y,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,v){var y=f.stackGroups[v];return mx(mx({},x),{},CV({},v,{numericAxisId:r,cateAxisId:a,items:y.items,stackedData:r4n(t,y.items,i)}))},g)}return mx(mx({},h),{},CV({},m,f))},u)},XYt=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=v5n(d,i,o);return t.domain([LRe(u),vI(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),m=b5n(h,i,o);return{niceTicks:m}}return null};function gMe(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&&!Gc(a[t.dataKey])){var o=$Te(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=ny(a,Gc(l)?t.dataKey:l);return Gc(c)?null:t.scale(c)}var eNt=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=ny(l,n.dataKey,n.domain[o]);return Gc(c)?null:n.scale(c)-i/2+a},i4n=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]},o4n=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?mx(mx({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(N0(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},l4n=function(t){return t.reduce(function(n,r){return[LRe(r.concat([n[0]]).filter(xi)),vI(r.concat([n[1]]).filter(xi))]},[1/0,-1/0])},QYt=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=l4n(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})},tNt=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,sNt=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,SKe=function(t,n,r){if(hc(t))return t(n,r);if(!Array.isArray(t))return n;var a=[];if(xi(t[0]))a[0]=r?t[0]:Math.min(t[0],n[0]);else if(tNt.test(t[0])){var i=+tNt.exec(t[0])[1];a[0]=n[0]-i}else hc(t[0])?a[0]=t[0](n[0]):a[0]=n[0];if(xi(t[1]))a[1]=r?t[1]:Math.max(t[1],n[1]);else if(sNt.test(t[1])){var l=+sNt.exec(t[1])[1];a[1]=n[1]+l}else hc(t[1])?a[1]=t[1](n[1]):a[1]=n[1];return a},xMe=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=sat(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},x4n=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=y_(t.cx,l,l/2),h=y_(t.cy,o,o/2),m=tZt(l,o,r),f=y_(t.innerRadius,m,0),g=y_(t.outerRadius,m,m*.8),x=Object.keys(n);return x.reduce(function(v,y){var b=n[y],w=b.domain,S=b.reversed,A;if(Gc(b.range))a==="angleAxis"?A=[c,d]:a==="radiusAxis"&&(A=[f,g]),S&&(A=[A[1],A[0]]);else{A=b.range;var E=A,I=u4n(E,2);c=I[0],d=I[1]}var P=YYt(b,i),R=P.realScaleType,D=P.scale;D.domain(w).range(A),ZYt(D);var O=XYt(D,CA(CA({},b),{},{realScaleType:R})),U=CA(CA(CA({},b),O),{},{range:A,radius:g,realScaleType:R,scale:D,cx:u,cy:h,innerRadius:f,outerRadius:g,startAngle:c,endAngle:d});return CA(CA({},v),{},eZt({},y,U))},{})},y4n=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))},v4n=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=y4n({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}},b4n=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}},_4n=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},iNt=function(t,n){var r=t.x,a=t.y,i=v4n({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=b4n(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?CA(CA({},n),{},{radius:l,angle:_4n(f,n)}):null},sZt=function(t){return!j.isValidElement(t)&&!hc(t)&&typeof t!="boolean"?t.className:""};function Vse(s){"@babel/helpers - typeof";return Vse=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},Vse(s)}var w4n=["offset"];function j4n(s){return C4n(s)||S4n(s)||k4n(s)||N4n()}function N4n(){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 k4n(s,t){if(s){if(typeof s=="string")return CKe(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 CKe(s,t)}}function S4n(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function C4n(s){if(Array.isArray(s))return CKe(s)}function CKe(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 E4n(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 oNt(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 n0(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=y<=0?S:!S;var A=Yf(d,u,v,w),E=Yf(d,u,v,w+(S?1:-1)*359),I="M".concat(A.x,",").concat(A.y,` A`).concat(v,",").concat(v,",0,1,").concat(S?0:1,`, `).concat(E.x,",").concat(E.y),P=Gc(t.id)?WB("recharts-radial-line-"):t.id;return Kt.createElement("text",Hse({},r,{dominantBaseline:"central",className:sd("recharts-radial-bar-label",o)}),Kt.createElement("defs",null,Kt.createElement("path",{id:P,d:I})),Kt.createElement("textPath",{xlinkHref:"#".concat(P)},n))},D4n=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 v=(c+d)/2,y=Yf(l,o,v,m),b=y.x,w=y.y;return{x:b,y:w,textAnchor:"middle",verticalAnchor:"middle"}},F4n=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,v=x*a,y=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 n0(n0({},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 n0(n0({},S),r?{height:Math.max(r.y+r.height-(c+u),0),width:d}:{})}if(i==="left"){var A={x:o-v,y:c+u/2,textAnchor:y,verticalAnchor:"middle"};return n0(n0({},A),r?{width:Math.max(A.x-r.x,0),height:u}:{})}if(i==="right"){var E={x:o+d+v,y:c+u/2,textAnchor:b,verticalAnchor:"middle"};return n0(n0({},E),r?{width:Math.max(r.x+r.width-E.x,0),height:u}:{})}var I=r?{width:d,height:u}:{};return i==="insideLeft"?n0({x:o+v,y:c+u/2,textAnchor:b,verticalAnchor:"middle"},I):i==="insideRight"?n0({x:o+d-v,y:c+u/2,textAnchor:y,verticalAnchor:"middle"},I):i==="insideTop"?n0({x:o+d/2,y:c+m,textAnchor:"middle",verticalAnchor:g},I):i==="insideBottom"?n0({x:o+d/2,y:c+u-m,textAnchor:"middle",verticalAnchor:f},I):i==="insideTopLeft"?n0({x:o+v,y:c+m,textAnchor:b,verticalAnchor:g},I):i==="insideTopRight"?n0({x:o+d-v,y:c+m,textAnchor:y,verticalAnchor:g},I):i==="insideBottomLeft"?n0({x:o+v,y:c+u-m,textAnchor:b,verticalAnchor:f},I):i==="insideBottomRight"?n0({x:o+d-v,y:c+u-m,textAnchor:y,verticalAnchor:f},I):bK(i)&&(xi(i.x)||h8(i.x))&&(xi(i.y)||h8(i.y))?n0({x:o+y_(i.x,d),y:c+y_(i.y,u),textAnchor:"end",verticalAnchor:"end"},I):n0({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},I)},O4n=function(t){return"cx"in t&&xi(t.cx)};function gv(s){var t=s.offset,n=t===void 0?5:t,r=A4n(s,w4n),a=n0({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||Gc(o)&&Gc(c)&&!j.isValidElement(d)&&!hc(d))return null;if(j.isValidElement(d))return j.cloneElement(d,a);var f;if(hc(d)){if(f=j.createElement(d,a),j.isValidElement(f))return f}else f=I4n(a);var g=O4n(i),x=ll(a,!0);if(g&&(l==="insideStart"||l==="insideEnd"||l==="end"))return R4n(a,f,x);var v=g?D4n(a):F4n(a);return Kt.createElement(eB,Hse({className:sd("recharts-label",h)},x,v,{breakAll:m}),f)}gv.displayName="Label";var nZt=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,v=t.height,y=t.clockWise,b=t.labelViewBox;if(b)return b;if(xi(x)&&xi(v)){if(xi(h)&&xi(m))return{x:h,y:m,width:x,height:v};if(xi(f)&&xi(g))return{x:f,y:g,width:x,height:v}}return xi(h)&&xi(m)?{x:h,y:m,width:0,height:0}:xi(n)&&xi(r)?{cx:n,cy:r,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:u||c||o||0,clockWise:y}:t.viewBox?t.viewBox:{}},z4n=function(t,n){return t?t===!0?Kt.createElement(gv,{key:"label-implicit",viewBox:n}):N0(t)?Kt.createElement(gv,{key:"label-implicit",viewBox:n,value:t}):j.isValidElement(t)?t.type===gv?j.cloneElement(t,{key:"label-implicit",viewBox:n}):Kt.createElement(gv,{key:"label-implicit",content:t,viewBox:n}):hc(t)?Kt.createElement(gv,{key:"label-implicit",content:t,viewBox:n}):bK(t)?Kt.createElement(gv,Hse({viewBox:n},t,{key:"label-implicit"})):null:null},B4n=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=nZt(t),l=x2(a,gv).map(function(c,d){return j.cloneElement(c,{viewBox:n||i,key:"label-".concat(d)})});if(!r)return l;var o=z4n(t.label,n||i);return[o].concat(j4n(l))};gv.parseViewBox=nZt;gv.renderCallByParent=B4n;function $4n(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var U4n=$4n;const q4n=ru(U4n);function Gse(s){"@babel/helpers - typeof";return Gse=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},Gse(s)}var V4n=["valueAccessor"],H4n=["data","dataKey","clockWise","id","textBreakAll"];function G4n(s){return Z4n(s)||Y4n(s)||K4n(s)||W4n()}function W4n(){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 K4n(s,t){if(s){if(typeof s=="string")return AKe(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 AKe(s,t)}}function Y4n(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Z4n(s){if(Array.isArray(s))return AKe(s)}function AKe(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 e3n(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 t3n=function(t){return Array.isArray(t.value)?q4n(t.value):t.value};function z4(s){var t=s.valueAccessor,n=t===void 0?t3n:t,r=dNt(s,V4n),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=dNt(r,H4n);return!a||!a.length?null:Kt.createElement(ku,{className:"recharts-label-list"},a.map(function(u,h){var m=Gc(i)?n(u,h):ny(u&&u.payload,i),f=Gc(o)?{}:{id:"".concat(o,"-").concat(h)};return Kt.createElement(gv,vMe({},ll(u,!0),d,f,{parentViewBox:u.parentViewBox,value:m,textBreakAll:c,viewBox:gv.parseViewBox(Gc(l)?u:cNt(cNt({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}z4.displayName="LabelList";function s3n(s,t){return s?s===!0?Kt.createElement(z4,{key:"labelList-implicit",data:t}):Kt.isValidElement(s)||hc(s)?Kt.createElement(z4,{key:"labelList-implicit",data:t,content:s}):bK(s)?Kt.createElement(z4,vMe({data:t},s,{key:"labelList-implicit"})):null:null}function n3n(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=x2(r,z4).map(function(l,o){return j.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=s3n(s.label,t);return[i].concat(G4n(a))}z4.renderCallByParent=n3n;function Wse(s){"@babel/helpers - typeof";return Wse=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},Wse(s)}function EKe(){return EKe=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},l3n=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=x_(u-d),m=Hde({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),f=m.circleTangency,g=m.lineTangency,x=m.theta,v=Hde({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),y=v.circleTangency,b=v.lineTangency,w=v.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 `):rZt({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:d,endAngle:u});var A="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(y.x,",").concat(y.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(b.x,",").concat(b.y,` `);if(a>0){var E=Hde({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=Hde({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(A,"L").concat(n,",").concat(r,"Z");A+="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 A+="L".concat(n,",").concat(r,"Z");return A},c3n={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},aZt=function(t){var n=hNt(hNt({},c3n),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?v=l3n({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(x,g/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):v=rZt({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),Kt.createElement("path",EKe({},ll(n,!0),{className:f,d:v,role:"img"}))};function Kse(s){"@babel/helpers - typeof";return Kse=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},Kse(s)}function TKe(){return TKe=Object.assign?Object.assign.bind():function(s){for(var t=1;tw3n.call(s,t));function XB(s,t){return s===t||!s&&!t&&s!==s&&t!==t}const k3n="__v",S3n="__o",C3n="_owner",A3n=typeof Float16Array<"u",{getOwnPropertyDescriptor:xNt,keys:yNt}=Object;function E3n(s,t){return s.byteLength===t.byteLength&&bMe(new Uint8Array(s),new Uint8Array(t))}function T3n(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 M3n(s,t){return s.byteLength===t.byteLength&&bMe(new Uint8Array(s.buffer,s.byteOffset,s.byteLength),new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function P3n(s,t){return XB(s.getTime(),t.getTime())}function vNt(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 I3n(s,t){return s===t}function bNt(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 L3n=XB;function _Nt(s,t,n){const r=yNt(s);let a=r.length;if(yNt(t).length!==a)return!1;for(;a-- >0;)if(!cZt(s,t,n,r[a]))return!1;return!0}function I$(s,t,n){const r=gNt(s);let a=r.length;if(gNt(t).length!==a)return!1;let i,l,o;for(;a-- >0;)if(i=r[a],!cZt(s,t,n,i)||(l=xNt(s,i),o=xNt(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function R3n(s,t){return XB(s.valueOf(),t.valueOf())}function D3n(s,t){return s.source===t.source&&s.flags===t.flags}function wNt(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 bMe(s,t){let n=s.length;if(t.length!==n||s.byteOffset!==t.byteOffset)return!1;if(s instanceof Float64Array||s instanceof Float32Array||A3n&&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 F3n(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&&O3n(s.searchParams,t.searchParams)}function O3n(s,t){const n=s.toString(),r=t.toString();return n===r||jNt(n)===jNt(r)}function jNt(s){return s.split("&").sort().join("&")}function cZt(s,t,n,r){return(r===C3n||r===S3n||r===k3n)&&(s.$$typeof||t.$$typeof)?!0:N3n(t,r)&&n.equals(s[r],t[r],r,r,s,t,n)}const z3n="[object ArrayBuffer]",B3n="[object Arguments]",$3n="[object Boolean]",U3n="[object DataView]",q3n="[object Date]",V3n="[object Error]",H3n="[object Map]",G3n="[object Number]",W3n="[object Object]",K3n="[object RegExp]",Y3n="[object Set]",Z3n="[object String]",X3n={"[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},Q3n="[object URL]",J3n=Object.prototype.toString;function eAn({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(v,y,b){if(v===y)return!0;if(v==null||y==null)return!1;const w=typeof v;if(w!==typeof y)return!1;if(w!=="object")return w==="number"?o(v,y,b):w==="function"?i(v,y,b):!1;const S=v.constructor;if(S!==y.constructor)return!1;if(S===Object)return c(v,y,b);if(Array.isArray(v))return t(v,y,b);if(S===Date)return r(v,y,b);if(S===RegExp)return u(v,y,b);if(S===Map)return l(v,y,b);if(S===Set)return h(v,y,b);if(S==null)return c(v,y,b);const A=J3n.call(v);if(A===q3n)return r(v,y,b);if(A===K3n)return u(v,y,b);if(A===H3n)return l(v,y,b);if(A===Y3n)return h(v,y,b);if(A===W3n)return typeof v.then!="function"&&typeof y.then!="function"&&c(v,y,b);if(A===Q3n)return f(v,y,b);if(A===V3n)return a(v,y,b);if(A===B3n)return c(v,y,b);if(X3n[A])return m(v,y,b);if(A===z3n)return s(v,y,b);if(A===U3n)return n(v,y,b);if(A===$3n||A===G3n||A===Z3n)return d(v,y,b);if(g){let E=g[A];if(!E){const I=j3n(v);I&&(E=g[I])}if(E)return E(v,y,b)}return!1}}function tAn({circular:s,createCustomConfig:t,strict:n}){let r={areArrayBuffersEqual:E3n,areArraysEqual:n?I$:T3n,areDataViewsEqual:M3n,areDatesEqual:P3n,areErrorsEqual:n?YZ(vNt,I$):YZ(vNt,_Nt),areFunctionsEqual:I3n,areMapsEqual:n?YZ(bNt,I$):bNt,areNumbersEqual:L3n,areObjectsEqual:n?I$:_Nt,arePrimitiveWrappersEqual:R3n,areRegExpsEqual:D3n,areSetsEqual:n?YZ(wNt,I$):wNt,areTypedArraysEqual:n?YZ(bMe,I$):bMe,areUrlsEqual:F3n,unknownTagComparators:void 0};if(t&&(r=Object.assign({},r,t(r))),s){const a=ZZ(r.areArraysEqual),i=ZZ(r.areErrorsEqual),l=ZZ(r.areMapsEqual),o=ZZ(r.areObjectsEqual),c=ZZ(r.areSetsEqual);r=Object.assign({},r,{areArraysEqual:a,areErrorsEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return r}function sAn(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function nAn({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 rAn=j6();j6({strict:!0});j6({circular:!0});j6({circular:!0,strict:!0});j6({createInternalComparator:()=>XB});j6({strict:!0,createInternalComparator:()=>XB});j6({circular:!0,createInternalComparator:()=>XB});j6({circular:!0,createInternalComparator:()=>XB,strict:!0});function j6(s={}){const{circular:t=!1,createInternalComparator:n,createState:r,strict:a=!1}=s,i=tAn(s),l=eAn(i),o=n?n(l):sAn(l);return nAn({circular:t,comparator:l,createState:r,equals:o,strict:a})}function aAn(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function NNt(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):aAn(a)};requestAnimationFrame(r)}function MKe(s){"@babel/helpers - typeof";return MKe=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},MKe(s)}function iAn(s){return dAn(s)||cAn(s)||lAn(s)||oAn()}function oAn(){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 lAn(s,t){if(s){if(typeof s=="string")return kNt(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 kNt(s,t)}}function kNt(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:y<0?0:y},x=function(y){for(var b=y>1?1:y,w=b,S=0;S<8;++S){var A=h(w)-b,E=f(w);if(Math.abs(A-b)<_Me||E<_Me)return m(w);w=g(w-A/E)}return m(w)};return x.isStepper=!1,x},SAn=function(){var t=arguments.length>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,v=m*o/1e3+u;return Math.abs(v-h)<_Me&&Math.abs(x)<_Me?[h,0]:[v,x]};return c.isStepper=!0,c.dt=o,c},CAn=function(){for(var t=arguments.length,n=new Array(t),r=0;rs.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 $An(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 v9e(s){return HAn(s)||VAn(s)||qAn(s)||UAn()}function UAn(){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 qAn(s,t){if(s){if(typeof s=="string")return DKe(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 DKe(s,t)}}function VAn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function HAn(s){if(Array.isArray(s))return DKe(s)}function DKe(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 jMe(s){return jMe=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},jMe(s)}var gC=function(s){ZAn(n,s);var t=XAn(n);function n(r,a){var i;GAn(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(zKe(i)),i.changeStyle=i.changeStyle.bind(zKe(i)),!o||f<=0)return i.state={style:{}},typeof m=="function"&&(i.state={style:u}),OKe(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof m=="function")return i.state={style:d},OKe(i);i.state={style:c?yQ({},c,d):d}}else i.state={style:{}};return i}return KAn(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?yQ({},c,u):u};this.state&&m&&(c&&m[c]!==u||!c&&m!==u)&&this.setState(f);return}if(!(rAn(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 v={style:c?yQ({},c,x):x};(c&&m[c]!==x||!c&&m!==x)&&this.setState(v)}this.runAnimation(Jk(Jk({},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=OAn(l,o,CAn(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,v,y){if(y===0)return x;var b=v.duration,w=v.easing,S=w===void 0?"ease":w,A=v.style,E=v.properties,I=v.onAnimationEnd,P=y>0?l[y-1]:v,R=E||Object.keys(A);if(typeof S=="function"||S==="spring")return[].concat(v9e(x),[i.runJSAnimation.bind(i,{from:P.style,to:A,duration:b,easing:S}),b]);var D=ANt(R,b,S),O=Jk(Jk(Jk({},P.style),A),{},{transition:D});return[].concat(v9e(x),[O,b,I]).filter(pAn)};return this.manager.start([c].concat(v9e(l.reduce(f,[u,Math.max(m,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=uAn());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?yQ({},o,c):c,v=ANt(Object.keys(x),l,d);g.start([u,i,Jk(Jk({},x),{},{transition:v}),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=BAn(a,zAn),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,v=x===void 0?{}:x,y=g.className,b=j.cloneElement(f,Jk(Jk({},c),{},{style:Jk(Jk({},v),u),className:y}));return b};return d===1?h(j.Children.only(i)):Kt.createElement("div",null,j.Children.map(i,function(m){return h(m)}))}}]),n}(j.PureComponent);gC.displayName="Animate";gC.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};gC.propTypes={from:fm.oneOfType([fm.object,fm.string]),to:fm.oneOfType([fm.object,fm.string]),attributeName:fm.string,duration:fm.number,begin:fm.number,easing:fm.oneOfType([fm.string,fm.func]),steps:fm.arrayOf(fm.shape({duration:fm.number.isRequired,style:fm.object.isRequired,easing:fm.oneOfType([fm.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),fm.func]),properties:fm.arrayOf("string"),onAnimationEnd:fm.func})),children:fm.oneOfType([fm.node,fm.func]),isActive:fm.bool,canBegin:fm.bool,onAnimationEnd:fm.func,shouldReAnimate:fm.bool,onAnimationStart:fm.func,onAnimationReStart:fm.func};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)}function NMe(){return NMe=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},oEn=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},lEn={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Eat=function(t){var n=DNt(DNt({},lEn),t),r=j.useRef(),a=j.useState(-1),i=JAn(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,v=n.animationBegin,y=n.isAnimationActive,b=n.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||h!==+h||u===0||h===0)return null;var w=sd("recharts-rectangle",f);return b?Kt.createElement(gC,{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 A=S.width,E=S.height,I=S.x,P=S.y;return Kt.createElement(gC,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:x,isActive:y,easing:g},Kt.createElement("path",NMe({},ll(n,!0),{className:w,d:FNt(I,P,A,E,m),ref:r})))}):Kt.createElement("path",NMe({},ll(n,!0),{className:w,d:FNt(c,d,u,h,m)}))},cEn=["points","className","baseLinePoints","connectNulls"];function sq(){return sq=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 uEn(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 ONt(s){return pEn(s)||fEn(s)||mEn(s)||hEn()}function hEn(){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 mEn(s,t){if(s){if(typeof s=="string")return BKe(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 BKe(s,t)}}function fEn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function pEn(s){if(Array.isArray(s))return BKe(s)}function BKe(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){zNt(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),zNt(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},Uee=function(t,n){var r=gEn(t);n&&(r=[r.reduce(function(i,l){return[].concat(ONt(i),ONt(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},xEn=function(t,n,r){var a=Uee(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(Uee(n.reverse(),r).slice(1))},yEn=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=dEn(t,cEn);if(!n||!n.length)return null;var o=sd("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=xEn(n,a,i);return Kt.createElement("g",{className:o},Kt.createElement("path",sq({},ll(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?Kt.createElement("path",sq({},ll(l,!0),{fill:"none",d:Uee(n,i)})):null,c?Kt.createElement("path",sq({},ll(l,!0),{fill:"none",d:Uee(a,i)})):null)}var u=Uee(n,i);return Kt.createElement("path",sq({},ll(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function $Ke(){return $Ke=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 kEn(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 SEn=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},CEn=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=NEn(t,vEn),v=bEn({x:r,y:i,top:o,left:d,width:h,height:f},x);return!xi(r)||!xi(i)||!xi(h)||!xi(f)||!xi(o)||!xi(d)?null:Kt.createElement("path",UKe({},ll(v,!0),{className:sd("recharts-cross",g),d:SEn(r,i,h,f,o,d)}))},AEn=IRe,EEn=CYt,TEn=h3;function MEn(s,t){return s&&s.length?AEn(s,TEn(t),EEn):void 0}var PEn=MEn;const IEn=ru(PEn);var LEn=IRe,REn=h3,DEn=AYt;function FEn(s,t){return s&&s.length?LEn(s,REn(t),DEn):void 0}var OEn=FEn;const zEn=ru(OEn);var BEn=["cx","cy","angle","ticks","axisLine"],$En=["ticks","tick","angle","tickFormatter","stroke"];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 qee(){return qee=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 UEn(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 qEn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function qNt(s,t){for(var n=0;nGNt?l=a==="outer"?"start":"end":i<-GNt?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=gR(gR({},ll(this.props,!1)),{},{fill:"none"},ll(o,!1));if(c==="circle")return Kt.createElement(Cie,GO({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 Kt.createElement(yEn,GO({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=ll(this.props,!1),h=ll(l,!1),m=gR(gR({},u),{},{fill:"none"},ll(o,!1)),f=i.map(function(g,x){var v=r.getTickLineCoord(g),y=r.getTickTextAnchor(g),b=gR(gR(gR({textAnchor:y},u),{},{stroke:"none",fill:d},h),{},{index:x,payload:g,x:v.x2,y:v.y2});return Kt.createElement(ku,GO({className:sd("recharts-polar-angle-axis-tick",sZt(l)),key:"tick-".concat(g.coordinate)},J7(r.props,g,x)),o&&Kt.createElement("line",GO({className:"recharts-polar-angle-axis-tick-line"},m,v)),l&&t.renderTickItem(l,b,c?c(g.value,x):g.value))});return Kt.createElement(ku,{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:Kt.createElement(ku,{className:sd("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return Kt.isValidElement(r)?l=Kt.cloneElement(r,a):hc(r)?l=r(a):l=Kt.createElement(eB,GO({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(j.PureComponent);zRe(BRe,"displayName","PolarAngleAxis");zRe(BRe,"axisType","angleAxis");zRe(BRe,"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 rTn=NKt,aTn=rTn(Object.getPrototypeOf,Object),iTn=aTn,oTn=IT,lTn=iTn,cTn=LT,dTn="[object Object]",uTn=Function.prototype,hTn=Object.prototype,bZt=uTn.toString,mTn=hTn.hasOwnProperty,fTn=bZt.call(Object);function pTn(s){if(!cTn(s)||oTn(s)!=dTn)return!1;var t=lTn(s);if(t===null)return!0;var n=mTn.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&bZt.call(n)==fTn}var gTn=pTn;const xTn=ru(gTn);var yTn=IT,vTn=LT,bTn="[object Boolean]";function _Tn(s){return s===!0||s===!1||vTn(s)&&yTn(s)==bTn}var wTn=_Tn;const jTn=ru(wTn);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)}function CMe(){return CMe=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:y},function(w){var S=w.upperWidth,A=w.lowerWidth,E=w.height,I=w.x,P=w.y;return Kt.createElement(gC,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:x,easing:g},Kt.createElement("path",CMe({},ll(n,!0),{className:b,d:ZNt(I,P,S,A,E),ref:r})))}):Kt.createElement("g",null,Kt.createElement("path",CMe({},ll(n,!0),{className:b,d:ZNt(c,d,u,h,m)})))},LTn=["option","shapeType","propTransformer","activeClassName","isActive"];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 RTn(s,t){if(s==null)return{};var n=DTn(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 DTn(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 XNt(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 AMe(s){for(var t=1;t0?g2(w,"paddingAngle",0):0;if(A){var I=b0(A.endAngle-A.startAngle,w.endAngle-w.startAngle),P=qf(qf({},w),{},{startAngle:b+E,endAngle:b+I(x)+E});v.push(P),b=P.endAngle}else{var R=w.endAngle,D=w.startAngle,O=b0(0,R-D),U=O(x),W=qf(qf({},w),{},{startAngle:b+E,endAngle:b+U+E});v.push(W),b=W.endAngle}}),Kt.createElement(ku,null,r.renderSectorsStatically(v))})}},{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||!tB(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||!xi(d)||!xi(u)||!xi(h)||!xi(m))return null;var x=sd("recharts-pie",o);return Kt.createElement(ku,{tabIndex:this.props.rootTabIndex,className:x,ref:function(y){r.pieRef=y}},this.renderSectors(),c&&this.renderLabels(l),gv.renderCallByParent(this.props,null,!1),(!f||g)&&z4.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=v-b*f-w,A=a.reduce(function(P,R){var D=ny(R,y,0);return P+(xi(D)?D:0)},0),E;if(A>0){var I;E=a.map(function(P,R){var D=ny(P,y,0),O=ny(P,u,R),U=(xi(D)?D:0)/A,W;R?W=I.endAngle+x_(x)*c*(D!==0?1:0):W=l;var V=W+x_(x)*((D!==0?f:0)+U*S),G=(W+V)/2,Z=(g.innerRadius+g.outerRadius)/2,X=[{name:O,value:D,payload:P,dataKey:y,type:m}],ae=Yf(g.cx,g.cy,Z,G);return I=qf(qf(qf({percent:U,cornerRadius:i,name:O,tooltipPayload:X,midAngle:G,middleRadius:Z,tooltipPosition:ae},P),g),{},{value:ny(P,y),startAngle:W,endAngle:V,payload:P,paddingAngle:x_(x)*c}),I})}return qf(qf({},g),{},{sectors:E,data:a})});var nMn=Math.ceil,rMn=Math.max;function aMn(s,t,n,r){for(var a=-1,i=rMn(nMn((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var iMn=aMn,oMn=qKt,tkt=1/0,lMn=17976931348623157e292;function cMn(s){if(!s)return s===0?s:0;if(s=oMn(s),s===tkt||s===-tkt){var t=s<0?-1:1;return t*lMn}return s===s?s:0}var NZt=cMn,dMn=iMn,uMn=SRe,b9e=NZt;function hMn(s){return function(t,n,r){return r&&typeof r!="number"&&uMn(t,n,r)&&(n=r=void 0),t=b9e(t),n===void 0?(n=t,t=0):n=b9e(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),Cj(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()}),Cj(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),Cj(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),Cj(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),Cj(r,"handleSlideDragStart",function(a){var i=ikt(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 SMn(t,s),wMn(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=ny(i[r],o,r);return hc(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 v=this.getIndex({startX:l+x,endX:o+x});(v.startIndex!==m||v.endIndex!==f)&&g&&g(v),this.setState({startX:l+x,endX:o+x,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=ikt(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,v=u.data,y={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)),y[l]=d+b;var w=this.getIndex(y),S=w.startIndex,A=w.endIndex,E=function(){var P=v.length-1;return l==="startX"&&(o>c?S%x===0:A%x===0)||oc?A%x===0:S%x===0)||o>c&&A===P};this.setState(Cj(Cj({},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(Cj({},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 Kt.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?Kt.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,v=c.endIndex,y=Math.max(r,this.props.x),b=_9e(_9e({},ll(this.props,!1)),{},{x:y,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[v])===null||l===void 0?void 0:l.name);return Kt.createElement(ku,{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(A){["ArrowLeft","ArrowRight"].includes(A.key)&&(A.preventDefault(),A.stopPropagation(),o.handleTravellerMoveKeyboard(A.key==="ArrowRight"?1:-1,a))},onFocus:function(){o.setState({isTravellerFocused:!0})},onBlur:function(){o.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(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 Kt.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 Kt.createElement(ku,{className:"recharts-brush-texts"},Kt.createElement(eB,MMe({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,m)-f,y:l+o/2},g),this.getTextOfTick(a)),Kt.createElement(eB,MMe({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,v=m.isSlideMoving,y=m.isTravellerMoving,b=m.isTravellerFocused;if(!a||!a.length||!xi(o)||!xi(c)||!xi(d)||!xi(u)||d<=0||u<=0)return null;var w=sd("recharts-brush",i),S=Kt.Children.count(l)===1,A=bMn("userSelect","none");return Kt.createElement(ku,{className:w,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:A},this.renderBackground(),S&&this.renderPanorama(),this.renderSlide(f,g),this.renderTravellerLayer(f,"startX"),this.renderTravellerLayer(g,"endX"),(x||v||y||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 Kt.createElement(Kt.Fragment,null,Kt.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),Kt.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),Kt.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 Kt.isValidElement(r)?i=Kt.cloneElement(r,a):hc(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 _9e({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?AMn({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);Cj(XG,"displayName","Brush");Cj(XG,"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 EMn=tat;function TMn(s,t){var n;return EMn(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var MMn=TMn,PMn=gKt,IMn=h3,LMn=MMn,RMn=qw,DMn=SRe;function FMn(s,t,n){var r=RMn(s)?PMn:LMn;return n&&DMn(s,t,n)&&(t=void 0),r(s,IMn(t))}var OMn=FMn;const zMn=ru(OMn);var B4=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},okt=OKt;function BMn(s,t,n){t=="__proto__"&&okt?okt(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var $Mn=BMn,UMn=$Mn,qMn=DKt,VMn=h3;function HMn(s,t){var n={};return t=VMn(t),qMn(s,function(r,a,i){UMn(n,a,t(r,a,i))}),n}var GMn=HMn;const WMn=ru(GMn);function KMn(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 uPn(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 hPn(s,t){var n=s.x,r=s.y,a=dPn(s,iPn),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 XZ(XZ(XZ(XZ(XZ({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:m,name:t.name,radius:t.radius})}function ckt(s){return Kt.createElement(_Zt,WKe({shapeType:"rectangle",propTransformer:hPn,activeClassName:"recharts-active-bar"},s))}var mPn=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=xi(r)||Rgn(r);return i?t(r,a):(i||nB(),n)}},fPn=["value","background"],EZt;function QG(s){"@babel/helpers - typeof";return QG=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},QG(s)}function pPn(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 IMe(){return IMe=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(G)0&&Math.abs(V)0&&(W=Math.min((ve||0)-(V[fe-1]||0),W))}),Number.isFinite(W)){var G=W/U,Z=x.layout==="vertical"?r.height:r.width;if(x.padding==="gap"&&(I=G*Z/2),x.padding==="no-gap"){var X=y_(t.barCategoryGap,G*Z),ae=G*Z/2;I=ae-X-(ae-X)/Z*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,A&&(P=[P[1],P[0]]);var le=YYt(x,i,m),re=le.scale,te=le.realScaleType;re.domain(y).range(P),ZYt(re);var J=XYt(re,IS(IS({},x),{},{realScaleType:te}));a==="xAxis"?(O=v==="top"&&!S||v==="bottom"&&S,R=r.left,D=h[E]-O*x.height):a==="yAxis"&&(O=v==="left"&&!S||v==="right"&&S,R=h[E]-O*x.width,D=r.top);var ce=IS(IS(IS({},x),J),{},{realScaleType:te,x:R,y:D,scale:re,width:a==="xAxis"?r.width:x.width,height:a==="yAxis"?r.height:x.height});return ce.bandSize=xMe(ce,J),!x.hide&&a==="xAxis"?h[E]+=(O?-1:1)*ce.height:x.hide||(h[E]+=(O?-1:1)*ce.width),IS(IS({},f),{},qRe({},g,ce))},{})},IZt=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)}},CPn=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return IZt({x:n,y:r},{x:a,y:i})},LZt=function(){function s(t){NPn(this,s),this.scale=t}return kPn(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)}}])}();qRe(LZt,"EPS",1e-4);var Mat=function(t){var n=Object.keys(t).reduce(function(r,a){return IS(IS({},r),{},qRe({},a,LZt.create(t[a])))},{});return IS(IS({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return WMn(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return AZt(a,function(i,l){return n[l].isInRange(i)})}})};function APn(s){return(s%180+180)%180}var EPn=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=APn(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var LPn=IPn,RPn=NZt;function DPn(s){var t=RPn(s),n=t%1;return t===t?n?t-n:t:0}var FPn=DPn,OPn=TKt,zPn=h3,BPn=FPn,$Pn=Math.max;function UPn(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:BPn(n);return a<0&&(a=$Pn(r+a,0)),OPn(s,zPn(t),a)}var qPn=UPn,VPn=LPn,HPn=qPn,GPn=VPn(HPn),WPn=GPn;const KPn=ru(WPn);var YPn=$pn(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("")}),Pat=j.createContext(void 0),Iat=j.createContext(void 0),RZt=j.createContext(void 0),DZt=j.createContext({}),FZt=j.createContext(void 0),OZt=j.createContext(0),zZt=j.createContext(0),fkt=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=YPn(i);return Kt.createElement(Pat.Provider,{value:r},Kt.createElement(Iat.Provider,{value:a},Kt.createElement(DZt.Provider,{value:i},Kt.createElement(RZt.Provider,{value:u},Kt.createElement(FZt.Provider,{value:l},Kt.createElement(OZt.Provider,{value:d},Kt.createElement(zZt.Provider,{value:c},o)))))))},ZPn=function(){return j.useContext(FZt)},BZt=function(t){var n=j.useContext(Pat);n==null&&nB();var r=n[t];return r==null&&nB(),r},XPn=function(){var t=j.useContext(Pat);return kP(t)},QPn=function(){var t=j.useContext(Iat),n=KPn(t,function(r){return AZt(r.domain,Number.isFinite)});return n||kP(t)},$Zt=function(t){var n=j.useContext(Iat);n==null&&nB();var r=n[t];return r==null&&nB(),r},JPn=function(){var t=j.useContext(RZt);return t},eIn=function(){return j.useContext(DZt)},Lat=function(){return j.useContext(zZt)},Rat=function(){return j.useContext(OZt)};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 tIn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function sIn(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 FIn(s,t){return KZt(s,t+1)}function OIn(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:KZt(r,d)};var x=c,v,y=function(){return v===void 0&&(v=n(g,x)),v},b=g.coordinate,w=c===0||OMe(s,b,y,u,o);w||(c=0,u=l,d+=1),w&&(u=b+s*(y()/2+a),c+=d)},m;d<=i.length;)if(m=h(),m)return m.v;return[]}function ane(s){"@babel/helpers - typeof";return ane=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},ane(s)}function wkt(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 o1(s){for(var t=1;t0?f.coordinate-v*s:f.coordinate})}else i[m]=f=o1(o1({},f),{},{tickCoord:f.coordinate});var y=OMe(s,f.tickCoord,x,o,c);y&&(c=f.tickCoord-s*(x()/2+a),i[m]=o1(o1({},f),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function qIn(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=o1(o1({},u),{},{tickCoord:m>0?u.coordinate-m*s:u.coordinate});var f=OMe(s,u.tickCoord,function(){return h},c,d);f&&(d=u.tickCoord-s*(h/2+a),l[o-1]=o1(o1({},u),{},{isShow:!0}))}for(var g=i?o-1:o,x=function(b){var w=l[b],S,A=function(){return S===void 0&&(S=n(w,b)),S};if(b===0){var E=s*(w.coordinate-s*A()/2-c);l[b]=w=o1(o1({},w),{},{tickCoord:E<0?w.coordinate-E*s:w.coordinate})}else l[b]=w=o1(o1({},w),{},{tickCoord:w.coordinate});var I=OMe(s,w.tickCoord,A,c,d);I&&(c=w.tickCoord+s*(A()/2+a),l[b]=o1(o1({},w),{},{isShow:!0}))},v=0;v=2?x_(a[1].coordinate-a[0].coordinate):1,y=DIn(i,v,f);return c==="equidistantPreserveStart"?OIn(v,y,x,a,l):(c==="preserveStart"||c==="preserveStartEnd"?m=qIn(v,y,x,a,l,c==="preserveStartEnd"):m=UIn(v,y,x,a,l),m.filter(function(b){return b.isShow}))}var VIn=["viewBox"],HIn=["viewBox"],GIn=["ticks"];function sW(s){"@babel/helpers - typeof";return sW=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},sW(s)}function rq(){return rq=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 WIn(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 KIn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Nkt(s,t){for(var n=0;n0?c(this.props):c(f)),l<=0||o<=0||!g||!g.length?null:Kt.createElement(ku,{className:sd("recharts-cartesian-axis",d),ref:function(v){r.layerReference=v}},i&&this.renderAxisLine(),this.renderTicks(g,this.state.fontSize,this.state.letterSpacing),gv.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=sd(a.className,"recharts-cartesian-axis-tick-value");return Kt.isValidElement(r)?l=Kt.cloneElement(r,t0(t0({},a),{},{className:o})):hc(r)?l=r(t0(t0({},a),{},{className:o})):l=Kt.createElement(eB,rq({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(j.Component);zat(MK,"displayName","CartesianAxis");zat(MK,"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 tLn=["x1","y1","x2","y2","key"],sLn=["offset"];function rB(s){"@babel/helpers - typeof";return rB=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},rB(s)}function kkt(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;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function iLn(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 oLn=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 Kt.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function XZt(s,t){var n;if(Kt.isValidElement(s))n=Kt.cloneElement(s,t);else if(hc(s))n=s(t);else{var r=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=Skt(t,tLn),d=ll(c,!1);d.offset;var u=Skt(d,sLn);n=Kt.createElement("line",p8({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function lLn(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=u1(u1({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return XZt(a,d)});return Kt.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function cLn(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=u1(u1({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return XZt(a,d)});return Kt.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function dLn(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 v=f%t.length;return Kt.createElement("rect",{key:"react-".concat(f),y:m,x:r,height:x,width:i,stroke:"none",fill:t[v],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return Kt.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function uLn(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 v=f%r.length;return Kt.createElement("rect",{key:"react-".concat(f),x:m,y:l,width:x,height:c,stroke:"none",fill:r[v],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return Kt.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var hLn=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return KYt(Oat(u1(u1(u1({},MK.defaultProps),r),{},{ticks:jE(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},mLn=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return KYt(Oat(u1(u1(u1({},MK.defaultProps),r),{},{ticks:jE(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},L$={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function pT(s){var t,n,r,a,i,l,o=Lat(),c=Rat(),d=eIn(),u=u1(u1({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:L$.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:L$.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:L$.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:L$.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:L$.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:L$.verticalFill,x:xi(s.x)?s.x:d.left,y:xi(s.y)?s.y:d.top,width:xi(s.width)?s.width:d.width,height:xi(s.height)?s.height:d.height}),h=u.x,m=u.y,f=u.width,g=u.height,x=u.syncWithTicks,v=u.horizontalValues,y=u.verticalValues,b=XPn(),w=QPn();if(!xi(f)||f<=0||!xi(g)||g<=0||!xi(h)||h!==+h||!xi(m)||m!==+m)return null;var S=u.verticalCoordinatesGenerator||hLn,A=u.horizontalCoordinatesGenerator||mLn,E=u.horizontalPoints,I=u.verticalPoints;if((!E||!E.length)&&hc(A)){var P=v&&v.length,R=A({yAxis:w?u1(u1({},w),{},{ticks:P?v:w.ticks}):void 0,width:o,height:c,offset:d},P?!0:x);iC(Array.isArray(R),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(rB(R),"]")),Array.isArray(R)&&(E=R)}if((!I||!I.length)&&hc(S)){var D=y&&y.length,O=S({xAxis:b?u1(u1({},b),{},{ticks:D?y:b.ticks}):void 0,width:o,height:c,offset:d},D?!0:x);iC(Array.isArray(O),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(rB(O),"]")),Array.isArray(O)&&(I=O)}return Kt.createElement("g",{className:"recharts-cartesian-grid"},Kt.createElement(oLn,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),Kt.createElement(lLn,p8({},u,{offset:d,horizontalPoints:E,xAxis:b,yAxis:w})),Kt.createElement(cLn,p8({},u,{offset:d,verticalPoints:I,xAxis:b,yAxis:w})),Kt.createElement(dLn,p8({},u,{horizontalPoints:E})),Kt.createElement(uLn,p8({},u,{verticalPoints:I})))}pT.displayName="CartesianGrid";var fLn=["type","layout","connectNulls","ref"],pLn=["key"];function nW(s){"@babel/helpers - typeof";return nW=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},nW(s)}function Ckt(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 Vee(){return Vee=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(R$(c.slice(0,g)),[h-x]);break}var v=f.length%2===0?[0,m]:[m];return[].concat(R$(t.repeat(c,u)),R$(f),v).map(function(y){return"".concat(y,"px")}).join(", ")}),LS(n,"id",WB("recharts-line-")),LS(n,"pathRef",function(l){n.mainCurve=l}),LS(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),LS(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return SLn(t,s),wLn(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=x2(u,Sie);if(!h)return null;var m=function(x,v){return{x:x.x,y:x.y,value:x.value,errorVal:ny(x.payload,v)}},f={clipPath:r?"url(#clipPath-".concat(a,")"):null};return Kt.createElement(ku,f,h.map(function(g){return Kt.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=ll(this.props,!1),m=ll(c,!0),f=d.map(function(x,v){var y=jj(jj(jj({key:"dot-".concat(v),r:3},h),m),{},{index:v,cx:x.x,cy:x.y,value:x.value,dataKey:u,payload:x.payload,points:d});return t.renderDotItem(c,y)}),g={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return Kt.createElement(ku,Vee({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=Ckt(o,fLn),m=jj(jj(jj({},ll(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 Kt.createElement(x7,Vee({},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,v=l.height,y=this.state,b=y.prevPoints,w=y.totalLength;return Kt.createElement(gC,{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 A=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],Z=b0(G.x,U.x),X=b0(G.y,U.y);return jj(jj({},U),{},{x:Z(A),y:X(A)})}if(g){var ae=b0(x*2,U.x),le=b0(v/2,U.y);return jj(jj({},U),{},{x:ae(A),y:le(A)})}return jj(jj({},U),{},{x:U.x,y:U.y})});return i.renderCurveStatically(I,r,a)}var P=b0(0,w),R=P(A),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||!tB(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,v=a.id;if(i||!o||!o.length)return null;var y=this.state.isAnimationFinished,b=o.length===1,w=sd("recharts-line",c),S=d&&d.allowDataOverflow,A=u&&u.allowDataOverflow,E=S||A,I=Gc(v)?this.id:v,P=(r=ll(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=$Wt(l)?l:{},V=W.clipDot,G=V===void 0?!0:V,Z=D*2+U;return Kt.createElement(ku,{className:w},S||A?Kt.createElement("defs",null,Kt.createElement("clipPath",{id:"clipPath-".concat(I)},Kt.createElement("rect",{x:S?m:m-f/2,y:A?h:h-g/2,width:S?f:f*2,height:A?g:g*2})),!G&&Kt.createElement("clipPath",{id:"clipPath-dots-".concat(I)},Kt.createElement("rect",{x:m-Z/2,y:h-Z/2,width:f+Z,height:g+Z}))):null,!b&&this.renderCurve(E,I),this.renderErrorBar(E,I),(b||l)&&this.renderDots(E,G,I),(!x||y)&&z4.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(R$(r),[0]):r,l=[],o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function TLn(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 g8(){return g8=Object.assign?Object.assign.bind():function(s){for(var t=1;t0||!tB(u,l)||!tB(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,v=a.id;if(i||!o||!o.length)return null;var y=this.state.isAnimationFinished,b=o.length===1,w=sd("recharts-area",c),S=h&&h.allowDataOverflow,A=m&&m.allowDataOverflow,E=S||A,I=Gc(v)?this.id:v,P=(r=ll(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=$Wt(l)?l:{},V=W.clipDot,G=V===void 0?!0:V,Z=D*2+U;return Kt.createElement(ku,{className:w},S||A?Kt.createElement("defs",null,Kt.createElement("clipPath",{id:"clipPath-".concat(I)},Kt.createElement("rect",{x:S?u:u-f/2,y:A?d:d-g/2,width:S?f:f*2,height:A?g:g*2})),!G&&Kt.createElement("clipPath",{id:"clipPath-dots-".concat(I)},Kt.createElement("rect",{x:u-Z/2,y:d-Z/2,width:f+Z,height:g+Z}))):null,b?null:this.renderArea(E,I),(l||b)&&this.renderDots(E,G,I),(!x||y)&&z4.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);eXt=Pw;x4(Pw,"displayName","Area");x4(Pw,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!b6.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});x4(Pw,"getBaseValue",function(s,t,n,r){var a=s.layout,i=s.baseValue,l=t.props.baseValue,o=l??i;if(xi(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]});x4(Pw,"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=eXt.getBaseValue(t,n,r,a),v=f==="horizontal",y=!1,b=h.map(function(S,A){var E;g?E=d[u+A]:(E=ny(S,c),Array.isArray(E)?y=!0:E=[x,E]);var I=E[1]==null||g&&ny(S,c)==null;return v?{x:gMe({axis:r,ticks:i,bandSize:o,entry:S,index:A}),y:I?null:a.scale(E[1]),value:E,payload:S}:{x:I?null:r.scale(E[1]),y:gMe({axis:a,ticks:l,bandSize:o,entry:S,index:A}),value:E,payload:S}}),w;return g||y?w=b.map(function(S){var A=Array.isArray(S.value)?S.value[0]:null;return v?{x:S.x,y:A!=null&&S.y!=null?a.scale(A):null}:{x:A!=null?r.scale(A):null,y:S.y}}):w=v?a.scale(x):r.scale(x),WM({points:b,baseLine:w,layout:f,isRange:y},m)});x4(Pw,"renderDotItem",function(s,t){var n;if(Kt.isValidElement(s))n=Kt.cloneElement(s,t);else if(hc(s))n=s(t);else{var r=sd("recharts-area-dot",typeof s!="boolean"?s.className:""),a=t.key,i=tXt(t,ELn);n=Kt.createElement(Cie,g8({},i,{key:a,className:r}))}return n});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 OLn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function zLn(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 k6n(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 S6n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function C6n(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n0?l:t&&t.length&&xi(a)&&xi(i)?t.slice(a,i+1):[]};function xXt(s){return s==="number"?[0,"auto"]:void 0}var mYe=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=KRe(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=$Te(f,l.dataKey,a)}else m=h&&h[r]||o[r];return m?[].concat(lW(c),[JYt(d,m)]):c},[])},Fkt=function(t,n,r,a){var i=a||{x:t.chartX,y:t.chartY},l=z6n(i,r),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=W5n(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,m=mYe(t,n,u,h),f=B6n(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:m,activeCoordinate:f}}return null},$6n=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=WYt(u,i);return r.reduce(function(g,x){var v,y=x.type.defaultProps!==void 0?ba(ba({},x.type.defaultProps),x.props):x.props,b=y.type,w=y.dataKey,S=y.allowDataOverflow,A=y.allowDuplicatedCategory,E=y.scale,I=y.ticks,P=y.includeHidden,R=y[l];if(g[R])return g;var D=KRe(t.data,{graphicalItems:a.filter(function(J){var ce,ve=l in J.props?J.props[l]:(ce=J.type.defaultProps)===null||ce===void 0?void 0:ce[l];return ve===R}),dataStartIndex:c,dataEndIndex:d}),O=D.length,U,W,V;m6n(y.domain,S,b)&&(U=SKe(y.domain,null,S),f&&(b==="number"||E!=="auto")&&(V=Bee(D,w,"category")));var G=xXt(b);if(!U||U.length===0){var Z,X=(Z=y.domain)!==null&&Z!==void 0?Z:G;if(w){if(U=Bee(D,w,b),b==="category"&&f){var ae=Fgn(U);A&&ae?(W=U,U=TMe(0,O)):A||(U=nNt(X,U,x).reduce(function(J,ce){return J.indexOf(ce)>=0?J:[].concat(lW(J),[ce])},[]))}else if(b==="category")A?U=U.filter(function(J){return J!==""&&!Gc(J)}):U=nNt(X,U,x).reduce(function(J,ce){return J.indexOf(ce)>=0||ce===""||Gc(ce)?J:[].concat(lW(J),[ce])},[]);else if(b==="number"){var le=Q5n(D,a.filter(function(J){var ce,ve,fe=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:(ve=J.type.defaultProps)===null||ve===void 0?void 0:ve.hide;return fe===R&&(P||!ue)}),w,i,u);le&&(U=le)}f&&(b==="number"||E!=="auto")&&(V=Bee(D,w,"category"))}else f?U=TMe(0,O):o&&o[R]&&o[R].hasStack&&b==="number"?U=m==="expand"?[0,1]:QYt(o[R].stackGroups,c,d):U=GYt(D,a.filter(function(J){var ce=l in J.props?J.props[l]:J.type.defaultProps[l],ve="hide"in J.props?J.props.hide:J.type.defaultProps.hide;return ce===R&&(P||!ve)}),b,u,!0);if(b==="number")U=dYe(h,U,R,i,I),X&&(U=SKe(X,U,S));else if(b==="category"&&X){var re=X,te=U.every(function(J){return re.indexOf(J)>=0});te&&(U=re)}}return ba(ba({},g),{},uc({},R,ba(ba({},y),{},{axisType:i,domain:U,categoricalDomain:V,duplicateDomain:W,originalDomain:(v=y.domain)!==null&&v!==void 0?v:G,isCategorical:f,layout:u})))},{})},U6n=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=KRe(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),f=m.length,g=WYt(u,i),x=-1;return r.reduce(function(v,y){var b=y.type.defaultProps!==void 0?ba(ba({},y.type.defaultProps),y.props):y.props,w=b[l],S=xXt("number");if(!v[w]){x++;var A;return g?A=TMe(0,f):o&&o[w]&&o[w].hasStack?(A=QYt(o[w].stackGroups,c,d),A=dYe(h,A,w,i)):(A=SKe(S,GYt(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),A=dYe(h,A,w,i)),ba(ba({},v),{},uc({},w,ba(ba({axisType:i},a.defaultProps),{},{hide:!0,orientation:g2(F6n,"".concat(i,".").concat(x%2),null),domain:A,originalDomain:S,isCategorical:g,layout:u})))}return v},{})},q6n=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=x2(u,i),f={};return m&&m.length?f=$6n(t,{axes:m,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(f=U6n(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),f},V6n=function(t){var n=kP(t),r=jE(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:sat(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:xMe(n,r)}},Okt=function(t){var n=t.children,r=t.defaultShowTooltip,a=Bj(n,XG),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}},H6n=function(t){return!t||!t.length?!1:t.some(function(n){var r=qE(n&&n.type);return r&&r.indexOf("Bar")>=0})},zkt=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"}},G6n=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=Bj(h,XG),g=Bj(h,kV),x=Object.keys(c).reduce(function(A,E){var I=c[E],P=I.orientation;return!I.mirror&&!I.hide?ba(ba({},A),{},uc({},P,A[P]+I.width)):A},{left:m.left||0,right:m.right||0}),v=Object.keys(l).reduce(function(A,E){var I=l[E],P=I.orientation;return!I.mirror&&!I.hide?ba(ba({},A),{},uc({},P,g2(A,"".concat(P))+I.height)):A},{top:m.top||0,bottom:m.bottom||0}),y=ba(ba({},v),x),b=y.bottom;f&&(y.bottom+=f.props.height||XG.defaultProps.height),g&&n&&(y=Z5n(y,a,r,n));var w=d-y.left-y.right,S=u-y.top-y.bottom;return ba(ba({brushBottom:b},y),{},{width:Math.max(w,0),height:Math.max(S,0)})},W6n=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},YRe=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(y,b){var w=b.graphicalItems,S=b.stackGroups,A=b.offset,E=b.updateId,I=b.dataStartIndex,P=b.dataEndIndex,R=y.barSize,D=y.layout,O=y.barGap,U=y.barCategoryGap,W=y.maxBarSize,V=zkt(D),G=V.numericAxisName,Z=V.cateAxisName,X=H6n(w),ae=[];return w.forEach(function(le,re){var te=KRe(y.data,{graphicalItems:[le],dataStartIndex:I,dataEndIndex:P}),J=le.type.defaultProps!==void 0?ba(ba({},le.type.defaultProps),le.props):le.props,ce=J.dataKey,ve=J.maxBarSize,fe=J["".concat(G,"Id")],ue=J["".concat(Z,"Id")],be={},Ee=c.reduce(function(Qe,at){var rt=b["".concat(at.axisType,"Map")],Ke=J["".concat(at.axisType,"Id")];rt&&rt[Ke]||at.axisType==="zAxis"||nB();var Je=rt[Ke];return ba(ba({},Qe),{},uc(uc({},at.axisType,Je),"".concat(at.axisType,"Ticks"),jE(Je)))},be),ke=Ee[Z],Ie=Ee["".concat(Z,"Ticks")],Fe=S&&S[fe]&&S[fe].hasStack&&o4n(le,S[fe].stackGroups),Ne=qE(le.type).indexOf("Bar")>=0,Be=xMe(ke,Ie),Se=[],Ae=X&&K5n({barSize:R,stackGroups:S,totalSize:W6n(Ee,Z)});if(Ne){var Ce,qe,ze=Gc(ve)?W:ve,Ve=(Ce=(qe=xMe(ke,Ie,!0))!==null&&qe!==void 0?qe:ze)!==null&&Ce!==void 0?Ce:0;Se=Y5n({barGap:O,barCategoryGap:U,bandSize:Ve!==Be?Ve:Be,sizeList:Ae[ue],maxBarSize:ze}),Ve!==Be&&(Se=Se.map(function(Qe){return ba(ba({},Qe),{},{position:ba(ba({},Qe.position),{},{offset:Qe.position.offset-Ve/2})})}))}var ht=le&&le.type&&le.type.getComposedData;ht&&ae.push({props:ba(ba({},ht(ba(ba({},Ee),{},{displayedData:te,props:y,dataKey:ce,item:le,bandSize:Be,barPosition:Se,offset:A,stackedData:Fe,layout:D,dataStartIndex:I,dataEndIndex:P}))),{},uc(uc(uc({key:le.key||"item-".concat(re)},G,Ee[G]),Z,Ee[Z]),"animationId",E)),childIndex:Ygn(le,y.children),item:le})}),ae},f=function(y,b){var w=y.props,S=y.dataStartIndex,A=y.dataEndIndex,E=y.updateId;if(!Xwt({props:w}))return null;var I=w.children,P=w.layout,R=w.stackOffset,D=w.data,O=w.reverseStackOrder,U=zkt(P),W=U.numericAxisName,V=U.cateAxisName,G=x2(I,r),Z=a4n(D,G,"".concat(W,"Id"),"".concat(V,"Id"),R,O),X=c.reduce(function(J,ce){var ve="".concat(ce.axisType,"Map");return ba(ba({},J),{},uc({},ve,q6n(w,ba(ba({},ce),{},{graphicalItems:G,stackGroups:ce.axisType===W&&Z,dataStartIndex:S,dataEndIndex:A}))))},{}),ae=G6n(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 le=X["".concat(V,"Map")],re=V6n(le),te=m(w,ba(ba({},X),{},{dataStartIndex:S,dataEndIndex:A,updateId:E,graphicalItems:G,stackGroups:Z,offset:ae}));return ba(ba({formattedGraphicalItems:te,graphicalItems:G,offset:ae,stackGroups:Z},re),X)},g=function(v){function y(b){var w,S,A;return S6n(this,y),A=E6n(this,y,[b]),uc(A,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),uc(A,"accessibilityManager",new h6n),uc(A,"handleLegendBBoxUpdate",function(E){if(E){var I=A.state,P=I.dataStartIndex,R=I.dataEndIndex,D=I.updateId;A.setState(ba({legendBBox:E},f({props:A.props,dataStartIndex:P,dataEndIndex:R,updateId:D},ba(ba({},A.state),{},{legendBBox:E}))))}}),uc(A,"handleReceiveSyncEvent",function(E,I,P){if(A.props.syncId===E){if(P===A.eventEmitterSymbol&&typeof A.props.syncMethod!="function")return;A.applySyncEvent(I)}}),uc(A,"handleBrushChange",function(E){var I=E.startIndex,P=E.endIndex;if(I!==A.state.dataStartIndex||P!==A.state.dataEndIndex){var R=A.state.updateId;A.setState(function(){return ba({dataStartIndex:I,dataEndIndex:P},f({props:A.props,dataStartIndex:I,dataEndIndex:P,updateId:R},A.state))}),A.triggerSyncEvent({dataStartIndex:I,dataEndIndex:P})}}),uc(A,"handleMouseEnter",function(E){var I=A.getMouseInfo(E);if(I){var P=ba(ba({},I),{},{isTooltipActive:!0});A.setState(P),A.triggerSyncEvent(P);var R=A.props.onMouseEnter;hc(R)&&R(P,E)}}),uc(A,"triggeredAfterMouseMove",function(E){var I=A.getMouseInfo(E),P=I?ba(ba({},I),{},{isTooltipActive:!0}):{isTooltipActive:!1};A.setState(P),A.triggerSyncEvent(P);var R=A.props.onMouseMove;hc(R)&&R(P,E)}),uc(A,"handleItemMouseEnter",function(E){A.setState(function(){return{isTooltipActive:!0,activeItem:E,activePayload:E.tooltipPayload,activeCoordinate:E.tooltipPosition||{x:E.cx,y:E.cy}}})}),uc(A,"handleItemMouseLeave",function(){A.setState(function(){return{isTooltipActive:!1}})}),uc(A,"handleMouseMove",function(E){E.persist(),A.throttleTriggeredAfterMouseMove(E)}),uc(A,"handleMouseLeave",function(E){A.throttleTriggeredAfterMouseMove.cancel();var I={isTooltipActive:!1};A.setState(I),A.triggerSyncEvent(I);var P=A.props.onMouseLeave;hc(P)&&P(I,E)}),uc(A,"handleOuterEvent",function(E){var I=Kgn(E),P=g2(A.props,"".concat(I));if(I&&hc(P)){var R,D;/.*touch.*/i.test(I)?D=A.getMouseInfo(E.changedTouches[0]):D=A.getMouseInfo(E),P((R=D)!==null&&R!==void 0?R:{},E)}}),uc(A,"handleClick",function(E){var I=A.getMouseInfo(E);if(I){var P=ba(ba({},I),{},{isTooltipActive:!0});A.setState(P),A.triggerSyncEvent(P);var R=A.props.onClick;hc(R)&&R(P,E)}}),uc(A,"handleMouseDown",function(E){var I=A.props.onMouseDown;if(hc(I)){var P=A.getMouseInfo(E);I(P,E)}}),uc(A,"handleMouseUp",function(E){var I=A.props.onMouseUp;if(hc(I)){var P=A.getMouseInfo(E);I(P,E)}}),uc(A,"handleTouchMove",function(E){E.changedTouches!=null&&E.changedTouches.length>0&&A.throttleTriggeredAfterMouseMove(E.changedTouches[0])}),uc(A,"handleTouchStart",function(E){E.changedTouches!=null&&E.changedTouches.length>0&&A.handleMouseDown(E.changedTouches[0])}),uc(A,"handleTouchEnd",function(E){E.changedTouches!=null&&E.changedTouches.length>0&&A.handleMouseUp(E.changedTouches[0])}),uc(A,"handleDoubleClick",function(E){var I=A.props.onDoubleClick;if(hc(I)){var P=A.getMouseInfo(E);I(P,E)}}),uc(A,"handleContextMenu",function(E){var I=A.props.onContextMenu;if(hc(I)){var P=A.getMouseInfo(E);I(P,E)}}),uc(A,"triggerSyncEvent",function(E){A.props.syncId!==void 0&&j9e.emit(N9e,A.props.syncId,E,A.eventEmitterSymbol)}),uc(A,"applySyncEvent",function(E){var I=A.props,P=I.layout,R=I.syncMethod,D=A.state.updateId,O=E.dataStartIndex,U=E.dataEndIndex;if(E.dataStartIndex!==void 0||E.dataEndIndex!==void 0)A.setState(ba({dataStartIndex:O,dataEndIndex:U},f({props:A.props,dataStartIndex:O,dataEndIndex:U,updateId:D},A.state)));else if(E.activeTooltipIndex!==void 0){var W=E.chartX,V=E.chartY,G=E.activeTooltipIndex,Z=A.state,X=Z.offset,ae=Z.tooltipTicks;if(!X)return;if(typeof R=="function")G=R(ae,E);else if(R==="value"){G=-1;for(var le=0;le=0){var Fe,Ne;if(W.dataKey&&!W.allowDuplicatedCategory){var Be=typeof W.dataKey=="function"?Ie:"payload.".concat(W.dataKey.toString());Fe=$Te(le,Be,G),Ne=re&&te&&$Te(te,Be,G)}else Fe=le==null?void 0:le[V],Ne=re&&te&&te[V];if(ue||fe){var Se=E.props.activeIndex!==void 0?E.props.activeIndex:V;return[j.cloneElement(E,ba(ba(ba({},R.props),Ee),{},{activeIndex:Se})),null,null]}if(!Gc(Fe))return[ke].concat(lW(A.renderActivePoints({item:R,activePoint:Fe,basePoint:Ne,childIndex:V,isRange:re})))}else{var Ae,Ce=(Ae=A.getItemByXY(A.state.activeCoordinate))!==null&&Ae!==void 0?Ae:{graphicalItem:ke},qe=Ce.graphicalItem,ze=qe.item,Ve=ze===void 0?E:ze,ht=qe.childIndex,Qe=ba(ba(ba({},R.props),Ee),{},{activeIndex:ht});return[j.cloneElement(Ve,Qe),null,null]}return re?[ke,null,null]:[ke,null]}),uc(A,"renderCustomized",function(E,I,P){return j.cloneElement(E,ba(ba({key:"recharts-customized-".concat(P)},A.props),A.state))}),uc(A,"renderMap",{CartesianGrid:{handler:Kde,once:!0},ReferenceArea:{handler:A.renderReferenceElement},ReferenceLine:{handler:Kde},ReferenceDot:{handler:A.renderReferenceElement},XAxis:{handler:Kde},YAxis:{handler:Kde},Brush:{handler:A.renderBrush,once:!0},Bar:{handler:A.renderGraphicChild},Line:{handler:A.renderGraphicChild},Area:{handler:A.renderGraphicChild},Radar:{handler:A.renderGraphicChild},RadialBar:{handler:A.renderGraphicChild},Scatter:{handler:A.renderGraphicChild},Pie:{handler:A.renderGraphicChild},Funnel:{handler:A.renderGraphicChild},Tooltip:{handler:A.renderCursor,once:!0},PolarGrid:{handler:A.renderPolarGrid,once:!0},PolarAngleAxis:{handler:A.renderPolarAxis},PolarRadiusAxis:{handler:A.renderPolarAxis},Customized:{handler:A.renderCustomized}}),A.clipPathId="".concat((w=b.id)!==null&&w!==void 0?w:WB("recharts"),"-clip"),A.throttleTriggeredAfterMouseMove=VKt(A.triggeredAfterMouseMove,(S=b.throttleDelay)!==null&&S!==void 0?S:1e3/60),A.state={},A}return P6n(y,v),A6n(y,[{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,A=w.data,E=w.height,I=w.layout,P=Bj(S,kg);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=mYe(this.state,A,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},Z=this.state.formattedGraphicalItems.find(function(ae){var le=ae.item;return le.type.name==="Scatter"});Z&&(G=ba(ba({},G),Z.props.points[R].tooltipPosition),O=Z.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 A,E;this.accessibilityManager.setDetails({offset:{left:(A=this.props.margin.left)!==null&&A!==void 0?A:0,top:(E=this.props.margin.top)!==null&&E!==void 0?E:0}})}return null}},{key:"componentDidUpdate",value:function(w){$We([Bj(w.children,kg)],[Bj(this.props.children,kg)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var w=Bj(this.props.children,kg);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,A=S.getBoundingClientRect(),E=_Nn(A),I={chartX:Math.round(w.pageX-E.left),chartY:Math.round(w.pageY-E.top)},P=A.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=Fkt(this.state,this.props.data,this.props.layout,R);if(W!=="axis"&&O&&U){var G=kP(O).scale,Z=kP(U).scale,X=G&&G.invert?G.invert(I.chartX):null,ae=Z&&Z.invert?Z.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 A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,E=this.props.layout,I=w/A,P=S/A;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=kP(U);return iNt({x:I,y:P},V)}return null}},{key:"parseEventsOfWrapper",value:function(){var w=this.props.children,S=this.getTooltipEventType(),A=Bj(w,kg),E={};A&&S==="axis"&&(A.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=UTe(this.props,this.handleOuterEvent);return ba(ba({},I),E)}},{key:"addListener",value:function(){j9e.on(N9e,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){j9e.removeListener(N9e,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(w,S,A){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}=st({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:Zr,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:Yn,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:Ta,color:"text-blue-600"},{label:"Avg Click Rate",value:`${m}%`,icon:lb,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:Al,color:"text-orange-600"},{label:"Complaints",value:u,icon:Zl,color:"text-destructive"}],g=new Map;a.forEach(b=>{var A,E;const w=b.user_id,S=g.get(w)||{name:((A=i.get(w))==null?void 0:A.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),v=x.slice(0,6).map(b=>({name:b.name,value:b.sent})),y=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?Js(new Date(b.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Zr,{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(je,{children:e.jsxs(Le,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Le,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(j_,{width:"100%",height:"100%",children:e.jsxs(PK,{data:y,children:[e.jsx(Cb,{dataKey:"date",fontSize:11}),e.jsx(Ab,{fontSize:11,unit:"%"}),e.jsx(kg,{formatter:b=>`${b}%`}),e.jsx(Dw,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(Dw,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Le,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(j_,{width:"100%",height:"100%",children:e.jsxs(yXt,{children:[e.jsx(m3,{data:v,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:b,percent:w})=>`${b} (${(w*100).toFixed(0)}%)`,fontSize:11,children:v.map((b,w)=>e.jsx(KB,{fill:Bkt[w%Bkt.length]},w))}),e.jsx(kg,{})]})})})})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Le,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(j_,{width:"100%",height:"100%",children:e.jsxs(Bat,{data:y,children:[e.jsx(Cb,{dataKey:"date",fontSize:11}),e.jsx(Ab,{fontSize:11}),e.jsx(kg,{}),e.jsx(LL,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Agent Performance"})}),e.jsx(Le,{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($e,{variant:"outline",children:[b.openRate,"%"]})})]},b.id))})]})})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Le,{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",A=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?Js(new Date(b.sent_at),"MMM d, yyyy"):""," · ",b.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"})," ",S,"%"]}),e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(lb,{className:"h-3 w-3"})," ",A,"%"]})]})]},b.id)})})})]})]})})}const Y6n=()=>{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:A,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(...A||[]),!A||A.length<1e3)break;g+=1e3}const x=[];for(g=0;;){const{data:A,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(...A||[]),!A||A.length<1e3||(g+=1e3,g>2e4))break}const v=new Map;for(const A of m||[])v.set(A.slug,{app_slug:A.slug,app_name:A.name,installs:0,enabled:0,impressions:0,expands:0,cta_clicks:0,lead_captures:0});for(const A of f){const E=v.get(A.app_slug);E&&(E.installs+=1,A.enabled&&(E.enabled+=1))}for(const A of x){const E=v.get(A.app_slug);E&&(A.event_type==="impression"?E.impressions+=1:A.event_type==="expand"?E.expands+=1:A.event_type==="cta_click"?E.cta_clicks+=1:A.event_type==="lead_capture"&&(E.lead_captures+=1))}const y=new Map;for(const A of f){if(!A.enabled)continue;const E=y.get(A.user_id)||{user_id:A.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};E.apps_enabled.includes(A.app_slug)||E.apps_enabled.push(A.app_slug),y.set(A.user_id,E)}for(const A of x){const E=y.get(A.user_id);E&&(E.events_30d+=1,A.event_type==="lead_capture"&&(E.leads_30d+=1))}const b=Array.from(y.keys());if(b.length>0){const{data:A}=await q.from("profiles").select("id, name, email").in("id",b);for(const E of A||[]){const I=y.get(E.id);I&&(I.name=E.name,I.email=E.email)}}const w=Array.from(v.values()),S=Array.from(y.values()).sort((A,E)=>E.events_30d-A.events_30d);a(w),l(S),c({installs:w.reduce((A,E)=>A+E.enabled,0),activeAgents:S.length,impressions30d:w.reduce((A,E)=>A+E.impressions,0),leads30d:w.reduce((A,E)=>A+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(je,{children:e.jsx(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(cl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(Ta,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(pn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"App Performance (last 30 days)"})}),e.jsx(Le,{children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:[r.map(u=>{const h=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(An,{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(An,{children:e.jsx(wt,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Le,{children:[e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:[i.slice(0,100).map(u=>e.jsxs(An,{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($e,{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(An,{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."]})]})]})]})},Z6n=()=>{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(v=>v.user_id)));if(x.length){const{data:v}=await q.from("profiles").select("id, name, email").in("id",x),y={};(v||[]).forEach(b=>{y[b.id]={name:b.name,email:b.email}}),i(y)}}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(je,{children:e.jsx(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(Lz,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(lc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(va,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(no,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Users by Extension Activity"})}),e.jsx(Le,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:s.map(h=>e.jsxs(An,{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?Js(new Date(h.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(wt,{className:"text-xs text-muted-foreground",children:h.last_event_at?Js(new Date(h.last_event_at),"MMM d, h:mm a"):"—"})]},h.user_id))})]})})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Recent Activity"})}),e.jsx(Le,{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($e,{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:Js(new Date(h.created_at),"MMM d, h:mm a")})]},h.id)})})})]})]})},X6n=()=>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(pa,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"analytics",children:"Analytics"}),e.jsx(Xt,{value:"website-apps",children:"Website Apps"}),e.jsx(Xt,{value:"extension",children:"Chrome Extension"}),e.jsx(Xt,{value:"content",children:"Content"}),e.jsx(Xt,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(Xt,{value:"activity",children:"Activity"}),e.jsx(Xt,{value:"shares",children:"Shares"})]}),e.jsx(Qt,{value:"analytics",className:"space-y-4",children:e.jsx(smn,{})}),e.jsx(Qt,{value:"website-apps",className:"space-y-4",children:e.jsx(Y6n,{})}),e.jsx(Qt,{value:"extension",className:"space-y-4",children:e.jsx(Z6n,{})}),e.jsx(Qt,{value:"content",className:"space-y-4",children:e.jsx(rmn,{})}),e.jsx(Qt,{value:"email-campaigns",className:"space-y-4",children:e.jsx(K6n,{})}),e.jsx(Qt,{value:"activity",className:"space-y-4",children:e.jsx(tmn,{})}),e.jsx(Qt,{value:"shares",className:"space-y-4",children:e.jsx(AWt,{})})]})]})});function Q6n(){const s=Zt(),[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,v]=j.useState([]),[y,b]=j.useState(!1),[w,S]=j.useState(null),[A,E]=j.useState(""),{data:I,isLoading:P}=st({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:Ne,error:Be}=await q.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Be)throw Be;return Ne}}),{data:R}=st({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:Ne,error:Be}=await q.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Be)throw Be;return Ne}}),{data:D}=st({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:Ne,error:Be}=await q.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Be)throw Be;return Ne}}),{data:O}=st({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:Ne,error:Be}=await q.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Be)throw Be;return Ne}}),{data:U,isLoading:W}=st({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:Ne,error:Be}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Be)throw Be;return Ne}}),V=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),m([]),g([]),v([]),a(null),E("")},G=Ne=>{a(Ne),l({title:Ne.title,description:Ne.description||"",publish_date:Ne.publish_date.split("T")[0],is_published:Ne.is_published,category_id:Ne.category_id||""}),u(Ne.preview_image_url||""),E("");const Be=(R==null?void 0:R.filter(Ce=>Ce.resource_id===Ne.id))||[];m(Be.map(Ce=>({id:Ce.id,name:Ce.name,file_url:Ce.file_url,file_size:Ce.file_size,sort_order:Ce.sort_order})));const Se=(D==null?void 0:D.filter(Ce=>Ce.resource_id===Ne.id))||[];g(Se.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===Ne.id))||[];v(Ae.map(Ce=>({id:Ce.id,title:Ce.title,canva_share_link:Ce.canva_share_link,sort_order:Ce.sort_order}))),n(!0)},Z=Ne=>{var Se;const Be=(Se=Ne.target.files)==null?void 0:Se[0];Be&&(c(Be),u(URL.createObjectURL(Be)))},X=()=>{m([...h,{name:"",file_url:"",sort_order:h.length}])},ae=Ne=>{m(h.filter((Be,Se)=>Se!==Ne))},le=(Ne,Be,Se)=>{const Ae=[...h];if(Be==="file"&&Se instanceof File){const Ce=Se.name.replace(/\.[^/.]+$/,"");Ae[Ne]={...Ae[Ne],file:Se,file_size:Se.size,name:Ae[Ne].name||Ce}}else Ae[Ne]={...Ae[Ne],[Be]:Se};m(Ae)},re=()=>{g([...f,{title:"",video_url:"",sort_order:f.length}])},te=Ne=>{g(f.filter((Be,Se)=>Se!==Ne))},J=(Ne,Be,Se)=>{const Ae=[...f];Be==="file"&&Se instanceof File?Ae[Ne]={...Ae[Ne],file:Se}:Ae[Ne]={...Ae[Ne],[Be]:Se},g(Ae)},ce=()=>{v([...x,{title:"",canva_share_link:"",sort_order:x.length}])},ve=Ne=>{v(x.filter((Be,Se)=>Se!==Ne))},fe=(Ne,Be,Se)=>{const Ae=[...x];Ae[Ne]={...Ae[Ne],[Be]:Se},v(Ae)},ue=async(Ne,Be)=>{try{const Se=await q.functions.invoke("bunny-upload",{body:{action:"create",title:Ne.name}});if(Se.error)throw Se.error;const{videoId:Ae,uploadUrl:Ce,libraryId:qe}=Se.data,ze=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ae,libraryId:qe}});if(ze.error)throw ze.error;const{uploadUrl:Ve,apiKey:ht}=ze.data,Qe=new XMLHttpRequest;return Qe.open("PUT",Ve,!0),Qe.setRequestHeader("AccessKey",ht),Qe.upload.onprogress=at=>{if(at.lengthComputable){const rt=Math.round(at.loaded/at.total*100),Ke=[...f];Ke[Be]={...Ke[Be],uploadProgress:rt},g(Ke)}},await new Promise((at,rt)=>{Qe.onload=()=>Qe.status>=200&&Qe.status<300?at():rt(new Error("Upload failed")),Qe.onerror=()=>rt(new Error("Upload failed")),Qe.send(Ne)}),`https://iframe.mediadelivery.net/embed/${qe}/${Ae}`}catch(Se){throw console.error("Bunny upload error:",Se),Se}},be=mt({mutationFn:async Ne=>{const{data:Be,error:Se}=await q.from("brokerage_resource_categories").insert({name:Ne,sort_order:(U==null?void 0:U.length)||0}).select().single();if(Se)throw Se;return Be},onSuccess:Ne=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:Ne.id}),E(""),ne.success("Category created")},onError:Ne=>{ne.error("Failed to create category: "+Ne.message)}}),Ee=mt({mutationFn:async()=>{b(!0);let Ne=(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}`);Ne=ze.publicUrl}const Be={title:i.title,description:i.description||null,preview_image_url:Ne,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let Se;if(r){const{error:Ae}=await q.from("brokerage_resources").update(Be).eq("id",r.id);if(Ae)throw Ae;Se=r.id;const Ce=(R==null?void 0:R.filter(Je=>Je.resource_id===r.id).map(Je=>Je.id))||[],qe=h.filter(Je=>Je.id).map(Je=>Je.id),ze=Ce.filter(Je=>!qe.includes(Je));ze.length>0&&await q.from("brokerage_resource_pdfs").delete().in("id",ze);const Ve=(D==null?void 0:D.filter(Je=>Je.resource_id===r.id).map(Je=>Je.id))||[],ht=f.filter(Je=>Je.id).map(Je=>Je.id),Qe=Ve.filter(Je=>!ht.includes(Je));Qe.length>0&&await q.from("brokerage_resource_videos").delete().in("id",Qe);const at=(O==null?void 0:O.filter(Je=>Je.resource_id===r.id).map(Je=>Je.id))||[],rt=x.filter(Je=>Je.id).map(Je=>Je.id),Ke=at.filter(Je=>!rt.includes(Je));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(Be).select().single();if(Ce)throw Ce;Se=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"]}),ne.success(r?"Resource updated":"Resource created"),n(!1),V(),b(!1)},onError:Ne=>{ne.error("Failed to save resource: "+Ne.message),b(!1)}}),ke=mt({mutationFn:async Ne=>{const{error:Be}=await q.from("brokerage_resources").delete().eq("id",Ne);if(Be)throw Be},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ne.success("Resource deleted")},onError:Ne=>{ne.error("Failed to delete: "+Ne.message)}}),Ie=Ne=>{if(Ne.preventDefault(),!i.title){ne.error("Please enter a title");return}Ee.mutate()},Fe=Ne=>{const Be=(R==null?void 0:R.filter(Ce=>Ce.resource_id===Ne).length)||0,Se=(D==null?void 0:D.filter(Ce=>Ce.resource_id===Ne).length)||0,Ae=(O==null?void 0:O.filter(Ce=>Ce.resource_id===Ne).length)||0;return{pdfCount:Be,videoCount:Se,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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(I==null?void 0:I.length)||0})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(I==null?void 0:I.filter(Ne=>Ne.is_published).length)||0})})]})]}),e.jsxs($,{onClick:()=>{V(),n(!0)},children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(je,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:P?e.jsx(An,{children:e.jsx(wt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(I==null?void 0:I.length)===0?e.jsx(An,{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(Ne=>{const{pdfCount:Be,videoCount:Se,linkCount:Ae}=Fe(Ne.id),Ce=U==null?void 0:U.find(qe=>qe.id===Ne.category_id);return e.jsxs(An,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ne.preview_image_url?e.jsx("img",{src:Ne.preview_image_url,alt:Ne.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(wx,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ne.title}),Ne.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Ne.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(Qr,{className:"h-3.5 w-3.5"}),Be]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fa,{className:"h-3.5 w-3.5"}),Se]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Sd,{className:"h-3.5 w-3.5"}),Ae]})]})}),e.jsx(wt,{children:Js(new Date(Ne.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 ${Ne.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:Ne.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(ht=>ht.resource_id===Ne.id))||[],ze=(D==null?void 0:D.filter(ht=>ht.resource_id===Ne.id))||[],Ve=(O==null?void 0:O.filter(ht=>ht.resource_id===Ne.id))||[];S({...Ne,pdfs:qe,videos:ze,links:Ve})},children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>G(Ne),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await mo("Delete this resource?")&&ke.mutate(Ne.id)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},Ne.id)})})]})})}),e.jsx(Os,{open:t,onOpenChange:n,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Ie,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(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(wx,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(pe,{type:"file",accept:"image/*",onChange:Z})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:i.title,onChange:Ne=>l({...i,title:Ne.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(Cp,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:i.category_id,onValueChange:Ne=>l({...i,category_id:Ne}),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(Ne=>e.jsx(Ge,{value:Ne.id,children:Ne.name},Ne.id))})]}),i.category_id&&e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(mr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Or create new category...",value:A,onChange:Ne=>E(Ne.target.value),className:"flex-1"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:!A.trim()||be.isPending,onClick:()=>be.mutate(A.trim()),children:[e.jsx(cn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(kk,{content:i.description,onChange:Ne=>l({...i,description:Ne}),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:Ne=>l({...i,publish_date:Ne.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(jn,{checked:i.is_published,onCheckedChange:Ne=>l({...i,is_published:Ne})}),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(Qr,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:X,children:[e.jsx(cn,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),h.map((Ne,Be)=>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:Ne.name,onChange:Se=>le(Be,"name",Se.target.value),className:"flex-1"}),e.jsx(pe,{type:"file",accept:".pdf",onChange:Se=>{var Ce;const Ae=(Ce=Se.target.files)==null?void 0:Ce[0];Ae&&le(Be,"file",Ae)},className:"flex-1"}),Ne.file_url&&!Ne.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>ae(Be),children:e.jsx(mr,{className:"h-4 w-4"})})]},Be))]}),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(fa,{className:"h-4 w-4"}),"Videos (",f.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:re,children:[e.jsx(cn,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),f.map((Ne,Be)=>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:Ne.title,onChange:Se=>J(Be,"title",Se.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>te(Be),children:e.jsx(mr,{className:"h-4 w-4"})})]}),e.jsx(pe,{type:"file",accept:"video/*",onChange:Se=>{var Ce;const Ae=(Ce=Se.target.files)==null?void 0:Ce[0];Ae&&J(Be,"file",Ae)}}),Ne.uploadProgress!==void 0&&Ne.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:`${Ne.uploadProgress}%`}})}),Ne.video_url&&!Ne.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},Be))]}),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(Sd,{className:"h-4 w-4"}),"Canva Links (",x.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ce,children:[e.jsx(cn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),x.map((Ne,Be)=>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:Ne.title,onChange:Se=>fe(Be,"title",Se.target.value),className:"flex-1"}),e.jsx(pe,{placeholder:"Canva Share Link",value:Ne.canva_share_link,onChange:Se=>fe(Be,"canva_share_link",Se.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>ve(Be),children:e.jsx(mr,{className:"h-4 w-4"})})]},Be))]}),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||y,children:Ee.isPending||y?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(Os,{open:!!w,onOpenChange:()=>S(null),children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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(Qr,{className:"h-4 w-4"}),"PDF Documents (",w.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:w.pdfs.map(Ne=>e.jsx("a",{href:Ne.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:Ne.name},Ne.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(fa,{className:"h-4 w-4"}),"Videos (",w.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:w.videos.map(Ne=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:Ne.title})},Ne.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(Sd,{className:"h-4 w-4"}),"Canva Links (",w.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:w.links.map(Ne=>e.jsx("a",{href:Ne.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:Ne.title},Ne.id))})]})]})]})})]})})}const vXt=[{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 J6n(){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(""),[v,y]=j.useState(""),[b,w]=j.useState(""),[S,A]=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(""),[Z,X]=j.useState("");j.useEffect(()=>{ae()},[]);const ae=async()=>{try{const{data:be,error:Ee}=await q.from("dashboard_banners").select("*").order("placement").order("sort_order");if(Ee)throw Ee;t(be||[])}catch(be){ne.error("Failed to load banners: "+be.message)}finally{r(!1)}},le=()=>{x(""),y(""),w(""),A(""),I("Learn More"),R("top"),O(""),W(!0),G(""),X(""),d(null)},re=be=>{d(be),x(be.title),y(be.description||""),w(be.image_url),A(be.link_url||""),I(be.link_text||"Learn More"),R(be.placement),O(be.section_after||""),W(be.is_active),G(be.start_date?Js(new Date(be.start_date),"yyyy-MM-dd'T'HH:mm"):""),X(be.end_date?Js(new Date(be.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},te=async be=>{var ke;const Ee=(ke=be.target.files)==null?void 0:ke[0];if(Ee){h(!0);try{const Ie=Ee.name.split(".").pop(),Fe=`${Date.now()}.${Ie}`,{error:Ne}=await q.storage.from("banner-images").upload(Fe,Ee);if(Ne)throw Ne;const{data:{publicUrl:Be}}=q.storage.from("banner-images").getPublicUrl(Fe);w(Be),ne.success("Image uploaded successfully")}catch(Ie){ne.error("Failed to upload image: "+Ie.message)}finally{h(!1)}}},J=async()=>{if(!g.trim()||!b){ne.error("Please fill in required fields (title and image)");return}f(!0);try{const be={title:g.trim(),description:v.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:Z?new Date(Z).toISOString():null};if(c){const{error:Ee}=await q.from("dashboard_banners").update(be).eq("id",c.id);if(Ee)throw Ee;ne.success("Banner updated successfully")}else{const Ee=s.filter(Ie=>Ie.placement===P).length,{error:ke}=await q.from("dashboard_banners").insert({...be,sort_order:Ee});if(ke)throw ke;ne.success("Banner created successfully")}i(!1),le(),ae()}catch(be){ne.error("Failed to save banner: "+be.message)}finally{f(!1)}},ce=async()=>{if(c)try{const{error:be}=await q.from("dashboard_banners").delete().eq("id",c.id);if(be)throw be;ne.success("Banner deleted successfully"),o(!1),d(null),ae()}catch(be){ne.error("Failed to delete banner: "+be.message)}},ve=async be=>{try{const{error:Ee}=await q.from("dashboard_banners").update({is_active:!be.is_active}).eq("id",be.id);if(Ee)throw Ee;ne.success(be.is_active?"Banner deactivated":"Banner activated"),ae()}catch(Ee){ne.error("Failed to update banner: "+Ee.message)}},fe=s.filter(be=>be.placement==="top"),ue=s.filter(be=>be.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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Hc,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(Vn,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(Os,{open:a&&P==="top",onOpenChange:be=>{be||le(),i(be),be&&R("top")},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:()=>{le(),R("top")},children:[e.jsx(cn,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(Er,{children:"Configure the banner's content and display settings"})]}),e.jsx($kt,{title:g,setTitle:x,description:v,setDescription:y,imageUrl:b,linkUrl:S,setLinkUrl:A,linkText:E,setLinkText:I,placement:P,setPlacement:R,sectionAfter:D,setSectionAfter:O,isActive:U,setIsActive:W,startDate:V,setStartDate:G,endDate:Z,setEndDate:X,handleImageUpload:te,uploading:u,showPlacementOptions:!1}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>{i(!1),le()},children:"Cancel"}),e.jsx($,{onClick:J,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Le,{children:fe.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:fe.map(be=>e.jsx(Ukt,{banner:be,onEdit:()=>re(be),onDelete:()=>{d(be),o(!0)},onToggleActive:()=>ve(be)},be.id))})})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Hc,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(Vn,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(Os,{open:a&&P==="between",onOpenChange:be=>{be||le(),i(be),be&&R("between")},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:()=>{le(),R("between")},children:[e.jsx(cn,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(Er,{children:"Configure where this banner appears between sections"})]}),e.jsx($kt,{title:g,setTitle:x,description:v,setDescription:y,imageUrl:b,linkUrl:S,setLinkUrl:A,linkText:E,setLinkText:I,placement:P,setPlacement:R,sectionAfter:D,setSectionAfter:O,isActive:U,setIsActive:W,startDate:V,setStartDate:G,endDate:Z,setEndDate:X,handleImageUpload:te,uploading:u,showPlacementOptions:!0}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>{i(!1),le()},children:"Cancel"}),e.jsx($,{onClick:J,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Le,{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(be=>e.jsx(Ukt,{banner:be,onEdit:()=>re(be),onDelete:()=>{d(be),o(!0)},onToggleActive:()=>ve(be),showSection:!0},be.id))})})]})]}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Delete Banner"}),e.jsxs(Er,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:ce,children:"Delete"})]})]})})]})}function $kt({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:v,endDate:y,setEndDate:b,handleImageUpload:w,uploading:S,showPlacementOptions:A}){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)})]})]}),A&&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:vXt.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(Ea,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(pe,{id:"startDate",type:"datetime-local",value:x,onChange:E=>v(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(Ea,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(pe,{id:"endDate",type:"datetime-local",value:y,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(jn,{id:"isActive",checked:f,onCheckedChange:g}),e.jsx(ee,{htmlFor:"isActive",children:"Active"})]})})]})}function Ukt({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=vXt.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(zg,{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($e,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx($e,{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(Pm,{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(Ir,{className:"h-4 w-4"})})}),e.jsx($,{variant:"ghost",size:"icon",onClick:r,children:s.is_active?e.jsx(Ta,{className:"h-4 w-4"}):e.jsx(Nx,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})]})}const Yde={open:{label:"Open",icon:ca,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Ah,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Wl,color:"bg-green-500"},closed:{label:"Closed",icon:ju,color:"bg-muted-foreground"}},qkt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function eRn(){var P,R;const{user:s}=_s(),t=Zt(),[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}=st({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:v=[]}=st({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:Z}=await q.from("support_notification_settings").select("user_id, receive_notifications");if(Z)throw Z;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:y=[]}=st({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=mt({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"]}),ne.success("Notification settings updated")},onError:()=>{ne.error("Failed to update settings")}}),w=mt({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}),ne.success("Status updated")},onError:()=>{ne.error("Failed to update status")}}),S=mt({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"]}),ne.success("Ticket assigned")},onError:()=>{ne.error("Failed to assign ticket")}}),A=mt({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([]),ne.success("Reply sent!")},onError:()=>{ne.error("Failed to send reply")}}),E=()=>{!a.trim()&&l.length===0||A.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?(Yde[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(Va,{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($e,{variant:"secondary",children:qkt[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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm",children:"Status"})}),e.jsx(Le,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm",children:"Assigned To"})}),e.jsx(Le,{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"}),v.map(D=>e.jsx(Ge,{value:D.id,children:D.name},D.id))]})]})})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Vn,{children:["Created on ",Js(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Le,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Conversation"})}),e.jsxs(Le,{children:[e.jsx(go,{className:"h-[300px] pr-4",children:y.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:y.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:Js(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(vWt,{attachments:D.attachments})]},D.id)})})}),e.jsx(Vc,{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||A.isPending,className:"self-end",children:e.jsx(Zr,{className:"h-4 w-4"})})]}),e.jsx(yWt,{value:l,onChange:o,disabled:A.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($e,{variant:"destructive",className:"ml-2",children:[I," open"]})]})]}),e.jsxs(Os,{open:m,onOpenChange:f,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",children:[e.jsx(Nd,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Email Notification Settings"}),e.jsx(Er,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:v.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(zy,{className:"h-4 w-4 text-primary"}):e.jsx(KS,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(jn,{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(pa,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(ga,{children:[e.jsx(Xt,{value:"all",children:"All"}),e.jsx(Xt,{value:"open",children:"Open"}),e.jsx(Xt,{value:"in_progress",children:"In Progress"}),e.jsx(Xt,{value:"resolved",children:"Resolved"}),e.jsx(Xt,{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(je,{children:e.jsxs(Le,{className:"text-center py-12",children:[e.jsx(Ah,{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=Yde[D.status].icon;return e.jsx(je,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(D),children:e.jsx(Le,{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($e,{variant:"outline",className:"text-xs",children:qkt[D.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(U=D.profiles)==null?void 0:U.name," • ",Js(new Date(D.created_at),"MMM d, yyyy")]}),D.assigned_to&&e.jsxs($e,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(sl,{className:"h-3 w-3"}),((W=v.find(V=>V.id===D.assigned_to))==null?void 0:W.name)||"Assigned"]})]})]}),e.jsxs($e,{className:Yde[D.status].color,children:[e.jsx(O,{className:"h-3 w-3 mr-1"}),Yde[D.status].label]})]})})},D.id)})})})]})]})})}const bXt=Sb.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 tRn({content:s,onChange:t,variables:n}){const r=z6e({extensions:[B6e,U6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),q6e.configure({types:["heading","paragraph"]}),qnt,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(kE,{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(AE,{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(E0,{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(c2,{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(RI,{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(LI,{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(DI,{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(Sd,{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(SE,{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(FE,{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(RE,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(dV,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(Cu,{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(O6e,{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($e,{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 sRn(){const s=Zt(),[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:v}=st({queryKey:["email-templates"],queryFn:async()=>{const{data:A,error:E}=await q.from("email_templates").select("*").order("name");if(E)throw E;return A.map(I=>({...I,available_variables:I.available_variables||[]}))}}),y=mt({mutationFn:async A=>{const{error:E}=await q.from("email_templates").update({subject:A.subject,body_html:A.body_html,description:A.description,is_active:A.is_active}).eq("id",A.id);if(E)throw E},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),ne.success("Email template updated successfully"),n(null)},onError:A=>{ne.error("Failed to update template: "+A.message)}}),b=A=>{n(A),l(A.subject),c(A.body_html),u(A.description||""),m(A.is_active),g("visual")},w=()=>{t&&y.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:h})},S=(A,E)=>{let I=A;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(Va,{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(Ta,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs($,{onClick:w,disabled:y.isPending,children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),y.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5"}),t.name]}),e.jsxs(Vn,{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(jn,{id:"active-toggle",checked:h,onCheckedChange:m})]})]})}),e.jsxs(Le,{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:A=>u(A.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:A=>l(A.target.value),placeholder:"Email subject line"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["You can use variables like ","{{name}}"," in the subject"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Email Body"}),e.jsx(pa,{value:f,onValueChange:A=>g(A),children:e.jsxs(ga,{className:"h-8",children:[e.jsxs(Xt,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(ZN,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Xt,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(SE,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),f==="visual"?e.jsx(tRn,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Rs,{value:o,onChange:A=>c(A.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(Os,{open:!!r,onOpenChange:()=>a(null),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Email Preview"}),e.jsxs(Er,{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"})]}),v?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((A,E)=>e.jsx(je,{children:e.jsxs(St,{children:[e.jsx(xn,{className:"h-5 w-48"}),e.jsx(xn,{className:"h-4 w-96"})]})},E))}):e.jsx("div",{className:"grid gap-4",children:x==null?void 0:x.map(A=>e.jsxs(je,{className:"hover:shadow-md transition-shadow",children:[e.jsx(St,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Et,{className:"flex items-center gap-2 text-lg",children:[e.jsx(pn,{className:"h-5 w-5 text-muted-foreground"}),A.name,!A.is_active&&e.jsx($e,{variant:"secondary",children:"Inactive"})]}),e.jsx(Vn,{children:A.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>a(A),children:[e.jsx(Ta,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs($,{size:"sm",onClick:()=>b(A),children:[e.jsx(bp,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Le,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),e.jsx("code",{className:"bg-muted px-2 py-0.5 rounded text-sm",children:A.subject})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Variables:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:A.available_variables.map(E=>e.jsx($e,{variant:"outline",className:"font-mono text-xs",children:`{{${E.key}}}`},E.key))})]})]})})]},A.id))}),e.jsx(Os,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{children:["Email Preview: ",r==null?void 0:r.name]}),e.jsxs(Er,{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 nRn(){const s=Zt(),[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=[]}=st({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:v=[],isLoading:y}=st({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=mt({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),ne.success(r?"Template updated":"Template created")},onError:()=>ne.error("Failed to save template")}),w=mt({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"]}),ne.success("Template deleted")}}),S=mt({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),ne.success(i?"Category updated":"Category created")},onError:()=>ne.error("Failed to save category")}),A=mt({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"]}),ne.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(Dm,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(pa,{value:t,onValueChange:n,children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"templates",className:"gap-2",children:[e.jsx(pn,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Xt,{value:"categories",className:"gap-2",children:[e.jsx(Nv,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(Qt,{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(cn,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(je,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:y?e.jsx(An,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin mx-auto"})})}):v.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):v.map(D=>e.jsxs(An,{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($e,{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($e,{variant:"secondary",children:D.tone}):"—"}),e.jsx(wt,{children:e.jsx($e,{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(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:async()=>{await mo("Delete this template?")&&w.mutate(D.id)},children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},D.id))})]})})})]}),e.jsxs(Qt,{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(cn,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Et,{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(pi,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:async()=>{await mo("Delete this category?")&&A.mutate(D.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Le,{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:[v.filter(O=>O.category_id===D.id).length," templates"]})]})]},D.id))})]})]}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Fs,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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(jn,{checked:h.is_active,onCheckedChange:D=>m(O=>({...O,is_active:D}))}),e.jsx(ee,{children:"Active"})]})]}),e.jsxs(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Save Changes":"Create Template"]})]})]})}),e.jsx(Os,{open:d,onOpenChange:u,children:e.jsxs(Fs,{className:"sm:max-w-[450px]",children:[e.jsx(Us,{children:e.jsx($s,{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(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const rRn=({brokerageId:s})=>{var Pa,ii,$i;const{toast:t}=Bi(),n=Zn(),[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,v]=j.useState({}),[y,b]=j.useState(!1),[w,S]=j.useState(!1),[A,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,Z]=j.useState(null),[X,ae]=j.useState(!1),[le,re]=j.useState(!1),[te,J]=j.useState(!1),[ce,ve]=j.useState(""),[fe,ue]=j.useState(!1),[be,Ee]=j.useState([]),[ke,Ie]=j.useState(!1),[Fe,Ne]=j.useState(!1),[Be,Se]=j.useState(null),[Ae,Ce]=j.useState({name:"",phone:"",email:""}),[qe,ze]=j.useState(!1),[Ve,ht]=j.useState(!1),[Qe,at]=j.useState(null),[rt,Ke]=j.useState("asc"),[Je,ft]=j.useState(!1),[gt,es]=j.useState(null),[Ht,as]=j.useState(!1),[bs,Ut]=j.useState(null),[Ft,is]=j.useState(""),[jt,zs]=j.useState(!1),[yt,gs]=j.useState(null);j.useEffect(()=>{Bt(),Ds(),Ss()},[s]);const Ss=async()=>{try{const{data:Ln}=await q.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",s).maybeSingle();if(!Ln||!Ln.enabled){P(null),D([]);return}const{data:xa}=await q.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",Ln.id).order("sort_order",{ascending:!0});P({id:Ln.id,name:Ln.name}),D(xa||[]),xa&&xa.length>0&&U(xa[0].id)}catch(Ln){console.error("Error loading partnership packages:",Ln)}},Ds=async()=>{try{const{data:Ln,error:xa}=await q.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(xa)throw xa;Ee((Ln==null?void 0:Ln.map(Ka=>Ka.user_id))||[])}catch(Ln){console.error("Error loading brokerage managers:",Ln)}},Bt=async()=>{try{l(!0);const{data:Ln,error:xa}=await q.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(xa)throw xa;const Ka=Ln.agents||[];if(a(Ka),Ka.length>0){const uo=Ka.map(Fd=>Fd.id),{data:Tc}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",uo);if(Tc&&Tc.length>0){const Fd=Tc.map(ti=>ti.assistant_id),{data:Nl}=await q.from("profiles").select("id, name, email").in("id",Fd),Ho={};for(const ti of Tc){const Yr=Nl==null?void 0:Nl.find(Eo=>Eo.id===ti.assistant_id);Yr&&(Ho[ti.agent_id]={name:Yr.name||"",email:Yr.email||""})}v(Ho)}else v({})}}catch(Ln){console.error("Error loading agents:",Ln),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},zt=async()=>{var Ln;if(!A.email||!A.name||!A.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}S(!0);try{const{data:{session:xa}}=await q.auth.getSession(),Ka=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({...A,brokerageId:s,partnershipPackageId:I&&O!=="none"?O:void 0})}),uo=await Ka.json();if(!Ka.ok)throw new Error(uo.error||"Failed to create agent");t({title:"Success",description:`Agent ${A.email} created successfully`}),E({email:"",name:"",password:"",phone:""}),U(((Ln=R[0])==null?void 0:Ln.id)||"none"),b(!1),Bt()}catch(xa){console.error("Error creating agent:",xa),t({title:"Error",description:xa.message||"Failed to create agent",variant:"destructive"})}finally{S(!1)}},vs=async Ln=>{try{const{data:{session:xa}}=await q.auth.getSession(),Ka=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:Ln})}),uo=await Ka.json();if(!Ka.ok)throw new Error(uo.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"})}},dn=async(Ln,xa)=>{try{const{error:Ka}=await q.functions.invoke("send-password-reset",{body:{email:Ln,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(Ka)throw Ka;t({title:"Password Reset Sent",description:`Password reset email sent to ${xa}`})}catch(Ka){console.error("Error sending password reset:",Ka),t({title:"Error",description:Ka.message||"Failed to send password reset email",variant:"destructive"})}},Ks=Ln=>{Z(Ln),V(!0)},Cn=Ln=>{Se(Ln),Ce({name:Ln.name,phone:Ln.phone||"",email:Ln.email}),Ne(!0)},Rr=async()=>{if(!Be)return;if(!Ae.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Ln=Ae.email.trim().toLowerCase()!==Be.email.toLowerCase();ze(!0);try{if(Ln){if(!Ae.email.trim())throw new Error("Email is required");ht(!0);const{data:{session:Ka}}=await q.auth.getSession(),uo=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ka==null?void 0:Ka.access_token}`},body:JSON.stringify({agentId:Be.id,newEmail:Ae.email.trim(),brokerageId:s})}),Tc=await uo.json();if(ht(!1),!uo.ok)throw new Error(Tc.error||"Failed to update email")}const{error:xa}=await q.from("profiles").update({name:Ae.name.trim(),phone:Ae.phone.trim()||null}).eq("id",Be.id);if(xa)throw xa;t({title:"Success",description:"Agent profile updated successfully"}),Ne(!1),Se(null),Bt()}catch(xa){console.error("Error updating agent:",xa),t({title:"Error",description:xa.message||"Failed to update agent",variant:"destructive"})}finally{ze(!1),ht(!1)}},ia=async()=>{if(!ce){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}ue(!0);try{const{data:{session:Ln}}=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 ${Ln==null?void 0:Ln.access_token}`},body:JSON.stringify({userId:ce,role:"brokerage_manager",action:"add",brokerageId:s})}),Ka=await xa.json();if(!xa.ok)throw new Error(Ka.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),J(!1),ve(""),Ds()}catch(Ln){console.error("Error adding brokerage manager:",Ln),t({title:"Error",description:Ln.message||"Failed to add brokerage manager",variant:"destructive"})}finally{ue(!1)}},Hs=async Ln=>{try{const{data:{session:xa}}=await q.auth.getSession(),Ka=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:Ln,role:"brokerage_manager",action:"remove",brokerageId:s})}),uo=await Ka.json();if(!Ka.ok)throw new Error(uo.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),Ds()}catch(xa){console.error("Error removing brokerage manager:",xa),t({title:"Error",description:xa.message||"Failed to remove brokerage manager",variant:"destructive"})}},Br=Ln=>be.includes(Ln),Ur=Ln=>{Ut(Ln),is(""),as(!0)},Wn=async()=>{if(!(!bs||!Ft)){if(Ft.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}zs(!0);try{const{data:{session:Ln}}=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 ${Ln==null?void 0:Ln.access_token}`},body:JSON.stringify({agentId:bs.id,brokerageId:s,action:"set_password",newPassword:Ft})}),Ka=await xa.json();if(!xa.ok)throw new Error(Ka.error||"Failed to set password");t({title:"Success",description:`Password set for ${bs.name}`}),as(!1),Ut(null),is("")}catch(Ln){console.error("Error setting password:",Ln),t({title:"Error",description:Ln.message||"Failed to set password",variant:"destructive"})}finally{zs(!1)}}},Sn=async Ln=>{gs(Ln.id);try{const{data:{session:xa}}=await q.auth.getSession(),Ka=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:Ln.id,brokerageId:s,action:"claim_account"})}),uo=await Ka.json();if(!Ka.ok)throw new Error(uo.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Ln.name}`}),Bt()}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:Ln}}=await q.auth.getSession(),xa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ln==null?void 0:Ln.access_token}`},body:JSON.stringify({userId:G.id,brokerageId:s})}),Ka=await xa.json();if(!xa.ok)throw new Error(Ka.error||"Failed to remove agent");t({title:"Success",description:`${G.name} has been removed from your brokerage`}),V(!1),Z(null),Bt()}catch(Ln){console.error("Error removing agent:",Ln),t({title:"Error",description:Ln.message||"Failed to remove agent",variant:"destructive"})}finally{ae(!1)}}},bn=Ln=>{const xa=Ln.trim().split(" ");return xa.length>1?xa[xa.length-1].toLowerCase():Ln.toLowerCase()},xs=Ln=>{Qe===Ln?Ke(rt==="asc"?"desc":"asc"):(at(Ln),Ke("asc"))},Tr=Ln=>Qe!==Ln?e.jsx(Dy,{className:"ml-1 h-4 w-4"}):rt==="asc"?e.jsx(Zf,{className:"ml-1 h-4 w-4"}):e.jsx(Lg,{className:"ml-1 h-4 w-4"}),Lr=r.filter(Ln=>{if(d==="active"&&!Ln.claimed||d==="pending"&&Ln.claimed)return!1;if(!o)return!0;const xa=o.toLowerCase();return Ln.name.toLowerCase().includes(xa)||Ln.email.toLowerCase().includes(xa)}),la=[...Lr].sort((Ln,xa)=>{if(!Qe)return 0;let Ka=0;return Qe==="name"?Ka=bn(Ln.name).localeCompare(bn(xa.name)):Qe==="status"&&(Ka=Ln.claimed===xa.claimed?0:Ln.claimed?-1:1),rt==="asc"?Ka:-Ka});Lr.filter(Ln=>Ln.claimed&&!Br(Ln.id));const Xn=Ln=>{m(xa=>{const Ka=new Set(xa);return Ka.has(Ln)?Ka.delete(Ln):Ka.add(Ln),Ka})},wr=()=>{h.size===la.length?m(new Set):m(new Set(la.map(Ln=>Ln.id)))},Bn=()=>{m(new Set)},cr=async()=>{const Ln=Array.from(h);if(Ln.length===0)return;g(!0);let xa=0,Ka=0;try{const{data:{session:uo}}=await q.auth.getSession();for(const Tc of Ln)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${uo==null?void 0:uo.access_token}`},body:JSON.stringify({userId:Tc})})).ok?xa++:Ka++}catch{Ka++}xa>0?t({title:"Success",description:`Welcome emails sent to ${xa} agent${xa>1?"s":""}${Ka>0?` (${Ka} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Bn()}catch(uo){console.error("Error bulk sending welcome emails:",uo),t({title:"Error",description:uo.message||"Failed to send welcome emails",variant:"destructive"})}finally{g(!1)}};return i?e.jsx(je,{children:e.jsx(Le,{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(je,{children:[e.jsx(St,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Et,{children:"Agents"}),e.jsx(Vn,{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(Tf,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs($,{variant:"outline",onClick:()=>re(!0),children:[e.jsx(KN,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs($,{onClick:()=>b(!0),children:[e.jsx(lc,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(Le,{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:Ln=>c(Ln.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:d,onValueChange:Ln=>u(Ln),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(Ka=>h.has(Ka.id)&&Ka.email).map(Ka=>({email:Ka.email,name:Ka.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(xa)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:xa}})},disabled:f,children:[e.jsx(gm,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:cr,disabled:f,children:[e.jsx(pn,{className:"mr-2 h-4 w-4"}),f?"Sending...":"Resend Welcome Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:Bn,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(ai,{checked:la.length>0&&h.size===la.length,onCheckedChange:wr,"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)",Tr("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",Tr("status")]})}),e.jsx(Dt,{children:"Actions"})]})}),e.jsx(fi,{children:la.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):la.map(Ln=>e.jsxs(An,{children:[e.jsx(wt,{children:e.jsx(ai,{checked:h.has(Ln.id),onCheckedChange:()=>Xn(Ln.id),"aria-label":`Select ${Ln.name}`})}),e.jsx(wt,{className:"font-medium",children:Ln.name}),e.jsx(wt,{children:Ln.email}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Ln.claimed?e.jsx($e,{variant:"default",children:"Active"}):e.jsx($e,{variant:"secondary",children:"Pending"}),Br(Ln.id)&&e.jsxs($e,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(Rm,{className:"mr-1 h-3 w-3"}),"Manager"]}),x[Ln.id]&&e.jsxs($e,{variant:"outline",className:"text-xs",children:[e.jsx(Yn,{className:"mr-1 h-3 w-3"}),"Asst: ",x[Ln.id].name||x[Ln.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:()=>{es(Ln),ft(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(kx,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Cn(Ln),title:"Edit agent",children:e.jsx(pi,{className:"h-4 w-4"})}),!Ln.claimed&&e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>vs(Ln.id),title:"Resend welcome email",children:e.jsx(pn,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Sn(Ln),title:"Claim account for agent",disabled:yt===Ln.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(u2,{className:"h-4 w-4"})})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Ur(Ln),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(jc,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>dn(Ln.email,Ln.name),title:"Send password reset email",children:e.jsx(VI,{className:"h-4 w-4"})}),Br(Ln.id)&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Hs(Ln.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(Tf,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Ks(Ln),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},Ln.id))})]})})]})]}),e.jsx(Os,{open:y,onOpenChange:b,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Add New Agent"}),e.jsx(Er,{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:A.name,onChange:Ln=>E({...A,name:Ln.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:A.email,onChange:Ln=>E({...A,email:Ln.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:A.phone,onChange:Ln=>E({...A,phone:Ln.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:A.password,onChange:Ln=>E({...A,password:Ln.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(Ln=>e.jsx(Ge,{value:Ln.id,children:Ln.name},Ln.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(Ln=>Ln.id===O))==null?void 0:Pa.description)||"Their welcome email will list what is included in this package."})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx($,{onClick:zt,disabled:w,children:w?"Creating...":"Create Agent"})]})]})}),e.jsx(Os,{open:W,onOpenChange:V,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Remove Agent"}),e.jsxs(Er,{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(Nr,{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:le,onOpenChange:re,fixedBrokerageId:s,onSuccess:Bt}),e.jsx(Os,{open:te,onOpenChange:J,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Add Brokerage Manager"}),e.jsx(Er,{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(Gd,{open:ke,onOpenChange:Ie,children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":ke,className:"w-full justify-between",children:[ce?((ii=r.find(Ln=>Ln.id===ce))==null?void 0:ii.name)+" ("+(($i=r.find(Ln=>Ln.id===ce))==null?void 0:$i.email)+")":"Select an agent to promote...",e.jsx(kw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Dd,{className:"w-full p-0",align:"start",children:e.jsxs(N2,{children:[e.jsx(k2,{placeholder:"Search by name or email..."}),e.jsxs(S2,{className:"max-h-[200px]",children:[e.jsx(C2,{children:"No eligible agents found."}),e.jsx(Rw,{children:r.filter(Ln=>!Br(Ln.id)).map(Ln=>e.jsxs(h1,{value:`${Ln.name} ${Ln.email}`,onSelect:()=>{ve(Ln.id),Ie(!1)},children:[e.jsx(ma,{className:`mr-2 h-4 w-4 ${ce===Ln.id?"opacity-100":"opacity-0"}`}),Ln.name," (",Ln.email,")"]},Ln.id))})]})]})})]}),r.filter(Ln=>!Br(Ln.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>J(!1),children:"Cancel"}),e.jsx($,{onClick:ia,disabled:fe||!ce,children:fe?"Adding...":"Add as Manager"})]})]})}),e.jsx(Os,{open:Fe,onOpenChange:Ne,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Edit Agent"}),e.jsxs(Er,{children:["Update profile information for ",Be==null?void 0:Be.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:Ln=>Ce({...Ae,name:Ln.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:Ln=>Ce({...Ae,email:Ln.target.value}),placeholder:"agent@example.com"}),Ae.email.trim().toLowerCase()!==(Be==null?void 0:Be.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:Ln=>Ce({...Ae,phone:Ln.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>Ne(!1),children:"Cancel"}),e.jsx($,{onClick:Rr,disabled:qe||Ve,children:Ve?"Updating email...":qe?"Saving...":"Save Changes"})]})]})}),gt&&e.jsx(_Wt,{open:Je,onOpenChange:Ln=>{ft(Ln),Ln||es(null)},userId:gt.id,userName:gt.name}),e.jsx(Os,{open:Ht,onOpenChange:as,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Set Password"}),e.jsxs(Er,{children:["Set a new password for ",bs==null?void 0:bs.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:Ln=>is(Ln.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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>as(!1),children:"Cancel"}),e.jsx($,{onClick:Wn,disabled:jt||!Ft||Ft.length<6,children:jt?"Setting...":"Set Password"})]})]})})]})},aRn={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},iRn={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},oRn=s=>{switch(s){case"academy_video":return e.jsx(fa,{className:"h-4 w-4"});case"template":return e.jsx(Qr,{className:"h-4 w-4"});case"toolbox":return e.jsx(Qr,{className:"h-4 w-4"});case"newsletter":return e.jsx(XN,{className:"h-4 w-4"});case"social_swag":return e.jsx(wn,{className:"h-4 w-4"});case"event":return e.jsx(Ea,{className:"h-4 w-4"});default:return e.jsx(Ir,{className:"h-4 w-4"})}},lRn=({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:v}=await q.from("profiles").select("id, name, email").eq("brokerage_id",s);if(v)throw v;const y=x.map(O=>O.id),b=new Map(x.map(O=>[O.id,O]));if(y.length===0){r([]),i([]),o([]);return}const{data:w,error:S}=await q.from("activity_logs").select("*").in("user_id",y).order("launched_at",{ascending:!1});if(S)throw S;const A=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(A);const{data:E,error:I}=await q.from("content_engagement_logs").select("*").in("user_id",y).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:""})}),A.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(v=>v.user_id===x),g=x=>a.filter(v=>v.user_id===x);return c?e.jsx(je,{children:e.jsx(Le,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Agent Activity"}),e.jsx(Vn,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Le,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:l.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(x=>e.jsxs(An,{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($e,{variant:"outline",className:"gap-1",children:[e.jsx(Ou,{className:"h-3 w-3"}),x.app_launches]})}),e.jsx(wt,{className:"text-center",children:e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Qr,{className:"h-3 w-3"}),x.content_views]})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:x.last_activity&&hu(new Date(x.last_activity),{addSuffix:!0})})]},x.user_id))})]})})})]}),e.jsx(Os,{open:!!u,onOpenChange:x=>!x&&h(null),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs($s,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(Er,{children:u==null?void 0:u.email})]}),e.jsxs(pa,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ga,{className:"grid w-full grid-cols-2",children:[e.jsx(Xt,{value:"content",children:"Content Engagement"}),e.jsx(Xt,{value:"apps",children:"App Launches"})]}),e.jsx(Qt,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{children:"Resource"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Action"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(fi,{children:u&&g(u.id).length===0?e.jsx(An,{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(An,{children:[e.jsx(wt,{className:"max-w-[200px] truncate font-medium",children:x.resource_title}),e.jsx(wt,{children:e.jsxs($e,{variant:"outline",className:"gap-1",children:[oRn(x.resource_type),aRn[x.resource_type]||x.resource_type]})}),e.jsx(wt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:iRn[x.action_type]||x.action_type})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:hu(new Date(x.created_at),{addSuffix:!0})})]},x.id))})]})})}),e.jsx(Qt,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{children:"App"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(fi,{children:u&&f(u.id).length===0?e.jsx(An,{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(An,{children:[e.jsx(wt,{children:e.jsx($e,{variant:"outline",children:x.app_name})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:hu(new Date(x.launched_at),{addSuffix:!0})})]},x.id))})]})})})]})]})})]})},cRn=({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(A=>A.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:v}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),y=new Date;y.setDate(y.getDate()-7);const{count:b}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",y.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:v||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(je,{children:e.jsx(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(Wl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(ca,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(rf,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"This Week"}),e.jsx(rf,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"This Month"}),e.jsx(rf,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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"})]})]})]})},dRn=({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:y,error:b}=await q.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(b)throw b;n(y||[])}catch(y){console.error("Error loading invite codes:",y),ne.error("Failed to load invite links")}finally{a(!1)}},m=()=>Math.random().toString(36).substring(2,8).toUpperCase(),f=async()=>{l(!0);try{const y=m(),{error:b}=await q.from("invite_codes").insert({code:y,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(b)throw b;ne.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),h()}catch(y){console.error("Error creating invite code:",y),ne.error("Failed to create invite link")}finally{l(!1)}},g=async y=>{try{const{error:b}=await q.from("invite_codes").delete().eq("id",y);if(b)throw b;ne.success("Invite link deleted"),n(t.filter(w=>w.id!==y))}catch(b){console.error("Error deleting invite code:",b),ne.error("Failed to delete invite link")}},x=async(y,b)=>{try{const{error:w}=await q.from("invite_codes").update({is_active:!b}).eq("id",y);if(w)throw w;n(t.map(S=>S.id===y?{...S,is_active:!b}:S)),ne.success(`Invite link ${b?"deactivated":"activated"}`)}catch(w){console.error("Error toggling invite code:",w),ne.error("Failed to update invite link")}},v=y=>{const b=`${window.location.origin}/join?code=${y}`;navigator.clipboard.writeText(b),ne.success("Link copied to clipboard!")};return r?e.jsx(je,{children:e.jsx(Le,{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Sd,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(Vn,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(Os,{open:o,onOpenChange:c,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(cn,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Create Invite Link"}),e.jsx(Er,{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:y=>u({...d,description:y.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:y=>u({...d,maxUses:y.target.value})})]}),e.jsx($,{onClick:f,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Le,{children:t.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 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(y=>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:y.code}),e.jsx($e,{variant:y.is_active?"default":"secondary",children:y.is_active?"Active":"Inactive"})]}),y.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:y.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[y.uses_count," uses",y.max_uses&&` / ${y.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>v(y.code),title:"Copy link",children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>x(y.id,y.is_active),title:y.is_active?"Deactivate":"Activate",children:y.is_active?"Disable":"Enable"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>g(y.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(qn,{className:"h-4 w-4"})})]})]},y.id))})})]})},uRn=({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),v=()=>{const S=o.trim().toLowerCase();if(S&&x(S)&&!d.includes(S)){if(d.length>=10){ne.error("Maximum 10 emails per invite");return}u([...d,S]),c("")}else S&&!x(S)?ne.error("Please enter a valid email address"):d.includes(S)&&ne.error("Email already added")},y=S=>{u(d.filter(A=>A!==S))},b=S=>{(S.key==="Enter"||S.key===",")&&(S.preventDefault(),v())},w=async()=>{if(d.length===0){ne.error("Please add at least one email address");return}g(!0);try{const{data:S,error:A}=await q.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:h.trim()||void 0,referralCode:n,brokerageId:r,senderName:a,brokerageName:i}});if(A)throw A;S.successCount===S.totalCount?ne.success(`${S.successCount} invite${S.successCount>1?"s":""} sent successfully!`):ne.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),ne.error("Failed to send invites. Please try again.")}finally{g(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[550px]",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(Er,{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(dl,{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:v}),e.jsx($,{type:"button",variant:"secondary",onClick:v,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(S=>e.jsxs($e,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[S,e.jsx("button",{type:"button",onClick:()=>y(S),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(mr,{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(wn,{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(Zr,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},hRn=({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($e,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(Wl,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs($e,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(ju,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(ca,{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(pn,{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 ",Js(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},mRn=()=>{const{brokerageId:s,user:t}=_s(),[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&&v()},[s]);const v=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)}},y=()=>{const E=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(E),ne.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,A=Math.max(0,Math.ceil((299-S)/25));return u?null:e.jsxs(e.Fragment,{children:[e.jsxs(je,{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(dl,{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(Wl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),A>0&&S<299&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Refer ",A," more = ",e.jsx("span",{className:"text-primary",children:"FREE membership!"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your membership could cost $0/month"})]}),S>=299&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(wn,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(Le,{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(pn,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs($,{onClick:y,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Za,{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(su,{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(Yn,{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(ca,{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(hRn,{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($e,{variant:E.status==="qualified"?"default":E.status==="pending"?"secondary":"destructive",className:E.status==="qualified"?"bg-green-600":"",children:[E.status==="qualified"&&e.jsx(Wl,{className:"h-3 w-3 mr-1"}),E.status]})]},E.id)})]})]})]}),e.jsx(uRn,{open:m,onOpenChange:f,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>x(E=>E+1)})]})},fRn=({brokerageId:s})=>{const t=Zn(),{teams:n,isLoading:r}=d3(s),{data:a,isLoading:i}=st({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:v}=await q.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",m),{data:y}=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;(v||[]).forEach(E=>{w.set(E.owner_user_id,(w.get(E.owner_user_id)||0)+1)});const S=new Map;(y||[]).forEach(E=>{S.set(E.owner_user_id,(S.get(E.owner_user_id)||0)+1)});const A=new Map;return(b||[]).forEach(E=>{A.set(E.owner_user_id,(A.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+(A.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(je,{children:[e.jsx(St,{children:e.jsx(xn,{className:"h-5 w-32"})}),e.jsx(Le,{children:e.jsx(xn,{className:"h-24 w-full"})})]},u))});if(n.length===0)return e.jsx(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Yn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-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(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Yn,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:n.length})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Yn,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(BI,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(wx,{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(je,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(St,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Et,{className:"text-lg",children:u.team_name}),e.jsxs($e,{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(Ii,{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(Og,{className:"h-3 w-3 text-amber-500"}),u.leader_name]})]})]}),e.jsx(Le,{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 →"})})]})},pRn=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=_s(),o=Zn(),{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:v}=await q.from("brokerages").select("name").eq("id",f).single();if(v)throw v;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(wi,{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(pa,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(ga,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(Xt,{value:"agents",children:"Agents"}),e.jsx(Xt,{value:"teams",children:"Teams"}),e.jsx(Xt,{value:"invite",children:"Invite Links"}),e.jsx(Xt,{value:"referrals",children:"Referrals"}),e.jsx(Xt,{value:"leaderboard",children:"Leaderboard"}),e.jsx(Xt,{value:"activity",children:"Activity"}),e.jsx(Xt,{value:"analytics",children:"Analytics"}),e.jsx(Xt,{value:"shares",children:"Shares"})]}),e.jsx(Qt,{value:"agents",className:"space-y-4",children:e.jsx(rRn,{brokerageId:f})}),e.jsx(Qt,{value:"teams",className:"space-y-4",children:e.jsx(fRn,{brokerageId:f})}),e.jsx(Qt,{value:"invite",className:"space-y-4",children:e.jsx(dRn,{brokerageId:f})}),e.jsx(Qt,{value:"referrals",className:"space-y-4",children:e.jsx(mRn,{})}),e.jsx(Qt,{value:"leaderboard",className:"space-y-4",children:e.jsx(cHt,{brokerageId:f,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(Qt,{value:"activity",className:"space-y-4",children:e.jsx(lRn,{brokerageId:f})}),e.jsx(Qt,{value:"analytics",className:"space-y-4",children:e.jsx(cRn,{brokerageId:f})}),e.jsx(Qt,{value:"shares",className:"space-y-4",children:e.jsx(AWt,{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(wi,{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}=_s(),[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,v]=j.useState(""),[y,b]=j.useState(""),[w,S]=j.useState(!1),A=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]))||[]),Z=U.map(X=>({...X,author:G.get(X.created_by)||{name:"Unknown",avatar_url:null}}));a(Z)}else a([])}catch(D){console.error("Error fetching announcements:",D)}finally{l(!1)}};j.useEffect(()=>{A()},[s]);const E=()=>{v(""),b(""),S(!1),u(null)},I=D=>{D?(u(D),v(D.title),b(D.content),S(D.is_pinned)):E(),c(!0)},P=async()=>{if(!x.trim()||!y.trim()){ne.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:y.trim(),is_pinned:w,pinned_at:w?new Date().toISOString():null}).eq("id",d.id);if(D)throw D;ne.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:y.trim(),is_pinned:w,pinned_at:w?new Date().toISOString():null});if(D)throw D;ne.success("Announcement created")}c(!1),E(),A()}catch(D){console.error("Error saving announcement:",D),ne.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;ne.success("Announcement deleted"),A()}catch(D){console.error("Error deleting announcement:",D),ne.error("Failed to delete announcement")}finally{m(null)}};return i?e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(gm,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(gm,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs($,{size:"sm",onClick:()=>I(),className:"gap-1",children:[e.jsx(cn,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Le,{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(IE,{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(Ii,{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:Js(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(pi,{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(qn,{className:"h-4 w-4"})})]})]})},D.id)})})})]}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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=>v(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:y,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(jn,{id:"pinned",checked:w,onCheckedChange:S}),e.jsxs(ee,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(IE,{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(fc,{open:!!h,onOpenChange:()=>m(null),children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Delete Announcement"}),e.jsx(ic,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:R,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function xRn({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=cLe(),{user:a}=_s(),[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:v}=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(v)throw v;if(l(x||[]),x&&x.length>0){const y=x.map(w=>w.id),{data:b}=await q.from("agent_assistant_assignments").select("agent_id").in("agent_id",y);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,v;return g.name.toLowerCase().includes(d.toLowerCase())||g.email.toLowerCase().includes(d.toLowerCase())||((x=g.title)==null?void 0:x.toLowerCase().includes(d.toLowerCase()))||((v=g.areas_served)==null?void 0:v.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Yn,{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(Le,{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(yRn,{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 yRn({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(Ii,{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($e,{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(ui,{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(ry,{children:[e.jsx(ay,{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(GI,{className:"h-4 w-4"})})}),e.jsxs(vx,{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(pn,{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(ly,{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(Ef,{className:"h-4 w-4"})})})]})]})}function vRn({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 v=f.get(x.user_id);return{user_id:x.user_id,total_points:x.total_points,name:(v==null?void 0:v.name)||"Unknown",avatar_url:(v==null?void 0:v.avatar_url)||null}});n(g)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Kl,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(Le,{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(EE,{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(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Kl,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(Le,{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(Ii,{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 bRn({brokerageId:s}){const t=Zn(),[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(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Et,{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(cn,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Le,{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(cn,{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(Ir,{className:"h-3 w-3 ml-1"})]})]})]})}const _Rn={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 wRn({brokerageId:s,canManage:t}){const{user:n}=_s(),{toast:r}=Bi(),{data:a,isLoading:i}=lsn(s),l=csn(s),[o,c]=j.useState({..._Rn}),[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 lHt(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)}}},v=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"})}},y=(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 A;return((A=S.target.files)==null?void 0:A[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(Ct,{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(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(wi,{className:"h-5 w-5"}),"Brokerage Brand"]}),e.jsx(Vn,{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(Le,{className:"space-y-6",children:i?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Ct,{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:A=>g(b,A.target.value)}),e.jsx(pe,{disabled:!t,value:o[b],placeholder:S,onChange:A=>g(b,A.target.value)})]})]},b))}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[y("logo_url","Logo (light background)"),y("logo_dark_url","Logo (dark background)"),y("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(jn,{disabled:!t,checked:d[b],onCheckedChange:S=>u(A=>({...A,[b]:S}))})]},b))}),t&&e.jsxs($,{onClick:v,disabled:l.isPending,children:[l.isPending?e.jsx(Ct,{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",dE=s=>s.status==="approved"||s.status==="complete";function wXt(s){return st({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 st({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 jXt(s){return st({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(dE).length,overdue:u.filter(h=>!dE(h)&&h.due_date&&h.due_dateh.status==="submitted").length}})}})}function NXt(s){return st({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 NRn(s){return st({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 kRn(s,t){return st({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 SRn(s,t){return st({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 kXt(s,t){return st({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 Zde(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 ZRe(s){const t=Zt(),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=mt({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:v,error:y}=await q.from("brokerage_onboarding_template_steps").select("*").eq("template_id",m).order("sort_order",{ascending:!0});if(y)throw y;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(v!=null&&v.length){const A=new Date,E=v.map(P=>{let R=null;if(P.due_days!=null){const D=new Date(A);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 Zde({brokerageId:s,agentUserId:h,eventType:"onboarding_started",description:`Onboarding started using "${g.name}"`}),b},onSuccess:h=>n(h.agent_user_id,h.id)}),a=mt({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=mt({mutationFn:async({step:h,status:m,note:f,agentUserId:g})=>{var b;const{data:x}=await q.auth.getUser(),v=m==="approved"||m==="complete",{error:y}=await q.from("brokerage_onboarding_steps").update({status:m,review_note:f??null,completed_at:v?new Date().toISOString():null,completed_by:v?((b=x.user)==null?void 0:b.id)??null:null}).eq("id",h.id);if(y)throw y;return s&&await Zde({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=mt({mutationFn:async({step:h,file:m,agentUserId:f,existingVersions:g})=>{var S;const{data:x}=await q.auth.getUser(),v=m.name.replace(/[^a-zA-Z0-9._-]/g,"_"),y=`${s}/${f}/${h.id}/${Date.now()}-${v}`,{error:b}=await q.storage.from(_Xt).upload(y,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:y,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 Zde({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=mt({mutationFn:async({doc:h,step:m,status:f,note:g,agentUserId:x})=>{var w;const{data:v}=await q.auth.getUser(),{error:y}=await q.from("brokerage_onboarding_documents").update({review_status:f,review_note:g??null,reviewed_by:((w=v.user)==null?void 0:w.id)??null,reviewed_at:new Date().toISOString()}).eq("id",h.id);if(y)throw y;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 Zde({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=mt({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=mt({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=mt({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 CRn(s){const t=Zt(),n=d=>{t.invalidateQueries({queryKey:["onboarding-templates",s]}),d&&t.invalidateQueries({queryKey:["onboarding-template-steps",d]})},r=mt({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=mt({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=mt({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=mt({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=mt({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=mt({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 ARn(s){const{data:t,error:n}=await q.storage.from(_Xt).createSignedUrl(s,300);if(n)throw n;return t.signedUrl}const ERn=s=>s==="document"?Qr:s==="form"?l_:qj,TRn=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"}}},fYe=({brokerageId:s,agentUserId:t,steps:n,documents:r,mode:a,displayMode:i="all"})=>{const{toast:l}=Bi(),{setStepStatus:o,uploadDocument:c,reviewDocument:d}=ZRe(s),u=j.useRef({}),[h,m]=j.useState(null),[f,g]=j.useState(""),x=new Date().toISOString().slice(0,10),v=w=>r.filter(S=>S.step_id===w).sort((S,A)=>A.version-S.version),y=async(w,S)=>{try{await c.mutateAsync({step:w,file:S,agentUserId:t,existingVersions:v(w.id).length}),l({title:"Uploaded",description:`${S.name} is ready for review.`})}catch(A){l({title:"Upload failed",description:A.message,variant:"destructive"})}},b=async w=>{try{const S=await ARn(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=ERn(w.step_type),A=TRn(w),E=v(w.id),I=E[0],P=!dE(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(Qr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:D.file_name}),e.jsxs($e,{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(ji,{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&&y(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&&!dE(w)&&e.jsxs($,{size:"sm",onClick:()=>o.mutate({step:w,status:"complete",agentUserId:t}),children:[e.jsx(qj,{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(Vr,{className:"mr-1 h-4 w-4"})," Approve"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{m({step:w,doc:I}),g("")},children:[e.jsx(ju,{className:"mr-1 h-4 w-4"})," Needs changes"]})]}),a==="manager"&&dE(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(Sx,{className:"mr-1 h-4 w-4"})," Revoke"]})]})]})},w.id)}),e.jsx(Os,{open:!!h,onOpenChange:w=>!w&&m(null),children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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(Nr,{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"})]})]})})]})},MRn=()=>{const{user:s}=_s(),{data:t}=NRn(s==null?void 0:s.id),{data:n}=NXt(t==null?void 0:t.id);if(!t)return null;const r=(n==null?void 0:n.steps)||[],a=r.filter(dE).length,i=r.length?Math.round(a/r.length*100):0;return e.jsxs(je,{children:[e.jsx(St,{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(GN,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx(Et,{children:"Your onboarding"}),e.jsx(Vn,{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(Le,{children:e.jsx(fYe,{brokerageId:t.brokerage_id,agentUserId:t.agent_user_id,steps:r,documents:(n==null?void 0:n.documents)||[],mode:"agent"})})]})};function PRn(){const{user:s,isAdmin:t,isBrokerageManager:n}=_s(),r=Zn(),[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:y}=await q.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(y!=null&&y.brokerage_id)){i(!1);return}o(y.brokerage_id);const{data:b}=await q.from("brokerages").select("name").eq("id",y.brokerage_id).maybeSingle();b&&d(b.name);const{count:w}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",y.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",y.brokerage_id).maybeSingle();f(!!S),x(!!S)}}catch(y){console.error("Error fetching brokerage info:",y)}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(Yn,{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(_x,{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(MRn,{}),e.jsx(wRn,{brokerageId:l,canManage:m}),e.jsx(gRn,{brokerageId:l,canManage:m}),e.jsx(xRn,{brokerageId:l,canManage:m}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(vRn,{brokerageId:l}),e.jsx(bRn,{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(wi,{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 IRn(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 LRn(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 Vkt={video:{icon:Ou,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Qr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:nu,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:Ea,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:yd,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function RRn({item:s,canManage:t}){const[n,r]=j.useState(!1),[a,i]=j.useState(null),l=rWs(),o=Zn(),c=Vkt[s.content_type]||Vkt.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"?IRn(s.url):null,[s]);j.useEffect(()=>{u||!s.url||s.content_type!=="video"||!LRn(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),ne.success("Content deleted")}catch{ne.error("Failed to delete")}r(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(je,{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(Le,{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($e,{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($e,{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:["📅 ",Js(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",Js(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,onClick:g=>g.stopPropagation(),children:e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsx(Cu,{align:"end",children:e.jsxs(ja,{onClick:g=>{g.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(qn,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(fc,{open:n,onOpenChange:r,children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Delete Content"}),e.jsxs(ic,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:f,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function DRn(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 Hkt=[{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 FRn({brokerageId:s,categories:t}){var J;const{user:n}=_s(),[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,v]=j.useState(""),[y,b]=j.useState(""),[w,S]=j.useState(""),[A,E]=j.useState(""),[I,P]=j.useState(""),[R,D]=j.useState(""),[O,U]=j.useState(""),W=nWs(),V=aWs(s),G=iWs(),Z=oWs(s),X=()=>{g("video"),v(""),b(""),S(""),E(""),P(""),D(""),U("")},ae=async(ce,ve)=>{var ue;const fe=(ue=ce.target.files)==null?void 0:ue[0];if(fe){m(!0);try{const be=fe.name.split(".").pop(),Ee=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${be}`,{error:ke}=await q.storage.from("brokerage-content").upload(Ee,fe);if(ke)throw ke;const{data:{publicUrl:Ie}}=q.storage.from("brokerage-content").getPublicUrl(Ee);ve==="file"?(E(Ie),f==="graphic"&&!I&&P(Ie)):P(Ie),ne.success("File uploaded")}catch(be){ne.error(be.message||"Upload failed")}finally{m(!1)}}},le=async()=>{if(!x.trim()){ne.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:y.trim()||null,url:w.trim()||null,file_url:A.trim()||null,thumbnail_url:I.trim()||null,event_date:R?new Date(R).toISOString():null,created_by:n.id}),ne.success("Content added!"),X(),a(!1)}catch(ce){ne.error(ce.message||"Failed to add content")}},re=async()=>{if(o.trim())try{await V.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),ne.success("Category created")}catch(ce){ne.error(ce.message||"Failed to create category")}},te=async()=>{try{await Z.mutateAsync(),ne.success("Default categories created")}catch{ne.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Os,{open:r,onOpenChange:a,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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:Hkt.map(ce=>e.jsx(Ge,{value:ce.value,children:ce.label},ce.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(J=Hkt.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=>v(ce.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{value:y,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 ve=ce.target.value;if(S(ve),f==="video"&&!I){const fe=DRn(ve);fe&&P(fe)}},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(Ct,{className:"h-4 w-4 animate-spin"})]}),A&&e.jsx("p",{className:"text-xs text-green-600",children:"✓ File uploaded"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(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(mr,{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:le,disabled:W.isPending||!x.trim(),className:"w-full",children:[W.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(Os,{open:i,onOpenChange:l,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",children:[e.jsx(Nd,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{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:Z.isPending,children:[Z.isPending?e.jsx(Ct,{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),ne.success("Category deleted")},children:e.jsx(mr,{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"&&re()}),e.jsx($,{size:"sm",onClick:re,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function ORn(){const{user:s,isAdmin:t,isBrokerageManager:n}=_s(),[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:A}=await q.from("brokerages").select("name").eq("id",S.brokerage_id).maybeSingle();if(A&&c(A.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=[]}=eWs(i),{data:v=[],isLoading:y}=tWs(i,h),b=j.useMemo(()=>{if(!f.trim())return v;const w=f.toLowerCase();return v.filter(S=>{var A;return S.title.toLowerCase().includes(w)||((A=S.description)==null?void 0:A.toLowerCase().includes(w))||S.content_type.toLowerCase().includes(w)})},[v,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(FRn,{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))]})]}),y?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(je,{className:"bg-muted/30 border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Nv,{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(RRn,{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(wi,{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 Gkt={video:{icon:Ou,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Qr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:nu,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:Ea,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:yd,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function zRn(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 BRn(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function $Rn(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function URn(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function qRn(){const{contentId:s}=Wi(),{data:t,isLoading:n}=st({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(wi,{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(br,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=Gkt[t.content_type]||Gkt.link,a=r.icon,i=t.url||t.file_url,l=i&&BRn(i)?zRn(i):null,o=i&&$Rn(i)?URn(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(br,{to:"/brokerage-content",children:[e.jsx(Va,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($e,{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($e,{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 ",Js(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(je,{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(je,{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(je,{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(je,{children:e.jsx(Le,{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(je,{children:e.jsxs(Le,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Ea,{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:Js(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(ji,{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(Ir,{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 HMe={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 VRn(s="open"){const{user:t}=_s();return st({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 HRn(s){return st({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 GRn(s){return st({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 WRn(){const s=Zt(),{user:t,brokerageId:n}=_s();return mt({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 KRn(){const s=Zt(),{user:t}=_s();return mt({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 YRn(){const s=Zt();return mt({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 ZRn(){const s=Zt();return mt({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 XRn(){const s=Zt();return mt({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 QRn(){const s=Zt();return mt({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 JRn(){const{user:s,brokerageId:t}=_s(),n=Zt(),r=st({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=mt({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 eDn(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 tDn(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 sDn({req:s,onClick:t}){var i;const n=HMe[s.request_type],r=eDn(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(je,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Le,{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($e,{variant:"secondary",className:"text-xs",children:[n.emoji," ",n.label]}),s.status!=="open"&&e.jsx($e,{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(ca,{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(ui,{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(su,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:tDn(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 nDn(){var c;const s=Zn(),{brokerageId:t}=_s(),[n,r]=j.useState("open"),{data:a=[],isLoading:i}=VRn(n),l=JRn(),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(pa,{value:n,onValueChange:d=>r(d),children:e.jsxs(ga,{children:[e.jsx(Xt,{value:"open",children:"Open"}),e.jsx(Xt,{value:"mine",children:"My Posts"}),e.jsx(Xt,{value:"my_claims",children:"My Claims"}),e.jsx(Xt,{value:"filled",children:"Filled"})]})}),e.jsxs($,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(cn,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(je,{className:"bg-muted/30 border-dashed",children:e.jsxs(Le,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(zy,{className:"h-4 w-4 text-primary"}):e.jsx(KS,{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(jn,{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(je,{className:"bg-muted/30 border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(t4,{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(sDn,{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(t4,{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 rDn(){const s=Zn(),{toast:t}=Bi(),n=WRn(),[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,v]=j.useState(""),[y,b]=j.useState(""),[w,S]=j.useState(""),[A,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",Z=r!=="general",X=(le,re)=>!le||!re?null:`${le}T${re}:00`,ae=async le=>{if(le.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const re=X(d,h),te=X(d,f);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:re,event_end_at:te,address:G&&x.trim()||null,city:G&&y.trim()||null,state:G&&w.trim()||null,zip:G&&A.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(re){t({title:"Could not post",description:(re==null?void 0:re.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(Va,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:ae,children:e.jsx(je,{children:e.jsxs(Le,{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(HMe).map(le=>{const re=HMe[le],te=le===r;return e.jsxs("button",{type:"button",onClick:()=>a(le),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:re.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:re.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:re.description})]},le)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:i,onChange:le=>l(le.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:le=>c(le.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),Z&&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:le=>u(le.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:le=>m(le.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:le=>g(le.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:le=>v(le.target.value),placeholder:"123 Oak St"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:y,onChange:le=>b(le.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:le=>S(le.target.value.toUpperCase()),maxLength:2})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"zip",children:"Zip"}),e.jsx(pe,{id:"zip",value:A,onChange:le=>E(le.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:le=>P(le.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(le=>{const re=R===le.val;return e.jsxs("button",{type:"button",onClick:()=>D(le.val),className:`text-left p-3 rounded-lg border-2 transition ${re?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:le.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:le.sub})]},le.val)})}),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:le=>U(le.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:le=>V(le.target.value),placeholder:"e.g. Venmo same day, or split any leads",maxLength:200})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{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(Ct,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function aDn(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 S9e(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function iDn(){var I,P,R,D,O,U,W,V;const{id:s}=Wi(),t=Zn(),{user:n}=_s(),{toast:r}=Bi(),{data:a,isLoading:i}=HRn(s),{data:l=[]}=GRn(s),o=KRn(),c=YRn(),d=ZRn(),u=XRn(),h=QRn(),[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(Ct,{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(Va,{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=HMe[a.request_type],x=aDn(a.event_start_at,a.event_end_at),v=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),y=(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",A=a.compensation_type==="flat_fee"?a.compensation_amount?`$${Number(a.compensation_amount).toFixed(0)} flat fee`:"Flat fee":a.compensation_type==="referral_percent"?a.compensation_amount?`${a.compensation_amount}% referral`:"Referral percentage":"Goodwill (paying it forward)",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(Va,{className:"h-4 w-4"})," Back to board"]}),e.jsx(je,{children:e.jsxs(Le,{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($e,{variant:"secondary",children:[g.emoji," ",g.label]}),e.jsx($e,{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(Ii,{src:((I=a.requester)==null?void 0:I.avatar_url)||void 0}),e.jsx(za,{children:S9e((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(ca,{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})]})]}),v&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ui,{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:v})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(su,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Compensation"}),e.jsx("div",{children:A})]})]}),a.mls_number&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(qI,{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]})]})}),!y&&S&&!b&&e.jsx(je,{children:e.jsxs(Le,{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(Ct,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!y&&b&&e.jsx(je,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx(ma,{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&&(y||w.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(je,{className:"border-primary/30",children:e.jsxs(Le,{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(Ii,{src:((D=w.claimant)==null?void 0:D.avatar_url)||void 0}),e.jsx(za,{children:S9e((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(pn,{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]})]})]})}),y&&e.jsx(je,{children:e.jsxs(Le,{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 Z,X,ae,le,re;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(Ii,{src:((Z=G.claimant)==null?void 0:Z.avatar_url)||void 0}),e.jsx(za,{children:S9e((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($e,{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(ma,{className:"h-3.5 w-3.5"})," Pick ",((re=(le=G.claimant)==null?void 0:le.name)==null?void 0:re.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(mr,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},G.id)}),y&&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"})}),y&&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 SXt({onSelect:s,maxHeight:t="460px"}){const[n,r]=j.useState(""),[a,i]=j.useState("all"),{data:l=[],isLoading:o}=st({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(go,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{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(Hc,{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($e,{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(ei,{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 oDn=[{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:pn,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:Ea,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:su,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:ui,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:Hd,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:Pm,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function Wkt(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function lDn(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function Uat({html:s,onChange:t}){const{user:n}=_s(),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),v=()=>{var jt;const Ft=(jt=r.current)==null?void 0:jt.contentDocument,is=Ft==null?void 0:Ft.getSelection();is&&is.rangeCount>0&&(Ft!=null&&Ft.body.contains(is.anchorNode))&&(x.current=is.getRangeAt(0).cloneRange())},y=()=>{var gs;const Ft=c.current,is=(gs=r.current)==null?void 0:gs.contentDocument;if(!Ft||!is)return;let jt=h.trim();jt&&!/^(https?:|mailto:|tel:|#|\/)/i.test(jt)&&(jt="https://"+jt),Ft.setAttribute("href",jt),Ft.setAttribute("target","_blank");const zs=f.trim();zs&&zs!==(Ft.textContent||"").trim()&&(Ft.textContent=zs);const yt=` `+is.documentElement.outerHTML;a.current=yt,i.current(yt),u(!1)};j.useEffect(()=>{var jt,zs;const Ft=r.current;if(!Ft||a.current===s)return;const is=()=>{const yt=Ft.contentDocument;if(!yt)return;yt.open(),yt.write(s||""),yt.close(),a.current=s;const gs=yt.body;if(!gs)return;gs.setAttribute("contenteditable","true"),gs.style.outline="none",gs.style.minHeight="400px",gs.style.cursor="text";const Ss=()=>{const Bt=` `+yt.documentElement.outerHTML;a.current=Bt,i.current(Bt)};gs.addEventListener("input",Ss),gs.addEventListener("blur",Ss),gs.addEventListener("mouseup",v),gs.addEventListener("keyup",v),yt.addEventListener("selectionchange",v);const Ds=Bt=>{var Rr;const zt=Bt.target,vs=zt==null?void 0:zt.closest("a");if(vs){if(Bt.metaKey||Bt.ctrlKey||Bt.shiftKey)return;Bt.preventDefault(),Bt.stopPropagation(),c.current=vs,m(vs.getAttribute("href")||""),g((vs.textContent||"").trim()),u(!0);return}const dn=yt.getSelection();if(!dn)return;const Ks=(Rr=yt.caretRangeFromPoint)==null?void 0:Rr.call(yt,Bt.clientX,Bt.clientY),Cn=Ks==null?void 0:Ks.startContainer;if(Cn&&Cn.nodeType===Node.TEXT_NODE){const ia=Cn.textContent||"",Hs=Ks.startOffset,Br=ia.lastIndexOf("[",Hs),Ur=ia.indexOf("]",Hs);if(Br!==-1&&Ur!==-1&&Ur>Br){const Wn=yt.createRange();Wn.setStart(Cn,Br),Wn.setEnd(Cn,Ur+1),dn.removeAllRanges(),dn.addRange(Wn),x.current=Wn.cloneRange()}}};gs.addEventListener("click",Ds,!0)};((jt=Ft.contentDocument)==null?void 0:jt.readyState)==="complete"||(zs=Ft.contentDocument)!=null&&zs.body?is():Ft.addEventListener("load",is,{once:!0})},[s]);const b=(Ft,is)=>{var yt;const jt=(yt=r.current)==null?void 0:yt.contentDocument;if(!jt)return;jt.body.focus(),jt.execCommand(Ft,!1,is);const zs=` `+jt.documentElement.outerHTML;a.current=zs,i.current(zs)},w=()=>{const Ft=window.prompt("Enter URL (https://...)");Ft&&b("createLink",Ft)},S=(Ft,is)=>{var yt;const jt=(yt=r.current)==null?void 0:yt.contentDocument;if(!jt)return;if(jt.body.focus(),is==="cursor"&&x.current&&jt.body.contains(x.current.startContainer)){const gs=jt.getSelection();if(gs){gs.removeAllRanges(),gs.addRange(x.current),jt.execCommand("insertHTML",!1,Ft);const Ss=` `+jt.documentElement.outerHTML;a.current=Ss,i.current(Ss);return}}is==="top"?jt.body.insertAdjacentHTML("afterbegin",Ft):jt.body.insertAdjacentHTML("beforeend",Ft);const zs=` `+jt.documentElement.outerHTML;a.current=zs,i.current(zs)},[A,E]=j.useState(!1),[I,P]=j.useState(null),[R,D]=j.useState(""),[O,U]=j.useState(""),[W,V]=j.useState("#406E71"),[G,Z]=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 is=Ft;if(I.isForward){const gs=Ft||"",Ss=encodeURIComponent("You should see this newsletter"),Ds=encodeURIComponent(gs?`I thought you'd like this — take a look: ${gs} `:`I thought you'd like this newsletter — take a look! `);is=`mailto:?subject=${Ss}&body=${Ds}`}else I.hrefPrefix==="tel:"?is="tel:"+Ft.replace(/[^0-9+]/g,""):I.hrefPrefix==="mailto:"?is="mailto:"+Ft:/^https?:\/\//i.test(Ft)||(is="https://"+Ft);const jt=(R||I.defaultText).replace(/[<>]/g,""),zs=W||"#406E71",yt=`
${jt}

 

`;S(yt,G),E(!1)},[le,re]=j.useState(!1),[te,J]=j.useState(""),[ce,ve]=j.useState(""),[fe,ue]=j.useState(""),[be,Ee]=j.useState("cursor"),ke=(()=>{if(ce.trim())return ce.trim();const Ft=Wkt(te);return Ft?`https://i.ytimg.com/vi/${Ft}/hqdefault.jpg`:""})(),Ie=()=>{J(""),ve(""),ue(""),re(!0)},Fe=()=>{const Ft=te.trim();if(!Ft)return;let is=Ft;/^https?:\/\//i.test(is)||(is="https://"+is);const jt=Wkt(is),zs=jt?null:lDn(is);let yt=ce.trim();!yt&&jt&&(yt=`https://i.ytimg.com/vi/${jt}/hqdefault.jpg`),!yt&&zs&&(yt=`https://vumbnail.com/${zs}.jpg`),yt||(yt="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const gs=(fe||"Watch the video").replace(/[<>]/g,""),Ss=`
${gs}
▶
▶ ${gs}

 

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

 

`.trim();S(jt,ht),Be(!1)},{data:es,isLoading:Ht}=st({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&le,queryFn:async()=>{const{data:Ft,error:is}=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(is)throw is;return Ft||[]}}),as=Ft=>{Ft.share_token&&(J(`https://video.relevelup.com/share/video/${Ft.share_token}`),ve(`https://video.relevelup.com/thumb/${Ft.share_token}`),ue(Ft.title||"Watch the video"))},bs=l==="mobile"?390:"100%",Ut=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(kE,{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(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("underline"),title:"Underline",children:e.jsx(Jz,{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(E0,{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(c2,{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(Sd,{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(FE,{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(RE,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(Bu,{children:[e.jsx($u,{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(Pm,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(Cu,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(_L,{children:"Insert a call-to-action"}),e.jsx(P0,{}),oDn.map(Ft=>{const is=Ft.icon;return e.jsxs(ja,{onClick:()=>X(Ft),children:[e.jsx(is,{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:Je,children:[e.jsx(Hc,{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:Ie,children:[e.jsx(fa,{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(jV,{type:"single",value:l,onValueChange:Ft=>Ft&&o(Ft),size:"sm",className:"h-7",children:[e.jsx(f7,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(ZN,{className:"h-3.5 w-3.5"})}),e.jsx(f7,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(g1,{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(Pm,{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:bs,maxWidth:Ut,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(Os,{open:d,onOpenChange:u,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{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(Nr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:y,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(Os,{open:A,onOpenChange:E,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsxs($s,{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(yw,{value:G,onValueChange:Ft=>Z(Ft),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Km,{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(Pm,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Km,{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(Km,{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(Lg,{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(Nr,{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(Os,{open:le,onOpenChange:re,children:e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{children:"Insert Video Block"})}),e.jsxs(pa,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(ga,{className:"grid w-full grid-cols-3",children:[e.jsx(Xt,{value:"library",children:"My Library"}),e.jsx(Xt,{value:"url",children:"From URL"}),e.jsx(Xt,{value:"record",children:"Record New"})]}),e.jsxs(Qt,{value:"library",className:"space-y-3 mt-2",children:[Ht?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!es||es.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(fa,{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:es.map(Ft=>{const is=te.includes(Ft.share_token||"___"),jt=Ft.share_token?`https://video.relevelup.com/thumb/${Ft.share_token}`:Ft.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>as(Ft),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${is?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[jt?e.jsx("img",{src:jt,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(fa,{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(Ou,{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:fe,onChange:Ft=>ue(Ft.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(Qt,{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:fe,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=>ve(Ft.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(Qt,{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(fa,{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(yw,{value:be,onValueChange:Ft=>Ee(Ft),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Km,{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(Pm,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Km,{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(Km,{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(Lg,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),ke&&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:ke,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(Nr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>re(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:Fe,disabled:!te.trim(),children:"Insert Video"})]})]})}),e.jsx(Os,{open:Ne,onOpenChange:Be,children:e.jsxs(Fs,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{children:"Insert Image"})}),e.jsxs(pa,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(ga,{className:"grid w-full grid-cols-3",children:[e.jsx(Xt,{value:"library",children:"Library"}),e.jsx(Xt,{value:"upload",children:"Upload"}),e.jsx(Xt,{value:"url",children:"From URL"})]}),e.jsx(Qt,{value:"library",className:"mt-2",children:e.jsx(SXt,{maxHeight:"380px",onSelect:Ft=>{Ae(Ft.image_url),Ce||qe(Ft.title)}})}),e.jsxs(Qt,{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 jt;const is=(jt=Ft.target.files)==null?void 0:jt[0];is&&ft(is),Ft.target.value=""}}),Se?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:Se,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:at,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:at?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{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(Qt,{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:Se,onChange:Ft=>Ae(Ft.target.value),placeholder:"https://..."})]}),Se&&/^https?:\/\//i.test(Se)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:Se,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(yw,{value:ze,onValueChange:Ft=>Ve(Ft),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Km,{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(Km,{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(yw,{value:ht,onValueChange:Ft=>Qe(Ft),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Km,{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(Pm,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Km,{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(Km,{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(Lg,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(Nr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>Be(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:gt,disabled:!Se.trim()||at,children:"Insert Image"})]})]})})]})}const Kkt="newsletter-content",cDn="inline-images";function dDn(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}}),A=(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)??mDn()),x((n==null?void 0:n.is_template)??!1),y((n==null?void 0:n.share_scope)??"private"))},[s,n]);const I=async()=>{if(a){if(!c.trim()){ne.error("Please enter a title");return}if(!m.trim()){ne.error("Newsletter content is empty");return}w(!0);try{const P=await uDn(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:v,shared_team_id:v==="team"?E:null,shared_brokerage_id:v==="brokerage"?o:null};if(v==="team"&&!E){ne.error("You must be a team leader to share with a team"),w(!1);return}if(v==="brokerage"&&!l){ne.error("Only brokerage managers can share to a brokerage"),w(!1);return}if(v==="global"&&!i){ne.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;ne.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(P){ne.error(P.message||"Failed to save")}finally{w(!1)}}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{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($s,{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(jn,{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"})]}),(A||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(yw,{value:v,onValueChange:P=>y(P),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Km,{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"})]})]}),A&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Km,{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(Km,{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(Km,{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(Uat,{html:m,onChange:f})]})]}),e.jsxs(Nr,{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(Ct,{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 mDn(){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 qat=/\[[^\]\[<>]{2,80}\]/g,fDn=/^\[\s*(?:\/?\s*if\b[^\]]*|endif|else|x-apple-[\w-]*|data-[\w-]*|object [^\]]*|cdata[^\]]*)\s*\]$/i;function Vat(s){return!fDn.test(s)}function pDn(s){return(s.match(qat)||[]).filter(Vat)}function Ykt(s){const t=s.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function gDn(s){const t=[],n=new RegExp(qat.source,"g");let r;for(;(r=n.exec(s))!==null;)Vat(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 · ${Ykt(h)}`:`Date ${i[l.token]}`:(m=Ykt(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 xDn({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 y=new RegExp(qat.source,"g");let b=0;const w=s.replace(y,S=>{if(!Vat(S))return S;const A=(a[b]||"").trim();return b+=1,A||S});w!==s&&(o(S=>[...S,{html:s,values:a}]),d.current=!0,i({}),t(w))},h=()=>{const y=l[l.length-1];y&&(o(b=>b.slice(0,-1)),d.current=!0,i(y.values),t(y.html))},m=()=>{const y=c.current;!y||y===s||(o([]),d.current=!0,i({}),t(y))},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(see,{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(Sx,{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(Vr,{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 v=r.filter(y=>(a[y.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(Al,{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($e,{variant:"secondary",className:"shrink-0",children:[v,"/",r.length," ready"]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-4",children:r.map(y=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:y.label}),e.jsx(pe,{value:a[y.index]||"",placeholder:y.hint,className:"h-10 text-sm",onChange:b=>i(w=>({...w,[y.index]:b.target.value})),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),u())}})]},y.index))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{type:"button",size:"sm",onClick:u,children:[e.jsx(Vq,{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 QB(){const s=Sa();return st({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 yDn(s){return st({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 Hat(){const s=Zt(),t=Sa();return mt({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 vDn(){const s=Zt();return mt({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 bDn(){const s=Zt();return mt({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 CXt(){const s=Zt();return mt({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 _Dn(){const s=Zt();return mt({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 Aie(){const s=Sa();return st({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 Gat(){const{user:s}=_s();return st({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 AXt(){const s=Zt(),{user:t}=_s();return mt({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 EXt(){const s=Zt();return mt({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 Zkt=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function Xkt(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 wDn(s,t,n,r){const a=t.trim()?`
${Zkt(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${Zkt(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 NDn=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function kDn(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=NDn.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 Wat({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=_s();Gy();const{isReady:l,settings:o}=FB(),{data:c}=eie(),[d,u]=j.useState(!1),h=Sa(),{data:m}=st({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:bn}=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 bn}}),[f,g]=j.useState("visual"),[x,v]=j.useState("all"),[y,b]=j.useState(""),[w,S]=j.useState(""),[A,E]=j.useState(""),[I,P]=j.useState(""),[R,D]=j.useState(!0),[O,U]=j.useState([]),[W,V]=j.useState(null),[G,Z]=j.useState(new Set),[X,ae]=j.useState(""),[le,re]=j.useState(!1),[te,J]=j.useState(!1),[ce,ve]=j.useState(!1),[fe,ue]=j.useState({sent:0,failed:0,total:0,currentName:""}),[be,Ee]=j.useState(!0),[ke,Ie]=j.useState(!1),[Fe,Ne]=j.useState([]),[Be,Se]=j.useState(!1),[Ae,Ce]=j.useState(new Set),[qe,ze]=j.useState("now"),[Ve,ht]=j.useState(""),{data:Qe=[]}=QB(),{data:at=[]}=Aie(),{data:rt=[]}=Gat(),{data:Ke=[],isLoading:Je}=st({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const bn=[];let xs=0;const Tr=1e3;for(;;){const{data:Lr,error:la}=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+Tr-1);if(la)throw la;if(!Lr||Lr.length===0||(bn.push(...Lr),Lr.length{const{data:bn}=await q.from("ses_suppressed_emails").select("email");return(bn||[]).map(xs=>xs.email.toLowerCase())}}),{data:gt}=st({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:bn}=await q.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(bn!=null&&bn.brokerage_id))return null;const{data:xs}=await q.from("brokerages").select("name, city, state").eq("id",bn.brokerage_id).maybeSingle();return xs}}),{data:es}=st({queryKey:["newsletter-active-lead-site",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!h)return null;const{data:bn}=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 bn}}),Ht=!!(es!=null&&es.mls_provider_id),as=(es==null?void 0:es.mls_agent_id)||(es==null?void 0:es.mls_agent_key)||null,{data:bs=[],isLoading:Ut}=st({queryKey:["newsletter-agent-listings",h,as],enabled:!!h&&!!as&&Be,staleTime:60*1e3,queryFn:async()=>{if(!as)return[];const{data:bn}=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",as).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return bn||[]}}),{data:Ft=[],isLoading:is}=st({queryKey:["newsletter-exchange-listings",h],enabled:!!h&&Be,staleTime:60*1e3,queryFn:async()=>{const{data:bn}=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=bn||[];if(xs.length===0)return[];const Tr=xs.map(wr=>wr.id),{data:Lr}=await q.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",Tr),la=new Map,Xn=new Map;for(const wr of Lr||[])wr.is_primary&&!la.has(wr.listing_id)&&la.set(wr.listing_id,wr.photo_url),Xn.has(wr.listing_id)||Xn.set(wr.listing_id,wr.photo_url);return xs.map(wr=>({...wr,_photo:la.get(wr.id)||Xn.get(wr.id)||""}))}}),{data:jt=!1}=st({queryKey:["newsletter-exchange-listings-exists",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:bn}=await q.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]);return(bn||0)>0}}),zs=j.useMemo(()=>{const bn=new Set(ft);return Ke.filter(xs=>xs.email&&xs.email.includes("@")&&!bn.has(xs.email.toLowerCase()))},[Ke,ft]),yt=j.useMemo(()=>{if(O.length===0)return null;const bn=new Set;for(const xs of at)O.includes(xs.tag_id)&&bn.add(xs.contact_id);return bn},[at,O]),gs=j.useMemo(()=>rt.find(bn=>bn.id===W)||null,[rt,W]),Ss=j.useMemo(()=>{var bn;if(x==="all")return zs;if(x==="tags")return yt?zs.filter(xs=>yt.has(xs.id)):[];if(x==="smartlists"){if(!gs)return[];const xs=(((bn=gs.filters)==null?void 0:bn.search)||"").toLowerCase().trim();return xs?zs.filter(Tr=>`${Tr.first_name||""} ${Tr.last_name||""}`.toLowerCase().includes(xs)||(Tr.email||"").toLowerCase().includes(xs)):zs}return zs.filter(xs=>G.has(xs.id))},[x,zs,yt,gs,G]),Ds=j.useMemo(()=>{if(!X.trim())return zs;const bn=X.toLowerCase();return zs.filter(xs=>`${xs.first_name||""} ${xs.last_name||""}`.toLowerCase().includes(bn))},[zs,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"),v("all"),U([]),V(null),Z(new Set),ae(""),re(!1),D(!0),Ee(!0),Ne([]),ze("now"),ht(""),ue({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const Bt=l,zt=j.useMemo(()=>pDn(I||a||""),[I,a]),vs=!!(y.trim()&&Bt&&Ss.length>0&&!te&&zt.length===0),dn=bn=>{const xs=I||a,Tr=R&&(m!=null&&m.email_signature)?m.email_signature:null;let Lr;return f==="light"?Lr=wDn(xs,w,A,Tr):Lr=Tr?`${xs}
${Tr}
`:xs,be&&(Lr+=jDn(m??null,gt??null,bn.email)),Xkt(Lr,bn,m??null,(gt==null?void 0:gt.name)??null)},Ks=j.useMemo(()=>dn({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[f,w,A,I,a,R,m,be,gt]),Cn=j.useMemo(()=>kDn(y,f==="advanced"||f==="visual"?I:a),[y,f,I,a]),Rr=async()=>{Ie(!0),Ne([]);try{const bn=f==="advanced"||f==="visual"?I:a,{data:xs,error:Tr}=await q.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:bn,currentSubject:y}});if(Tr)throw Tr;const Lr=xs==null?void 0:xs.subjects;if(!Array.isArray(Lr)||Lr.length===0)throw new Error("No subjects returned");Ne(Lr)}catch(bn){const xs=(bn==null?void 0:bn.message)||"Failed to generate subjects";xs.includes("credits exhausted")||xs.includes("402")?ne.error("AI credits exhausted. Please add credits to your workspace."):xs.includes("Rate limit")||xs.includes("429")?ne.error("Rate limit hit — try again in a moment."):ne.error(xs)}finally{Ie(!1)}},ia=bn=>bn?"$"+Number(bn).toLocaleString("en-US"):"",Hs=()=>{var Xn,wr;if(Ae.size===0){ne.error("Pick at least one listing first.");return}const bn=(es==null?void 0:es.subdomain_slug)||"",xs=bn?`https://${bn}.relevelup.com`:"https://relevelup.com",Tr=[];for(const Bn of bs){const cr=`mls:${Bn.listing_key}`;if(!Ae.has(cr))continue;const Pa=Array.isArray(Bn.photos)&&Bn.photos.length>0?typeof Bn.photos[0]=="string"?Bn.photos[0]:((Xn=Bn.photos[0])==null?void 0:Xn.MediaURL)||((wr=Bn.photos[0])==null?void 0:wr.url)||"":"",ii=Bn.bedrooms?`${Bn.bedrooms} bd`:"",$i=Bn.bathrooms_total?`${Bn.bathrooms_total} ba`:"",Ln=Bn.living_area?`${Number(Bn.living_area).toLocaleString()} sqft`:"";Tr.push({url:`${xs}/listings/${Bn.listing_key}`,photo:Pa,price:ia(Bn.list_price),addr:`${Bn.address||""}${Bn.city?", "+Bn.city:""}`,stats:[ii,$i,Ln].filter(Boolean).join(" • ")})}for(const Bn of Ft){const cr=`ex:${Bn.id}`;if(!Ae.has(cr))continue;const Pa=Bn.bedrooms?`${Bn.bedrooms} bd`:"",ii=Bn.bathrooms?`${Bn.bathrooms} ba`:"",$i=Bn.square_footage?`${Number(Bn.square_footage).toLocaleString()} sqft`:"";Tr.push({url:`https://listings.relevelup.com/${Bn.slug||Bn.id}`,photo:Bn._photo||"",price:ia(Bn.price),addr:`${Bn.property_address||""}${Bn.city?", "+Bn.city:""}`,stats:[Pa,ii,$i].filter(Boolean).join(" • ")})}const la=`

Featured Listings

${Tr.map(Bn=>`
${Bn.photo?`${Bn.addr}`:""}
${Bn.price}
${Bn.addr}
${Bn.stats}
`.trim()).join(` `)}
`.trim();P(Bn=>(Bn||a||"")+` `+la),g("visual"),Ce(new Set),Se(!1),ne.success(`Added ${Tr.length} listing${Tr.length===1?"":"s"} to your newsletter.`)},Br=()=>dn({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}}"),Ur=()=>Xkt(y,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},m??null,(gt==null?void 0:gt.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}}"),Wn=()=>{if(zt.length>0){ne.error(`Fill in ${zt.length} template field${zt.length===1?"":"s"} before sending.`);return}if(vs){if(qe==="later"){if(!Ve){ne.error("Pick a date and time to schedule.");return}const bn=new Date(Ve).getTime();if(Number.isNaN(bn)||bn{if(!(!vs||!i)){ve(!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`,Tr=Br(),Lr=Ur(),la=qe==="later",{data:Xn,error:wr}=await q.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:Lr,body_html:Tr,from_email:xs,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:Ss.length,status:la?"scheduled":"draft",scheduled_at:la?new Date(Ve).toISOString():null}).select("id").single();if(wr)throw wr;ue(cr=>({...cr,currentName:"Adding recipients…"}));const Bn=Ss.map(cr=>({campaign_id:Xn.id,contact_id:cr.id,email:cr.email,name:[cr.first_name,cr.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let cr=0;cr({...$i,sent:Math.min(cr+Pa.length,Bn.length)}))}if(la){const{error:cr}=await q.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:Xn.id}});if(cr)throw cr;ne.success(`Newsletter scheduled for ${new Date(Ve).toLocaleString()}.`)}else{const{error:cr}=await q.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:Xn.id}});if(cr)throw cr;ne.success(`Sending to ${Ss.length} contact${Ss.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(bn){console.error("Newsletter send failed:",bn),ne.error(`Failed to send: ${bn.message||"Unknown error"}`)}finally{J(!1)}}},Fn=bn=>{Z(xs=>{const Tr=new Set(xs);return Tr.has(bn)?Tr.delete(bn):Tr.add(bn),Tr})};return e.jsxs(Os,{open:s,onOpenChange:bn=>!te&&t(bn),children:[e.jsxs(Fs,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5"})," Send Newsletter"]})}),!Bt&&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(vl,{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:Rr,disabled:ke,title:"Generate subject lines with AI",children:[ke?e.jsx(Ct,{className:"h-3 w-3 animate-spin"}):e.jsx(wn,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(pe,{value:y,onChange:bn=>b(bn.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((bn,xs)=>e.jsxs("button",{type:"button",onClick:()=>{b(bn),Ne([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(wn,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),bn]},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}}"})]})]}),Cn.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(Qq,{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:Cn.map((bn,xs)=>e.jsx("li",{children:bn},xs))})]}),(Ht||jt)&&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:Ht&&jt?"Pick from your live MLS listings or your Listing Exchange listings.":Ht?"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:()=>Se(!0),children:"Choose listings"})]}),e.jsx(xDn,{html:I||a||"",originalHtml:a||"",onChange:P}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Editing"}),e.jsxs(pa,{value:f,onValueChange:bn=>g(bn),children:[e.jsxs(ga,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Xt,{value:"visual",children:[e.jsx(Qx,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Xt,{value:"light",children:[e.jsx(Qr,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(Xt,{value:"advanced",children:[e.jsx(e4,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(Qt,{value:"visual",className:"mt-3",children:e.jsx(Uat,{html:I,onChange:P})}),e.jsxs(Qt,{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:bn=>S(bn.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:A,onChange:bn=>E(bn.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(Qt,{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:bn=>P(bn.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(jn,{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(jn,{checked:be,onCheckedChange:Ee})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Recipients"}),e.jsxs(pa,{value:x,onValueChange:bn=>v(bn),children:[e.jsxs(ga,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Xt,{value:"all",children:[e.jsx(Yn,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(Xt,{value:"tags",children:[e.jsx(Cp,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(Xt,{value:"smartlists",children:[e.jsx(EJ,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(Xt,{value:"individual",children:[e.jsx(sl,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(Qt,{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:zs.length})," contact",zs.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(Qt,{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(go,{className:"h-40 rounded-lg border p-2",children:Qe.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No tags yet. Add tags to contacts to use this option."}):Qe.map(bn=>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(bn.id),onCheckedChange:xs=>U(Tr=>xs?[...Tr,bn.id]:Tr.filter(Lr=>Lr!==bn.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:bn.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:bn.name})]},bn.id))})]}),e.jsxs(Qt,{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(go,{className:"h-40 rounded-lg border p-2",children:rt.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):rt.map(bn=>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===bn.id,onChange:()=>V(bn.id)}),e.jsx("span",{className:"text-sm",children:bn.name})]},bn.id))})]}),e.jsxs(Qt,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(pe,{placeholder:"Search contacts...",value:X,onChange:bn=>ae(bn.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:()=>Z(new Set),children:"Clear"})]}),e.jsxs(go,{className:"h-48 rounded-lg border p-2",children:[Je&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!Je&&Ds.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),Ds.slice(0,200).map(bn=>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(bn.id),onCheckedChange:()=>Fn(bn.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[bn.first_name," ",bn.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:bn.email})]})]},bn.id)),Ds.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($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"})," ",Ss.length," recipient",Ss.length===1?"":"s"]}),Bt&&e.jsxs($e,{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:()=>re(bn=>!bn),children:le?e.jsxs(e.Fragment,{children:[e.jsx(Nx,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ta,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),le?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:Ks,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(Ct,{className:"h-4 w-4 animate-spin"}),"Sending to ",fe.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[fe.sent+fe.failed," / ",fe.total]})]}),e.jsx(Yi,{value:fe.total?(fe.sent+fe.failed)/fe.total*100:0}),fe.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[fe.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(ca,{className:"h-4 w-4"})," When to send"]}),e.jsxs(yw,{value:qe,onValueChange:bn=>ze(bn),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Km,{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(Km,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Su,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),qe==="later"&&e.jsx(pe,{type:"datetime-local",value:Ve,onChange:bn=>ht(bn.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:zt.length>0?`${zt.length} template field${zt.length===1?"":"s"} still need${zt.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:Wn,disabled:!vs,children:te?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):qe==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Su,{className:"h-4 w-4 mr-1"}),"Schedule for ",Ss.length]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),"Send to ",Ss.length]})})]})]})]})]}),e.jsx(fc,{open:ce,onOpenChange:ve,children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:qe==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(ic,{children:[qe==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',y,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[Ss.length," contact",Ss.length===1?"":"s"]}),qe==="later"&&Ve?` for ${new Date(Ve).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:Sn,children:qe==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Su,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),"Send to ",Ss.length]})})]})]})}),e.jsx(Os,{open:Be,onOpenChange:Se,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs($s,{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."}),(Ut||is)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!Ut&&!is&&bs.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."}),bs.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:bs.map(bn=>{var la,Xn;const xs=`mls:${bn.listing_key}`,Tr=Ae.has(xs),Lr=Array.isArray(bn.photos)&&bn.photos.length>0?typeof bn.photos[0]=="string"?bn.photos[0]:((la=bn.photos[0])==null?void 0:la.MediaURL)||((Xn=bn.photos[0])==null?void 0:Xn.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{Ce(wr=>{const Bn=new Set(wr);return Bn.has(xs)?Bn.delete(xs):Bn.size<6?Bn.add(xs):ne.error("Max 6 listings per newsletter"),Bn})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Tr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[Lr&&e.jsx("img",{src:Lr,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:bn.list_price?`$${Number(bn.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:bn.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[bn.city,bn.state?`, ${bn.state}`:""]})]}),Tr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Vr,{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(bn=>{const xs=`ex:${bn.id}`,Tr=Ae.has(xs);return e.jsxs("button",{type:"button",onClick:()=>{Ce(Lr=>{const la=new Set(Lr);return la.has(xs)?la.delete(xs):la.size<6?la.add(xs):ne.error("Max 6 listings per newsletter"),la})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Tr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[bn._photo&&e.jsx("img",{src:bn._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:bn.price?`$${Number(bn.price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:bn.property_address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[bn.city,bn.state?`, ${bn.state}`:""]})]}),Tr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Vr,{className:"h-4 w-4"})})]},xs)})})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>Se(!1),children:"Cancel"}),e.jsxs($,{onClick:Hs,disabled:Ae.size===0,children:["Insert ",Ae.size>0?Ae.size:""," listing",Ae.size===1?"":"s"]})]})]})}),e.jsx(b6e,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function SDn(){const{user:s}=_s(),t=Zt(),[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}=st({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))??[],v=(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&&(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"?v:y.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){ne.error(P.message);return}ne.success('Duplicated to "My Newsletters"'),g(),r("mine")},A=async I=>{const{error:P}=await q.from("agent_custom_newsletters").delete().eq("id",I);if(P){ne.error(P.message);return}ne.success("Deleted"),h(null),g()},E=I=>I.share_scope==="global"?e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(wn,{className:"h-3 w-3"}),"Starter"]}):I.share_scope==="brokerage"?e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(wi,{className:"h-3 w-3"}),"Brokerage"]}):I.share_scope==="team"?e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"}),"Team"]}):e.jsxs($e,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(jc,{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(wn,{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 (",v.length,")"]}),e.jsxs($,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",y.filter(I=>I.share_scope!=="global").length,")"]})]}),e.jsxs($,{onClick:()=>{o(null),i(!0)},children:[e.jsx(cn,{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(xn,{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(wn,{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(je,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Qr,{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(je,{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($e,{className:"bg-primary/90",children:"Template"}),E(I)]})]}),e.jsxs(Le,{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 ",Js(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(Zr,{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(pi,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>S(I),children:e.jsx(Za,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>h(I.id),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>S(I),children:[e.jsx(Za,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},I.id)})}),e.jsx(hDn,{open:a,onOpenChange:i,initial:l,onSaved:g}),c&&e.jsx(Wat,{open:!!c,onOpenChange:I=>!I&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(fc,{open:!!u,onOpenChange:I=>!I&&h(null),children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Delete this newsletter?"}),e.jsx(ic,{children:"This cannot be undone."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:()=>u&&A(u),children:"Delete"})]})]})})]})}function CDn(){const s=Zn(),[t,n]=j.useState(""),[r,a]=j.useState("grid"),[i,l]=j.useState(null),{data:o,isLoading:c}=st({queryKey:["newsletters"],queryFn:async()=>{const{data:A,error:E}=await q.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(E)throw E;return A}}),{data:d}=st({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:A}=await q.from("newsletter_likes").select("newsletter_id");return A||[]}}),{data:u}=st({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:A}=await q.from("newsletter_comments").select("newsletter_id");return A||[]}}),{data:h}=st({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[A,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:A.data||[],pdfs:E.data||[],videos:I.data||[],drives:P.data||[]}}}),m=A=>(d==null?void 0:d.filter(E=>E.newsletter_id===A).length)||0,f=A=>(u==null?void 0:u.filter(E=>E.newsletter_id===A).length)||0,g=A=>{var E;return((E=h==null?void 0:h.canva)==null?void 0:E.filter(I=>I.newsletter_id===A).length)||0},x=A=>{var E;return((E=h==null?void 0:h.pdfs)==null?void 0:E.filter(I=>I.newsletter_id===A).length)||0},v=A=>{var E;return((E=h==null?void 0:h.videos)==null?void 0:E.filter(I=>I.newsletter_id===A).length)||0},y=A=>{var E;return((E=h==null?void 0:h.drives)==null?void 0:E.filter(I=>I.newsletter_id===A).length)||0},b=A=>g(A)+x(A)+v(A)+y(A),w=o==null?void 0:o.filter(A=>{var E;return A.title.toLowerCase().includes(t.toLowerCase())||((E=A.description)==null?void 0:E.toLowerCase().includes(t.toLowerCase()))}),S=A=>{s(`/newsletters/${A}`)};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(pa,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"custom",children:"Build & Send"}),e.jsx(Xt,{value:"curated",children:"Curated Monthly"})]}),e.jsx(Qt,{value:"custom",className:"mt-2",children:e.jsx(SDn,{})}),e.jsxs(Qt,{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:A=>n(A.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(Xf,{className:"h-4 w-4"})}),e.jsx($,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(E0,{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((A,E)=>e.jsx(je,{children:e.jsxs(Le,{className:"p-0",children:[e.jsx(xn,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(xn,{className:"h-5 w-3/4"}),e.jsx(xn,{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(Qr,{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(A=>{const E=b(A.id),I=g(A.id),P=x(A.id),R=v(A.id);return r==="grid"?e.jsxs(je,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>S(A.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(Qr,{className:"h-16 w-16"})})}),e.jsxs(Le,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:A.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(Ea,{className:"h-3 w-3"}),Js(new Date(A.publish_date),"MMM d, yyyy")]})]}),A.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:A.description.replace(/<[^>]*>/g,"")}),E>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[I>0&&e.jsxs($e,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(yd,{className:"h-3 w-3"})," ",I," Template",I>1?"s":""]}),P>0&&e.jsxs($e,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(ji,{className:"h-3 w-3"})," ",P," PDF",P>1?"s":""]}),R>0&&e.jsxs($e,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Ou,{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($y,{className:"h-3 w-3"})," ",m(A.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ah,{className:"h-3 w-3"})," ",f(A.id)]})]}),A.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(A)},children:[e.jsx(Zr,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},A.id):e.jsx(je,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>S(A.id),children:e.jsxs("div",{className:"flex flex-row",children:[e.jsx("div",{className:"relative overflow-hidden bg-muted w-40 sm:w-48 shrink-0",children:A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground min-h-[100px]",children:e.jsx(Qr,{className:"h-10 w-10"})})}),e.jsxs(Le,{className:"p-4 flex-1 flex flex-col justify-center gap-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:A.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(Ea,{className:"h-3 w-3"}),Js(new Date(A.publish_date),"MMM d, yyyy")]})]}),A.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:A.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[E>0&&e.jsxs("span",{children:[E," resource",E>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($y,{className:"h-3 w-3"})," ",m(A.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ah,{className:"h-3 w-3"})," ",f(A.id)]})]})]}),A.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(A)},children:[e.jsx(Zr,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},A.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(Wat,{open:!!i,onOpenChange:A=>!A&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function ADn({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(je,{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(Le,{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 EDn(){const{id:s}=Wi(),t=Zn(),{user:n}=_s(),{toast:r}=Bi(),a=Zt(),{trackEngagement:i}=dK(),[l,o]=j.useState(""),[c,d]=j.useState(!1),{data:u,isLoading:h}=st({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}=st({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}=st({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}=st({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}=st({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:v}=st({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:I}=await q.from("newsletter_likes").select("*").eq("newsletter_id",s);return I||[]},enabled:!!s}),{data:y}=st({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=v==null?void 0:v.some(I=>I.user_id===(n==null?void 0:n.id)),w=mt({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=mt({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"})}}),A=mt({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(Ou,{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(xn,{className:"h-8 w-32"}),e.jsx(xn,{className:"h-64 w-full"}),e.jsx(xn,{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(Va,{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:Js(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(ADn,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(mK,{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":""}`}),(v==null?void 0:v.length)||0," ",(v==null?void 0:v.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(Zr,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(Wat,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),x&&x.length>0&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Le,{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(yd,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:I.title}),e.jsx(Ir,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},I.id))})]}),m&&m.length>0&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Le,{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(Ir,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:I.title})]},I.id))})]}),f&&f.length>0&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Le,{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(Qr,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:I.name}),e.jsx(ji,{className:"h-4 w-4 text-muted-foreground"})]},I.id))})]}),g&&g.length>0&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Videos"})}),e.jsx(Le,{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(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"text-lg",children:["Comments (",(y==null?void 0:y.length)||0,")"]})}),e.jsxs(Le,{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(Zr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:y==null?void 0:y.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:Js(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:()=>A.mutate(I.id),children:e.jsx(qn,{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 TDn({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((v,y)=>y===m?{...v,[f]:g}:v)},t(x)},d=async(h,m,f)=>{var v;const g=(v=f.target.files)==null?void 0:v[0];if(!g)return;const x=`${h}-${m}`;r(x);try{const y=`content-blocks/${Date.now()}-${g.name}`,{error:b}=await q.storage.from("newsletter-content").upload(y,g);if(!b){const{data:w}=q.storage.from("newsletter-content").getPublicUrl(y);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(cn,{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(je,{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(mr,{className:"h-4 w-4"})}),e.jsxs(Le,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(zg,{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(mr,{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:v=>d(m,g,v)}),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(Hc,{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(l2,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(pe,{placeholder:"Title",value:f.title,onChange:v=>c(m,g,"title",v.target.value),className:"h-8 text-sm"}),e.jsx(Rs,{placeholder:"Description",value:f.description,onChange:v=>c(m,g,"description",v.target.value),className:"text-sm min-h-[60px] resize-none"})]},g)})})]})]},m)),e.jsx(Os,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(Fs,{className:"sm:max-w-2xl",children:[e.jsx(Us,{children:e.jsx($s,{children:"Choose a Graphic"})}),e.jsx(SXt,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function MDn(){const{toast:s}=Bi(),t=Zt(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState({title:"",description:"",publish_date:Js(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([]),[v,y]=j.useState([]),[b,w]=j.useState([]),[S,A]=j.useState([]),[E,I]=j.useState(""),[P,R]=j.useState([]),[D,O]=j.useState(!1),{data:U,isLoading:W}=st({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:be,error:Ee}=await q.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(Ee)throw Ee;return be}}),V=mt({mutationFn:async be=>{const{data:Ee,error:ke}=await q.from("newsletter_content").insert({title:be.title,description:be.description||null,preview_image_url:be.preview_image_url,publish_date:be.publish_date,is_published:be.is_published,content_blocks:be.content_blocks,html_code:be.html_code}).select().single();if(ke)throw ke;return Ee},onSuccess:async be=>{await X(be.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),be.is_published&&Fhn(be.title,be.id),re()},onError:be=>{s({title:"Error creating newsletter",description:be.message,variant:"destructive"})}}),G=mt({mutationFn:async be=>{const{error:Ee}=await q.from("newsletter_content").update({title:be.title,description:be.description||null,preview_image_url:be.preview_image_url,publish_date:be.publish_date,is_published:be.is_published,content_blocks:be.content_blocks,html_code:be.html_code}).eq("id",be.id);if(Ee)throw Ee;return be.id},onSuccess:async be=>{await X(be),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),re()},onError:be=>{s({title:"Error updating newsletter",description:be.message,variant:"destructive"})}}),Z=mt({mutationFn:async be=>{const{error:Ee}=await q.from("newsletter_content").delete().eq("id",be);if(Ee)throw Ee},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:be=>{s({title:"Error deleting newsletter",description:be.message,variant:"destructive"})}}),X=async be=>{await q.from("newsletter_drive_links").delete().eq("newsletter_id",be),await q.from("newsletter_pdfs").delete().eq("newsletter_id",be),await q.from("newsletter_videos").delete().eq("newsletter_id",be),await q.from("newsletter_canva_links").delete().eq("newsletter_id",be);for(const Ee of P){const ke=`${be}/${Date.now()}-${Ee.file.name}`,{error:Ie}=await q.storage.from("newsletter-content").upload(ke,Ee.file);if(!Ie){const{data:Fe}=q.storage.from("newsletter-content").getPublicUrl(ke);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,ke)=>({newsletter_id:be,title:Ee.title,drive_url:Ee.drive_url,sort_order:ke}))),g.length>0&&await q.from("newsletter_pdfs").insert(g.map((Ee,ke)=>({newsletter_id:be,name:Ee.name,file_url:Ee.file_url,file_size:Ee.file_size||null,sort_order:ke}))),v.length>0&&await q.from("newsletter_videos").insert(v.map((Ee,ke)=>({newsletter_id:be,title:Ee.title,video_url:Ee.video_url,sort_order:ke}))),b.length>0&&await q.from("newsletter_canva_links").insert(b.map((Ee,ke)=>({newsletter_id:be,title:Ee.title,canva_share_link:Ee.canva_share_link,sort_order:ke})))},ae=async be=>{i(be),o({title:be.title,description:be.description||"",publish_date:Js(new Date(be.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:be.is_published}),h(be.preview_image_url),A(be.content_blocks||[]),I(be.html_code||"");const[Ee,ke,Ie,Fe]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",be.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",be.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",be.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",be.id).order("sort_order")]);f(Ee.data||[]),x(ke.data||[]),y(Ie.data||[]),w(Fe.data||[]),R([]),r(!0)},le=async be=>{const[Ee,ke,Ie,Fe]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",be.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",be.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",be.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",be.id).order("sort_order")]);i(null),o({title:`${be.title} (Copy)`,description:be.description||"",publish_date:Js(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(be.preview_image_url),A(be.content_blocks||[]),I(be.html_code||""),f((Ee.data||[]).map(({id:Ne,...Be})=>Be)),x((ke.data||[]).map(({id:Ne,...Be})=>Be)),y((Ie.data||[]).map(({id:Ne,...Be})=>Be)),w((Fe.data||[]).map(({id:Ne,...Be})=>Be)),R([]),r(!0)},re=()=>{r(!1),i(null),o({title:"",description:"",publish_date:Js(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),h(null),f([]),x([]),y([]),w([]),A([]),I(""),R([])},te=async be=>{var ke;const Ee=(ke=be.target.files)==null?void 0:ke[0];Ee&&(d(Ee),h(URL.createObjectURL(Ee)))},J=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}O(!0);let be=u;if(c){const Ee=`previews/${Date.now()}-${c.name}`,{error:ke}=await q.storage.from("newsletter-content").upload(Ee,c);if(!ke){const{data:Ie}=q.storage.from("newsletter-content").getPublicUrl(Ee);be=Ie.publicUrl}}a?G.mutate({id:a.id,...l,preview_image_url:be,content_blocks:S,html_code:E||null}):V.mutate({...l,preview_image_url:be,content_blocks:S,html_code:E||null}),O(!1)},ce=()=>f([...m,{title:"",drive_url:"",sort_order:m.length}]),ve=()=>y([...v,{title:"",video_url:"",sort_order:v.length}]),fe=()=>w([...b,{title:"",canva_share_link:"",sort_order:b.length}]),ue=be=>{const Ee=be.target.files;if(!Ee)return;const ke=Array.from(Ee).map(Ie=>({file:Ie,name:Ie.name.replace(/\.[^/.]+$/,"")}));R([...P,...ke])};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(Dm,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(U==null?void 0:U.length)||0})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(U==null?void 0:U.filter(be=>be.is_published).length)||0})})]})]}),e.jsxs(Os,{open:n,onOpenChange:be=>!be&&re(),children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:()=>r(!0),children:[e.jsx(cn,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(Fs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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:be=>o({...l,title:be.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:be=>o({...l,publish_date:be.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(kk,{content:l.description,onChange:be=>o({...l,description:be}),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(mr,{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(jn,{checked:l.is_published,onCheckedChange:be=>o({...l,is_published:be})}),e.jsx(ee,{children:"Published"})]}),e.jsx(TDn,{rows:S,onChange:A}),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:be=>I(be.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:fe,children:[e.jsx(cn,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),b.map((be,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(pe,{placeholder:"Link title",value:be.title,onChange:ke=>{const Ie=[...b];Ie[Ee].title=ke.target.value,w(Ie)},className:"w-1/3"}),e.jsx(pe,{placeholder:"Canva share link",value:be.canva_share_link,onChange:ke=>{const Ie=[...b];Ie[Ee].canva_share_link=ke.target.value,w(Ie)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>w(b.filter((ke,Ie)=>Ie!==Ee)),children:e.jsx(mr,{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(cn,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),m.map((be,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(pe,{placeholder:"Link title",value:be.title,onChange:ke=>{const Ie=[...m];Ie[Ee].title=ke.target.value,f(Ie)},className:"w-1/3"}),e.jsx(pe,{placeholder:"Google Drive URL",value:be.drive_url,onChange:ke=>{const Ie=[...m];Ie[Ee].drive_url=ke.target.value,f(Ie)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>f(m.filter((ke,Ie)=>Ie!==Ee)),children:e.jsx(mr,{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((be,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Qr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:be.name}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>x(g.filter((ke,Ie)=>Ie!==Ee)),children:e.jsx(mr,{className:"h-4 w-4"})})]},`existing-${Ee}`)),P.map((be,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Qr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:be.name,onChange:ke=>{const Ie=[...P];Ie[Ee].name=ke.target.value,R(Ie)},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((ke,Ie)=>Ie!==Ee)),children:e.jsx(mr,{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:ve,children:[e.jsx(cn,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),v.map((be,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(pe,{placeholder:"Video title",value:be.title,onChange:ke=>{const Ie=[...v];Ie[Ee].title=ke.target.value,y(Ie)},className:"w-1/3"}),e.jsx(pe,{placeholder:"Video URL",value:be.video_url,onChange:ke=>{const Ie=[...v];Ie[Ee].video_url=ke.target.value,y(Ie)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>y(v.filter((ke,Ie)=>Ie!==Ee)),children:e.jsx(mr,{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:re,children:"Cancel"}),e.jsx($,{onClick:J,disabled:D||V.isPending||G.isPending,children:D?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(je,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:W?e.jsx(An,{children:e.jsx(wt,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(U==null?void 0:U.length)===0?e.jsx(An,{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(be=>e.jsxs(An,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[be.preview_image_url?e.jsx("img",{src:be.preview_image_url,alt:be.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(Qr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:be.title}),be.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:be.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(wt,{children:Js(new Date(be.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 ${be.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:be.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(be),title:"Edit",children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>le(be),title:"Duplicate",children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:async()=>{await mo("Are you sure you want to delete this newsletter?")&&Z.mutate(be.id)},children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},be.id))})]})})})]})})}const PDn={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null};function IDn({brokerages:s}){var A;const{toast:t}=Bi(),[n,r]=j.useState(PDn),[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),[v,y]=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 mo({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),y({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,y({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(je,{children:[e.jsxs(St,{className:"pb-3",children:[e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(Rm,{className:"h-4 w-4"})," SMS Audience"]}),e.jsx(Vn,{children:"Only members with a recorded consent date and source are included. Opted-out and undeliverable numbers are always excluded."})]}),e.jsxs(Le,{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(Ct,{className:"h-4 w-4 animate-spin"}):(u==null?void 0:u.count)??0})]}),(A=u==null?void 0:u.sample)!=null&&A.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(ca,{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(je,{children:[e.jsxs(St,{className:"pb-3",children:[e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(no,{className:"h-4 w-4"})," Text message"]}),e.jsxs(Vn,{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(Le,{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($e,{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(Ct,{className:"mr-2 h-4 w-4 animate-spin"})," Send test"]})]}),v&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Yi,{value:v.total?(v.sent+v.failed)/v.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(Vr,{className:"h-3 w-3"})," ",v.sent," sent"]}),v.failed>0&&e.jsxs("span",{className:"flex items-center gap-1 text-destructive",children:[e.jsx(vl,{className:"h-3 w-3"})," ",v.failed," failed"]}),e.jsxs("span",{children:["of ",v.total]})]})]}),e.jsxs($,{onClick:S,disabled:g||!a.trim()||!(u!=null&&u.count),className:"w-full",children:[g?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Zr,{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 C9e={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null,respectOptOut:!0,program:"all",programStatus:"active"},LDn=["{{first_name}}","{{name}}","{{email}}"];function RDn(s){return`${s||'

Your email preview will appear here…

'}`}function DDn(){var Ke;const{toast:s}=Bi(),{user:t}=_s(),n=Zt(),[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,v]=j.useState(!1),[y,b]=j.useState(C9e),[w,S]=j.useState(null),[A,E]=j.useState(!1),[I,P]=j.useState(""),[R,D]=j.useState(""),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Z]=j.useState("rich"),[X,ae]=j.useState(""),[le,re]=j.useState(""),[te,J]=j.useState(""),[ce,ve]=j.useState(!1),[fe,ue]=j.useState(null),be=G==="rich"?X:le;j.useEffect(()=>{t!=null&&t.email&&(U(Je=>Je||t.email),V(Je=>Je||t.email),J(Je=>Je||t.email))},[t==null?void 0:t.email]);const{data:Ee}=st({queryKey:["broadcast-brokerages"],queryFn:async()=>{const{data:Je}=await q.from("brokerages").select("id, name").order("name");return Je||[]}}),{data:ke}=st({queryKey:["broadcast-programs"],queryFn:async()=>{const{data:Je}=await q.from("programs").select("id, name").order("created_at",{ascending:!1});return Je||[]}}),{data:Ie}=st({queryKey:["admin-broadcasts"],queryFn:async()=>{const{data:Je,error:ft}=await q.from("admin_broadcasts").select("*").order("created_at",{ascending:!1}).limit(30);if(ft)throw ft;return Je}}),{data:Fe}=st({queryKey:["admin-broadcast-templates"],queryFn:async()=>{const{data:Je,error:ft}=await q.from("admin_broadcast_templates").select("*").order("updated_at",{ascending:!1});if(ft)throw ft;return Je}}),Ne=async Je=>{E(!0);try{const{data:ft,error:gt}=await q.functions.invoke("admin-broadcast",{body:{action:"preview",filters:Je}});if(gt)throw gt;if(ft!=null&&ft.error)throw new Error(ft.error);S(ft)}catch(ft){s({title:"Could not load audience",description:ft.message,variant:"destructive"})}finally{E(!1)}};j.useEffect(()=>{if(r!=="filters")return;const Je=setTimeout(()=>Ne(y),400);return()=>clearTimeout(Je)},[y,r]),j.useEffect(()=>{if(r!=="manual")return;const Je=setTimeout(async()=>{m(!0);try{const{data:ft,error:gt}=await q.functions.invoke("admin-broadcast",{body:{action:"search_members",query:o}});if(gt)throw gt;u((ft==null?void 0:ft.members)||[])}catch{u([])}finally{m(!1)}},350);return()=>clearTimeout(Je)},[o,r]);const Be=(Je,ft)=>b(gt=>({...gt,[Je]:ft})),Se=r==="manual"?i.length:(w==null?void 0:w.count)||0,Ae=()=>r==="manual"?{recipient_mode:"manual",manual_emails:i.map(Je=>Je.email)}:{recipient_mode:"filters",filters:y},Ce=Je=>l(ft=>ft.some(gt=>gt.email.toLowerCase()===Je.email.toLowerCase())?ft.filter(gt=>gt.email.toLowerCase()!==Je.email.toLowerCase()):[...ft,Je]),qe=async()=>{const Je=(f||I||R).trim();if(!Je||!be.trim()){s({title:"Add a template name and content first",variant:"destructive"});return}v(!0);try{const{error:ft}=await q.from("admin_broadcast_templates").insert({created_by:t.id,name:Je,subject:R,body_html:be,editor_mode:G,from_email:O||null,reply_to_email:W||null,filters:y});if(ft)throw ft;g(""),s({title:"Template saved",description:`"${Je}" is available for future sends.`}),n.invalidateQueries({queryKey:["admin-broadcast-templates"]})}catch(ft){s({title:"Could not save template",description:ft.message,variant:"destructive"})}finally{v(!1)}},ze=Je=>{P(Je.name||""),D(Je.subject||""),Je.from_email&&U(Je.from_email),Je.reply_to_email&&V(Je.reply_to_email);const ft=Je.editor_mode==="html"?"html":"rich";Z(ft),ft==="html"?re(Je.body_html||""):ae(Je.body_html||""),Je.filters&&Object.keys(Je.filters).length&&b({...C9e,...Je.filters}),s({title:"Template loaded",description:"Edit and send when ready."})},Ve=async Je=>{if(!await mo(`Delete template "${Je.name}"?`))return;const{error:ft}=await q.from("admin_broadcast_templates").delete().eq("id",Je.id);if(ft){s({title:"Delete failed",description:ft.message,variant:"destructive"});return}n.invalidateQueries({queryKey:["admin-broadcast-templates"]})},ht=j.useMemo(()=>!!R.trim()&&!!be.trim()&&!!O.trim()&&Se>0,[R,be,O,Se]),Qe=async()=>{if(!te||!R.trim()||!be.trim()){s({title:"Add a subject, content and test address first",variant:"destructive"});return}try{const{data:Je,error:ft}=await q.functions.invoke("admin-broadcast",{body:{action:"test",to:te,subject:R,html:be,from_email:O,reply_to:W||void 0}});if(ft)throw ft;if(Je!=null&&Je.error)throw new Error(Je.error);s({title:"Test sent",description:`Check ${te}`})}catch(Je){s({title:"Test failed",description:Je.message,variant:"destructive"})}},at=async()=>{const Je=Se;if(await mo({title:"Send this broadcast?",description:`"${R}" will be emailed to ${Je} member${Je===1?"":"s"}. Sent emails can't be recalled.`,confirmText:"Send broadcast",cancelText:"Cancel",destructive:!1})){ve(!0),ue({total:Je,sent:0,failed:0});try{const{data:gt,error:es}=await q.functions.invoke("admin-broadcast",{body:{action:"queue",name:I||R,subject:R,html:be,from_email:O,reply_to:W||void 0,...Ae()}});if(es)throw es;if(gt!=null&>.error)throw new Error(gt.error);let Ht=0,as=0,bs=gt.total,Ut=0;for(;bs>0;){const{data:Ft,error:is}=await q.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:gt.broadcast_id,limit:40}});if(is)throw is;if(Ft!=null&&Ft.error)throw new Error(Ft.error);if(Ht+=Ft.sent,as+=Ft.failed,bs=Ft.remaining,ue({total:gt.total,sent:Ht,failed:as}),Ft.throttled){const jt=Math.min(Math.max(Number(Ft.retry_after_ms)||15e3,5e3),45e3);await new Promise(zs=>setTimeout(zs,jt));continue}if(Ft.sent===0&&Ft.failed===0){if(++Ut>=3)break;await new Promise(jt=>setTimeout(jt,5e3))}else Ut=0}s({title:"Broadcast complete",description:`${Ht} sent${as?`, ${as} failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(gt){s({title:"Send failed",description:gt.message,variant:"destructive"})}finally{ve(!1)}}},rt=async Je=>{ve(!0);try{const{data:ft,error:gt}=await q.functions.invoke("admin-broadcast",{body:{action:"retry_failed",broadcast_id:Je}});if(gt)throw gt;if(ft!=null&&ft.error)throw new Error(ft.error);let es=0,Ht=0,as=ft.requeued,bs=0;for(ue({total:as,sent:0,failed:0});as>0;){const{data:Ut,error:Ft}=await q.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:Je,limit:25}});if(Ft)throw Ft;if(Ut!=null&&Ut.error)throw new Error(Ut.error);if(es+=Ut.sent,Ht+=Ut.failed,as=Ut.remaining,ue({total:ft.requeued,sent:es,failed:Ht}),Ut.throttled){await new Promise(is=>setTimeout(is,Math.min(Math.max(Number(Ut.retry_after_ms)||15e3,5e3),45e3)));continue}if(Ut.sent===0&&Ut.failed===0){if(++bs>=3)break;await new Promise(is=>setTimeout(is,5e3))}else bs=0}s({title:"Retry complete",description:`${es} sent${Ht?`, ${Ht} still failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(ft){s({title:"Retry failed",description:ft.message,variant:"destructive"})}finally{ve(!1)}};return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Dm,{title:"Member Broadcasts",description:"Send a one-off email to a filtered slice of LevelUp members"}),e.jsxs(pa,{defaultValue:"compose",className:"space-y-6",children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"compose",className:"gap-2",children:[e.jsx(pn,{className:"h-4 w-4"})," Compose"]}),e.jsxs(Xt,{value:"sms",className:"gap-2",children:[e.jsx(no,{className:"h-4 w-4"})," Text (SMS)"]}),e.jsxs(Xt,{value:"templates",className:"gap-2",children:[e.jsx(o2,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Xt,{value:"history",className:"gap-2",children:[e.jsx(Cw,{className:"h-4 w-4"})," History"]})]}),e.jsx(Qt,{value:"sms",className:"space-y-6",children:e.jsx(IDn,{brokerages:Ee})}),e.jsx(Qt,{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(je,{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(Yn,{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:A?"—":(w==null?void 0:w.count)??0}),e.jsx("span",{className:"text-sm opacity-90",children:r==="manual"?"members selected":"members match"})]})]}),e.jsxs(Le,{className:"space-y-4 pt-5",children:[e.jsx(pa,{value:r,onValueChange:Je=>a(Je),children:e.jsxs(ga,{className:"grid w-full grid-cols-2",children:[e.jsxs(Xt,{value:"filters",className:"gap-1.5 text-xs",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," Filters"]}),e.jsxs(Xt,{value:"manual",className:"gap-1.5 text-xs",children:[e.jsx(lc,{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:Je=>c(Je.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(Je=>e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx("span",{className:"max-w-[150px] truncate",children:Je.name||Je.email}),e.jsx("button",{type:"button",onClick:()=>Ce(Je),"aria-label":`Remove ${Je.email}`,children:e.jsx(mr,{className:"h-3 w-3"})})]},Je.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(Je=>{const ft=i.some(gt=>gt.email.toLowerCase()===Je.email.toLowerCase());return e.jsxs("button",{type:"button",onClick:()=>Ce(Je),className:`flex w-full items-center justify-between rounded-md px-2.5 py-2 text-left text-xs hover:bg-muted ${ft?"bg-muted":""}`,children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate font-medium",children:Je.name||"Member"}),e.jsx("span",{className:"block truncate text-muted-foreground",children:Je.email})]}),ft&&e.jsx(Vr,{className:"h-4 w-4 shrink-0 text-primary"})]},Je.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:y.status,onValueChange:Je=>Be("status",Je),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:y.billing,onValueChange:Je=>Be("billing",Je),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:y.role,onValueChange:Je=>Be("role",Je),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:y.brokerage,onValueChange:Je=>Be("brokerage",Je),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(Je=>e.jsx(Ge,{value:Je.id,children:Je.name},Je.id))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Program enrollment"}),e.jsxs(ms,{value:y.program,onValueChange:Je=>Be("program",Je),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"}),(ke||[]).map(Je=>e.jsx(Ge,{value:Je.id,children:Je.name},Je.id))]})]})]}),y.program!=="all"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Enrollment status"}),e.jsxs(ms,{value:y.programStatus,onValueChange:Je=>Be("programStatus",Je),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:y.joinedWithinDays?String(y.joinedWithinDays):"all",onValueChange:Je=>Be("joinedWithinDays",Je==="all"?null:Number(Je)),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(jn,{checked:y.respectOptOut,onCheckedChange:Je=>Be("respectOptOut",Je)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>b(C9e),children:"Reset"}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>Ne(y),disabled:A,children:[A?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(co,{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(Je=>e.jsxs("p",{className:"truncate text-xs",children:[e.jsx("span",{className:"font-medium",children:Je.name||"Member"})," ",e.jsx("span",{className:"text-muted-foreground",children:Je.email})]},Je.email))})]}):null]})]})]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(je,{children:[e.jsxs(St,{className:"pb-4",children:[e.jsx(Et,{className:"text-base",children:"Message"}),e.jsxs(Vn,{children:["Personalize with merge tags: ",LDn.join(" ")]})]}),e.jsxs(Le,{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:Je=>P(Je.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:Je=>D(Je.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:Je=>U(Je.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:Je=>V(Je.target.value),placeholder:"support@relevelup.com"})]})]}),e.jsxs(pa,{value:G,onValueChange:Je=>Z(Je),children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"rich",className:"gap-2",children:[e.jsx(wn,{className:"h-3.5 w-3.5"})," Rich text"]}),e.jsxs(Xt,{value:"html",className:"gap-2",children:[e.jsx(SE,{className:"h-3.5 w-3.5"})," Paste HTML"]})]}),e.jsx(Qt,{value:"rich",className:"mt-3",children:e.jsx(kk,{content:X,onChange:ae,minHeight:"320px",placeholder:"Write your message…"})}),e.jsxs(Qt,{value:"html",className:"mt-3 space-y-2",children:[e.jsx(Rs,{value:le,onChange:Je=>re(Je.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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ta,{className:"h-4 w-4"})," Preview"]}),e.jsx($e,{variant:"secondary",children:G==="html"?"Raw HTML":"Rich text"})]}),e.jsx(Le,{children:e.jsx("iframe",{title:"Email preview",srcDoc:RDn(be),className:"h-[420px] w-full rounded-lg border bg-white"})})]}),e.jsx(je,{children:e.jsxs(Le,{className:"space-y-4 pt-6",children:[fe&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:[fe.sent+fe.failed," of ",fe.total," processed"]}),e.jsxs("span",{className:"text-muted-foreground",children:[fe.sent," sent",fe.failed?` • ${fe.failed} failed`:""]})]}),e.jsx(Yi,{value:fe.total?(fe.sent+fe.failed)/fe.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:Je=>J(Je.target.value),className:"w-64"})]}),e.jsx($,{variant:"outline",onClick:Qe,disabled:ce,children:"Send test"}),e.jsx("div",{className:"flex-1"}),e.jsxs($,{onClick:at,disabled:!ht||ce,size:"lg",className:"gap-2",children:[ce?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),ce?"Sending…":`Send to ${Se} member${Se===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:Je=>g(Je.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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(OI,{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(Qt,{value:"templates",className:"space-y-3",children:(Fe||[]).length===0?e.jsx(je,{children:e.jsxs(Le,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(o2,{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(Je=>e.jsx(je,{children:e.jsxs(Le,{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:Je.name}),e.jsx($e,{variant:"secondary",className:"text-xs",children:Je.editor_mode==="html"?"Raw HTML":"Rich text"})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",Je.subject||"—"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Updated ",Js(new Date(Je.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(Je),children:[e.jsx(tl,{className:"h-3.5 w-3.5"})," Use template"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Ve(Je),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})},Je.id))}),e.jsx(Qt,{value:"history",className:"space-y-3",children:(Ie||[]).length===0?e.jsx(je,{children:e.jsxs(Le,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(pn,{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."})]})}):(Ie||[]).map(Je=>e.jsx(je,{children:e.jsxs(Le,{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:Je.name}),e.jsxs($e,{variant:Je.status==="sent"?"default":Je.status==="sending"?"secondary":"outline",className:"gap-1 text-xs",children:[Je.status==="sent"?e.jsx(Vr,{className:"h-3 w-3"}):e.jsx(vl,{className:"h-3 w-3"}),Je.status]})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",Je.subject]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Js(new Date(Je.created_at),"MMM d, yyyy h:mm a")," • from ",Je.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:Je.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:Je.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:Je.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:[Je.open_count??0,Je.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((Je.open_count??0)/Je.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:[Je.click_count??0,Je.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((Je.click_count??0)/Je.sent_count*100),"%"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clicks"})]}),Je.failed_count>0&&e.jsx("div",{className:"flex items-center",children:e.jsx($,{size:"sm",variant:"outline",disabled:ce,onClick:()=>rt(Je.id),children:"Retry failed"})})]})]})},Je.id))})]})]})})}const FDn=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function ODn(){const s=Zt(),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}=st({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||[]}}),v=j.useMemo(()=>{const O=new Set(FDn);return g.forEach(U=>O.add(U.category)),Array.from(O).sort()},[g]),y=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)},A=async O=>{var U;if(!O.type.startsWith("image/")){ne.error("Please choose an image file");return}if(O.size>15*1024*1024){ne.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:Z}=q.storage.from("newsletter-content").getPublicUrl(V);f(X=>({...X,image_url:Z.publicUrl,title:X.title||O.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),ne.success("Uploaded")}catch(W){ne.error(W.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},E=mt({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:()=>{ne.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),b()},onError:O=>ne.error(O.message||"Save failed")}),I=mt({mutationFn:async O=>{const{error:U}=await q.from("newsletter_graphics").delete().eq("id",O);if(U)throw U},onSuccess:()=>{ne.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:O=>ne.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?ne.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?ne.error(U.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},D=O=>{navigator.clipboard.writeText(O),ne.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(Dm,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(je,{children:e.jsxs(Le,{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"}),v.map(O=>e.jsx(Ge,{value:O,children:O},O))]})]}),e.jsxs($,{onClick:w,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(kv,{className:"h-4 w-4"})," Add Graphic"]})]})}),x?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):y.length===0?e.jsx(je,{children:e.jsxs(Le,{className:"py-16 text-center",children:[e.jsx(Hc,{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(kv,{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:y.map(O=>e.jsxs(je,{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($e,{className:"absolute top-2 left-2 gap-0.5 bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(ei,{className:"h-3 w-3 fill-current"})," Featured"]}),!O.is_active&&e.jsx($e,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(Le,{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($e,{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(pi,{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(ei,{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(Za,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{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 mo(`Delete "${O.title}"?`)&&I.mutate(O.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})]})]},O.id))})]}),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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&&A(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(mr,{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(Ct,{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:v.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(jn,{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(jn,{checked:m.is_active,onCheckedChange:O=>f(U=>({...U,is_active:O}))})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>E.mutate(),disabled:E.isPending,children:[E.isPending&&e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const Qkt={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 zDn(){const{user:s}=_s(),{toast:t}=Bi(),n=Zn(),r=Zt(),[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:v=[],isLoading:y}=st({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(Z=>Z.user_id))||[])],{data:D}=await q.from("profiles").select("id, name").in("id",R),O=new Map((D==null?void 0:D.map(Z=>[Z.id,Z]))||[]);let U=[];if(s){const{data:Z}=await q.from("wishlist_votes").select("item_id").eq("user_id",s.id);U=(Z==null?void 0:Z.map(X=>X.item_id))||[]}const W=(I==null?void 0:I.map(Z=>Z.id))||[],{data:V}=await q.from("wishlist_comments").select("item_id").in("item_id",W),G=new Map;return V==null||V.forEach(Z=>{G.set(Z.item_id,(G.get(Z.item_id)||0)+1)}),I==null?void 0:I.map(Z=>{const X=O.get(Z.user_id),ae=(X==null?void 0:X.name)||"Unknown";return{...Z,user_name:ae,user_initials:ae.split(" ").map(le=>le[0]).join("").toUpperCase().slice(0,2),has_voted:U.includes(Z.id),comment_count:G.get(Z.id)||0}})}}),b=mt({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=mt({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=v.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=v.filter(E=>E.title.toLowerCase().includes(a.toLowerCase())||E.description.toLowerCase().includes(a.toLowerCase())),A=()=>{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(QS,{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(Os,{open:c,onOpenChange:d,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(cn,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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:A,className:"w-full",disabled:b.isPending,children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{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(pa,{value:l,onValueChange:E=>o(E),children:e.jsxs(ga,{children:[e.jsx(Xt,{value:"popular",children:"Most Popular"}),e.jsx(Xt,{value:"latest",children:"Latest"}),e.jsx(Xt,{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"})}),y?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{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(QS,{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(cn,{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($e,{className:Pt("text-xs",Qkt[E.status].color),children:Qkt[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(no,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:E.comment_count})]})]})},E.id))})]})})}const Jkt={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 BDn(){const{itemId:s}=Wi(),t=Zn(),{user:n}=_s(),{toast:r}=Bi(),a=Zt(),[i,l]=j.useState(""),{data:o=!1}=st({queryKey:["user-is-admin",n==null?void 0:n.id],queryFn:async()=>{if(!n)return!1;const{data:v,error:y}=await q.from("user_roles").select("role").eq("user_id",n.id).eq("role","admin").maybeSingle();return!y&&!!v},enabled:!!n}),{data:c,isLoading:d}=st({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:v,error:y}=await q.from("wishlist_items").select("*").eq("id",s).single();if(y)throw y;const{data:b}=await q.from("profiles").select("name").eq("id",v.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{...v,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}=st({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:v,error:y}=await q.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(y)throw y;const b=[...new Set((v==null?void 0:v.map(A=>A.user_id))||[])],{data:w}=await q.from("profiles").select("id, name").in("id",b),S=new Map((w==null?void 0:w.map(A=>[A.id,A]))||[]);return v==null?void 0:v.map(A=>{const E=S.get(A.user_id),I=(E==null?void 0:E.name)||"Unknown";return{...A,user_name:I,user_initials:I.split(" ").map(P=>P[0]).join("").toUpperCase().slice(0,2)}})}}),m=mt({mutationFn:async v=>{if(v){const{error:y}=await q.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",n.id);if(y)throw y;return{wasAdded:!1}}else{const{error:y}=await q.from("wishlist_votes").insert({item_id:s,user_id:n.id});if(y)throw y;return{wasAdded:!0}}},onSuccess:async v=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),v!=null&&v.wasAdded&&c){const y=(c.vote_count||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:y}}).catch(console.error)}},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),f=mt({mutationFn:async v=>{const{error:y}=await q.from("wishlist_comments").insert({item_id:s,user_id:n.id,content:v});if(y)throw y},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),r({title:"Comment added!"})},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),g=mt({mutationFn:async v=>{const{error:y}=await q.from("wishlist_comments").delete().eq("id",v);if(y)throw y},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),r({title:"Comment deleted"})},onError:v=>{r({title:"Error",description:v.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(xn,{className:"h-8 w-32 mb-6"}),e.jsx(xn,{className:"h-48 w-full mb-6"}),e.jsx(xn,{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(Va,{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($e,{className:Pt("text-xs",Jkt[c.status].color),children:Jkt[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(BTe,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"})})]}),h?e.jsx("div",{className:"space-y-4",children:[1,2].map(v=>e.jsx(xn,{className:"h-20 w-full"},v))}):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(v=>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:v.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:v.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(v.created_at).toLocaleDateString()})]}),e.jsx(Trt,{content:v.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===v.user_id&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>g.mutate(v.id),children:e.jsx(qn,{className:"h-4 w-4"})})]},v.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 eSt={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"}},tSt=["open","under_review","planned","in_progress","launched","declined"];function $Dn(){const{toast:s}=Bi(),t=Zn(),n=Zt(),[r,a]=j.useState(""),[i,l]=j.useState("all"),[o,c]=j.useState(!1),[d,u]=j.useState(null),{data:h=[],isLoading:m}=st({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:y,error:b}=await q.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(b)throw b;const w=[...new Set((y==null?void 0:y.map(R=>R.user_id))||[])],{data:S}=await q.from("profiles").select("id, name, email").in("id",w),A=new Map((S==null?void 0:S.map(R=>[R.id,R]))||[]),E=(y==null?void 0:y.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)}),y==null?void 0:y.map(R=>{const D=A.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=mt({mutationFn:async({itemId:y,status:b})=>{const{error:w}=await q.from("wishlist_items").update({status:b}).eq("id",y);if(w)throw w},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:y=>{s({title:"Error",description:y.message,variant:"destructive"})}}),g=mt({mutationFn:async y=>{const{error:b}=await q.from("wishlist_items").delete().eq("id",y);if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:y=>{s({title:"Error",description:y.message,variant:"destructive"})}}),x=h.filter(y=>{const b=y.title.toLowerCase().includes(r.toLowerCase())||y.description.toLowerCase().includes(r.toLowerCase())||y.user_name.toLowerCase().includes(r.toLowerCase()),w=i==="all"||y.status===i;return b&&w}),v={total:h.length,open:h.filter(y=>y.status==="open").length,inProgress:h.filter(y=>y.status==="in_progress").length,launched:h.filter(y=>y.status==="launched").length,highVotes:h.filter(y=>y.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(Va,{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:v.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:v.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:v.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:v.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:v.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:y=>a(y.target.value),className:"pl-10"})]}),e.jsxs(ms,{value:i,onValueChange:y=>l(y),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"}),tSt.map(y=>e.jsx(Ge,{value:y,children:eSt[y].label},y))]})]})]}),m?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(y=>e.jsx(xn,{className:"h-16 w-full"},y))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:x.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):x.map(y=>e.jsxs(An,{className:Pt(y.vote_count>=10&&"bg-primary/5"),children:[e.jsx(wt,{children:e.jsx($e,{variant:y.vote_count>=10?"default":"secondary",children:y.vote_count})}),e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:y.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:y.description})]})}),e.jsx(wt,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:y.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:y.user_email})]})}),e.jsx(wt,{className:"hidden sm:table-cell",children:y.comment_count}),e.jsx(wt,{children:e.jsxs(ms,{value:y.status,onValueChange:b=>f.mutate({itemId:y.id,status:b}),children:[e.jsx(us,{className:"w-[140px] h-8",children:e.jsx(fs,{})}),e.jsx(hs,{children:tSt.map(b=>e.jsx(Ge,{value:b,children:eSt[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/${y.id}`,"_blank"),children:e.jsx(Ir,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(y.id),c(!0)},children:e.jsx(qn,{className:"h-4 w-4"})})]})})]},y.id))})]})}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function UDn(){const{user:s}=_s(),[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,v]=j.useState(""),[y,b]=j.useState(""),[w,S]=j.useState(""),[A,E]=j.useState(""),[I,P]=j.useState(!1),[R,D]=j.useState(""),[O,U]=j.useState("once"),[W,V]=j.useState([]),[G,Z]=j.useState([]),[X,ae]=j.useState(!1),[le,re]=j.useState(!1),[te,J]=j.useState([]),[ce,ve]=j.useState({total:0,dismissed:0});j.useEffect(()=>{fe()},[]);const fe=async()=>{const{data:rt,error:Ke}=await q.from("levelup_briefs").select("*").order("created_at",{ascending:!1});Ke?(ne.error("Failed to fetch briefs"),console.error(Ke)):n(rt||[]),a(!1)},ue=()=>{g(""),v(""),b(""),S(""),E(""),P(!1),D(new Date().toISOString().slice(0,16)),U("once"),V([]),Z([]),c(null)},be=()=>{ue(),l(!0)},Ee=async rt=>{c(rt),g(rt.title),v(rt.description||""),b(rt.video_url||""),S(rt.graphic_url||""),E(rt.graphic_link_url||""),P(rt.is_published),D(rt.publish_date.slice(0,16)),U(rt.show_frequency);const{data:Ke}=await q.from("levelup_brief_links").select("*").eq("brief_id",rt.id).order("sort_order");V((Ke==null?void 0:Ke.map(ft=>({title:ft.title,url:ft.url})))||[]);const{data:Je}=await q.from("levelup_brief_polls").select("*").eq("brief_id",rt.id).order("sort_order");if(Je){const ft=[];for(const gt of Je){const{data:es}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",gt.id).order("sort_order");ft.push({question:gt.question,poll_type:gt.poll_type,options:(es==null?void 0:es.map(Ht=>Ht.option_text))||[]})}Z(ft)}l(!0)},ke=async rt=>{var Je;const Ke=(Je=rt.target.files)==null?void 0:Je[0];if(Ke){ae(!0);try{const ft=await q.functions.invoke("bunny-upload",{body:{action:"create",title:Ke.name.replace(/\.[^/.]+$/,"")}});if(ft.error)throw ft.error;const{videoId:gt,libraryId:es}=ft.data,Ht=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:gt}});if(Ht.error)throw Ht.error;const{uploadUrl:as,apiKey:bs}=Ht.data,Ut=new XMLHttpRequest;await new Promise((is,jt)=>{Ut.upload.addEventListener("progress",zs=>{if(zs.lengthComputable){const yt=Math.round(zs.loaded/zs.total*100);console.log("Upload progress:",yt)}}),Ut.addEventListener("load",()=>{Ut.status>=200&&Ut.status<300?is():jt(new Error(`Upload failed with status ${Ut.status}`))}),Ut.addEventListener("error",()=>jt(new Error("Upload failed"))),Ut.open("PUT",as),Ut.setRequestHeader("AccessKey",bs),Ut.send(Ke)});const Ft=`https://player.mediadelivery.net/embed/${es}/${gt}`;b(Ft),ne.success("Video uploaded successfully! It may take a few minutes to process.")}catch(ft){console.error("Upload error:",ft),ne.error("Failed to upload video")}finally{ae(!1)}}},Ie=async()=>{if(!f.trim()){ne.error("Title is required");return}try{let rt;if(o){const{error:Ke}=await q.from("levelup_briefs").update({title:f,description:x||null,video_url:y||null,graphic_url:w||null,graphic_link_url:A||null,is_published:I,publish_date:R,show_frequency:O}).eq("id",o.id);if(Ke)throw Ke;rt=o.id,await q.from("levelup_brief_links").delete().eq("brief_id",rt);const{data:Je}=await q.from("levelup_brief_polls").select("id").eq("brief_id",rt);if(Je)for(const ft of Je)await q.from("levelup_brief_poll_options").delete().eq("poll_id",ft.id);await q.from("levelup_brief_polls").delete().eq("brief_id",rt)}else{const{data:Ke,error:Je}=await q.from("levelup_briefs").insert({title:f,description:x||null,video_url:y||null,graphic_url:w||null,graphic_link_url:A||null,is_published:I,publish_date:R,show_frequency:O,created_by:s==null?void 0:s.id}).select().single();if(Je)throw Je;rt=Ke.id}if(W.length>0){const Ke=W.map((Je,ft)=>({brief_id:rt,title:Je.title,url:Je.url,sort_order:ft}));await q.from("levelup_brief_links").insert(Ke)}for(let Ke=0;Ke0){const es=Je.options.map((Ht,as)=>({poll_id:ft.id,option_text:Ht,sort_order:as}));await q.from("levelup_brief_poll_options").insert(es)}}ne.success(o?"Brief updated":"Brief created"),l(!1),ue(),fe()}catch(rt){console.error("Error saving brief:",rt),ne.error("Failed to save brief")}},Fe=async rt=>{if(await mo("Are you sure you want to delete this brief?"))try{const{error:Ke}=await q.from("levelup_briefs").delete().eq("id",rt);if(Ke)throw Ke;ne.success("Brief deleted"),fe()}catch(Ke){console.error("Error deleting brief:",Ke),ne.error("Failed to delete brief")}},Ne=async rt=>{m(rt);const{count:Ke}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",rt.id),{count:Je}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",rt.id).not("dismissed_at","is",null);ve({total:Ke||0,dismissed:Je||0});const{data:ft}=await q.from("levelup_brief_polls").select("*").eq("brief_id",rt.id).order("sort_order");if(ft){const gt=[];for(const es of ft){const{data:Ht}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",es.id).order("sort_order"),{data:as}=await q.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",es.id),bs=[...new Set((as==null?void 0:as.map(zs=>zs.user_id))||[])];let Ut={};if(bs.length>0){const{data:zs}=await q.from("profiles").select("id, name, email").in("id",bs);zs&&zs.forEach(yt=>{Ut[yt.id]=yt.name||yt.email||"Unknown"})}const Ft=(as||[]).map(zs=>({optionId:zs.option_id,userName:Ut[zs.user_id]||"Unknown",userId:zs.user_id})),is={};let jt=0;Ht&&Ht.forEach(zs=>{const yt=(as==null?void 0:as.filter(gs=>gs.option_id===zs.id).length)||0;is[zs.id]=yt,jt+=yt}),gt.push({...es,options:Ht||[],results:is,respondents:Ft,totalResponses:es.poll_type==="single"?new Set(as==null?void 0:as.map(zs=>zs.user_id)).size:jt})}J(gt)}u(!0)},Be=()=>{V([...W,{title:"",url:""}])},Se=(rt,Ke,Je)=>{const ft=[...W];ft[rt][Ke]=Je,V(ft)},Ae=rt=>{V(W.filter((Ke,Je)=>Je!==rt))},Ce=()=>{Z([...G,{question:"",poll_type:"single",options:["",""]}])},qe=(rt,Ke)=>{const Je=[...G];Je[rt].question=Ke,Z(Je)},ze=(rt,Ke)=>{const Je=[...G];Je[rt].poll_type=Ke,Z(Je)},Ve=rt=>{const Ke=[...G];Ke[rt].options.push(""),Z(Ke)},ht=(rt,Ke,Je)=>{const ft=[...G];ft[rt].options[Ke]=Je,Z(ft)},Qe=(rt,Ke)=>{const Je=[...G];Je[rt].options=Je[rt].options.filter((ft,gt)=>gt!==Ke),Z(Je)},at=rt=>{Z(G.filter((Ke,Je)=>Je!==rt))};return e.jsxs(Vs,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Dm,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs($,{onClick:be,children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(je,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:r?e.jsx(An,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(rt=>e.jsxs(An,{children:[e.jsx(wt,{className:"font-medium",children:rt.title}),e.jsx(wt,{children:e.jsx($e,{variant:rt.is_published?"default":"secondary",children:rt.is_published?"Published":"Draft"})}),e.jsx(wt,{className:"capitalize",children:rt.show_frequency.replace("_"," ")}),e.jsx(wt,{children:Js(new Date(rt.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:()=>Ne(rt),children:e.jsx(Gl,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Ee(rt),children:e.jsx(bp,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Fe(rt.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},rt.id))})]})})})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(pa,{defaultValue:"content",className:"w-full",children:[e.jsxs(ga,{className:"grid w-full grid-cols-4",children:[e.jsx(Xt,{value:"content",children:"Content"}),e.jsx(Xt,{value:"media",children:"Media"}),e.jsx(Xt,{value:"links",children:"Links"}),e.jsx(Xt,{value:"polls",children:"Polls"})]}),e.jsxs(Qt,{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:rt=>g(rt.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(kk,{content:x,onChange:rt=>v(rt),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:rt=>D(rt.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(jn,{checked:I,onCheckedChange:P}),e.jsx(ee,{children:"Publish immediately"})]})]}),e.jsxs(Qt,{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:ke,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:y,onChange:rt=>b(rt.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),y&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:y,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 rt=>{var Je;const Ke=(Je=rt.target.files)==null?void 0:Je[0];if(Ke){re(!0);try{const ft=Ke.name.split(".").pop(),gt=`brief-graphics/${Date.now()}.${ft}`,{error:es}=await q.storage.from("banner-images").upload(gt,Ke,{upsert:!0});if(es)throw es;const{data:Ht}=q.storage.from("banner-images").getPublicUrl(gt);S(Ht.publicUrl),ne.success("Image uploaded!")}catch(ft){console.error(ft),ne.error("Failed to upload image")}finally{re(!1)}}},disabled:le})}),le&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Or paste Image URL"}),e.jsx(pe,{value:w,onChange:rt=>S(rt.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:A,onChange:rt=>E(rt.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(Qt,{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:Be,children:[e.jsx(cn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),W.map((rt,Ke)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(pe,{value:rt.title,onChange:Je=>Se(Ke,"title",Je.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(pe,{value:rt.url,onChange:Je=>Se(Ke,"url",Je.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Ae(Ke),children:e.jsx(qn,{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(Qt,{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(cn,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),G.map((rt,Ke)=>e.jsx(je,{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:rt.question,onChange:Je=>qe(Ke,Je.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(ms,{value:rt.poll_type,onValueChange:Je=>ze(Ke,Je),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:()=>at(Ke),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[rt.options.map((Je,ft)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:Je,onChange:gt=>ht(Ke,ft,gt.target.value),placeholder:`Option ${ft+1}`}),rt.options.length>2&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Qe(Ke,ft),children:e.jsx(qn,{className:"h-4 w-4 text-muted-foreground"})})]},ft)),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>Ve(Ke),children:[e.jsx(cn,{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:Ie,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(Os,{open:d,onOpenChange:u,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs($s,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(Le,{children:e.jsx("p",{className:"text-2xl font-bold",children:ce.total})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(Le,{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(rt=>e.jsxs(je,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:rt.question}),e.jsx("div",{className:"space-y-2",children:rt.options.map(Ke=>{const Je=rt.results[Ke.id]||0,ft=rt.totalResponses>0?Math.round(Je/rt.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:[Je," (",ft,"%)"]})]}),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:`${ft}%`}})}),Je>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(rt.respondents||[]).filter(gt=>gt.optionId===Ke.id).map((gt,es)=>e.jsx($e,{variant:"secondary",className:"text-xs font-normal",children:gt.userName},es))})]},Ke.id)})})]},rt.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const qDn=()=>{const{user:s}=_s(),{toast:t}=Bi(),n=Zt(),[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}=st({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:A,error:E}=await q.from("additional_services").select("*").order("publish_date",{ascending:!1});if(E)throw E;return A}}),x=mt({mutationFn:async A=>{let E=A.existingImageUrl;if(A.image){const P=A.image.name.split(".").pop(),R=`${Date.now()}-${Math.random().toString(36).substring(7)}.${P}`,{error:D}=await q.storage.from("service-images").upload(R,A.image);if(D)throw D;const{data:O}=q.storage.from("service-images").getPublicUrl(R);E=O.publicUrl}const I={name:A.item.name,description:A.item.description||null,preview_image_url:E,signup_link_url:A.item.signup_link_url,publish_date:A.item.publish_date?new Date(A.item.publish_date).toISOString():new Date().toISOString(),is_published:A.item.is_published,created_by:s==null?void 0:s.id};if(A.itemId){const{error:P}=await q.from("additional_services").update(I).eq("id",A.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),y()},onError:A=>{t({title:"Error saving service",description:A.message,variant:"destructive"})}}),v=mt({mutationFn:async A=>{const{error:E}=await q.from("additional_services").delete().eq("id",A);if(E)throw E},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:"Service deleted"})},onError:A=>{t({title:"Error deleting service",description:A.message,variant:"destructive"})}}),y=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),m(""),l(null)},b=A=>{l(A),c({name:A.name,description:A.description||"",signup_link_url:A.signup_link_url,publish_date:A.publish_date?new Date(A.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:A.is_published}),m(A.preview_image_url||""),a(!0)},w=A=>{var I;const E=(I=A.target.files)==null?void 0:I[0];E&&(u(E),m(URL.createObjectURL(E)))},S=A=>{if(A.preventDefault(),!o.name.trim()){t({title:"Name is required",variant:"destructive"});return}if(!o.signup_link_url.trim()){t({title:"Signup link URL is required",variant:"destructive"});return}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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.length})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(A=>A.is_published).length})})]})]}),e.jsxs(Os,{open:r,onOpenChange:A=>{a(A),A||y()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(cn,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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:A=>c({...o,name:A.target.value}),placeholder:"Enter service name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(kk,{content:o.description,onChange:A=>c({...o,description:A}),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:A=>c({...o,signup_link_url:A.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:A=>c({...o,publish_date:A.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(jn,{id:"is_published",checked:o.is_published,onCheckedChange:A=>c({...o,is_published:A})}),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(mr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(Hc,{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(je,{children:e.jsx(Le,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:f.map(A=>e.jsxs(An,{children:[e.jsx(wt,{children:A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(Hc,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(wt,{className:"font-medium",children:A.name}),e.jsx(wt,{children:e.jsxs("a",{href:A.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(Ir,{className:"h-3 w-3"}),"Link"]})}),e.jsx(wt,{children:new Date(A.publish_date).toLocaleDateString()}),e.jsx(wt,{children:e.jsx($e,{variant:A.is_published?"default":"secondary",children:A.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(A),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await mo("Are you sure you want to delete this service?")&&v.mutate(A.id)},children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},A.id))})]})})})]})})};function VDn(){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:v,error:y}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(y)throw y;n(v.coupons||[])}catch(v){console.error("Error fetching coupons:",v),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 v={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?v.percent_off=parseFloat(d.percentOff):(v.amount_off=Math.round(parseFloat(d.amountOff)*100),v.currency="usd"),d.duration==="repeating"&&(v.duration_in_months=parseInt(d.durationInMonths));const{data:y,error:b}=await q.functions.invoke("stripe-manage-coupons",{body:v});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(v){console.error("Error creating coupon:",v),s({title:"Error",description:v.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},f=async v=>{if(await mo("Are you sure you want to delete this coupon?"))try{const{error:y}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:v}});if(y)throw y;s({title:"Success",description:"Coupon deleted successfully"}),h()}catch(y){console.error("Error deleting coupon:",y),s({title:"Error",description:y.message||"Failed to delete coupon",variant:"destructive"})}},g=v=>v.percent_off?`${v.percent_off}% off`:v.amount_off?`$${(v.amount_off/100).toFixed(2)} off`:"N/A",x=v=>{switch(v.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${v.duration_in_months} months`;default:return v.duration}};return e.jsx(Vs,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Dm,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(Os,{open:o,onOpenChange:c,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(cn,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Create New Coupon"}),e.jsx(Er,{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:v=>u({...d,promotionCode:v.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:v=>u({...d,name:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Discount Type"}),e.jsxs(ms,{value:d.discountType,onValueChange:v=>{const y=v==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:v,duration:y})},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(Aw,{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(su,{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:v=>u({...d,percentOff:v.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:v=>u({...d,amountOff:v.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Duration"}),e.jsxs(ms,{value:d.duration,onValueChange:v=>u({...d,duration:v}),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:v=>u({...d,durationInMonths:v.target.value})})]}),e.jsx($,{onClick:m,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Active Coupons"}),e.jsx(Vn,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Le,{children:r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:t.map(v=>{var y;return e.jsxs(An,{children:[e.jsx(wt,{className:"font-mono font-medium",children:((y=v.promotion_codes)==null?void 0:y.length)>0?v.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(wt,{children:v.name||"-"}),e.jsx(wt,{children:g(v)}),e.jsx(wt,{children:x(v)}),e.jsx(wt,{children:v.times_redeemed}),e.jsx(wt,{children:e.jsx($e,{variant:v.valid?"default":"secondary",children:v.valid?"Active":"Inactive"})}),e.jsx(wt,{className:"text-right",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>f(v.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})})]},v.id)})})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"How to Use Coupons"})}),e.jsxs(Le,{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 A9e={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 HDn(){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}=st({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:y,error:b}=await q.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(b)throw b;return y}}),{data:h}=st({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:y,error:b}=await q.from("brokerages").select("*").order("name");if(b)throw b;return await Promise.all((y||[]).map(async S=>{const{data:A}=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=(A==null?void 0:A.filter(D=>I.includes(D.id)))||[],R=(A==null?void 0:A.length)||0;return{...S,managers:P,agentCount:R}}))}}),{data:m}=st({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:y,error:b}=await q.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(b)throw b;return y}}),f=y=>{if(y.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(y.brokerage_id&&!y.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(y.is_trial&&y.trial_expires_at)return new Date(y.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(y.subscription_status==="active"||y.subscription_status==="trialing"){const b=A9e[y.subscription_product_id];return{status:(b==null?void 0:b.name)||"Active",badge:y.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return y.subscription_status==="canceled"||y.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},g=c==null?void 0:c.filter(y=>{var w,S;if(!(((w=y.name)==null?void 0:w.toLowerCase().includes(s.toLowerCase()))||((S=y.email)==null?void 0:S.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const A=y.subscription_source||"platform";if(a==="platform"&&A==="local_move_website"||a==="local_move_website"&&A!=="local_move_website")return!1}switch(f(y),n){case"active":return y.subscription_status==="active";case"trialing":return y.subscription_status==="trialing"||y.is_trial&&new Date(y.trial_expires_at)>new Date;case"grandfathered":return y.is_grandfathered;case"brokerage":return y.brokerage_id&&!y.subscription_product_id&&!y.is_grandfathered;case"expired":return y.subscription_status==="canceled"||y.subscription_status==="past_due"||y.is_trial&&new Date(y.trial_expires_at)<=new Date;case"none":return!y.subscription_status||y.subscription_status==="none";default:return!0}}),x={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(y=>y.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(y=>y.subscription_status==="trialing"||y.is_trial&&new Date(y.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(y=>y.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(y=>y.brokerage_id&&!y.subscription_product_id&&!y.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(y=>y.subscription_status==="active"&&y.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(y=>y.subscription_status==="active"&&(y.subscription_product_id==="prod_Tc08MupgoVySDG"||y.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},v=y=>{window.open(`https://dashboard.stripe.com/customers/${y}`,"_blank")};return e.jsx(Vs,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Dm,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs($,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(co,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{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(je,{className:"border-green-500/50",children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jv,{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(je,{className:"border-blue-500/50",children:e.jsxs(Le,{className:"pt-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:"Trials"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-blue-600",children:x.trials})]})}),e.jsx(je,{className:"border-purple-500/50",children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Og,{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(je,{className:"border-orange-500/50",children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wi,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(u2,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wi,{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(pa,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"users",children:"All Users"}),e.jsx(Xt,{value:"brokerages",children:"Brokerages"}),e.jsxs(Xt,{value:"websites",className:"gap-2",children:[e.jsx(cl,{className:"h-4 w-4"}),"Website Subscriptions",m&&m.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1",children:m.length})]})]}),e.jsxs(Qt,{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:y=>t(y.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:a,onValueChange:y=>i(y),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:y=>r(y),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(je,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:d?e.jsx(An,{children:e.jsx(wt,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(g==null?void 0:g.length)===0?e.jsx(An,{children:e.jsx(wt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):g==null?void 0:g.map(y=>{var S,A;const b=f(y),w=A9e[y.subscription_product_id];return e.jsxs(An,{children:[e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:y.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:y.email})]})}),e.jsx(wt,{children:e.jsx($e,{variant:b.variant,children:b.badge})}),e.jsx(wt,{children:e.jsx("span",{className:"text-sm",children:y.is_grandfathered?"Legacy Access":y.brokerage_id&&!y.subscription_product_id?"Brokerage Subscription":(w==null?void 0:w.name)||b.status})}),e.jsx(wt,{children:(S=y.brokerages)!=null&&S.name?e.jsx("span",{className:"text-sm",children:y.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(wt,{children:y.subscription_end_date?e.jsx("span",{className:"text-sm",children:Js(new Date(y.subscription_end_date),"MMM d, yyyy")}):y.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",Js(new Date(y.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:[y.stripe_customer_id&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>v(y.stripe_customer_id),children:e.jsx(Ir,{className:"h-4 w-4"})}),e.jsxs(Os,{children:[e.jsx(jl,{asChild:!0,children:e.jsx($,{variant:"outline",size:"sm",onClick:()=>o(y),children:"Details"})}),e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Subscription Details"}),e.jsxs(Er,{children:[y.name," (",y.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($e,{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:y.is_grandfathered?"Grandfathered (Legacy)":y.brokerage_id&&!y.subscription_product_id?"Brokerage Subscription":(w==null?void 0:w.name)||"None"})]}),y.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((A=y.brokerages)==null?void 0:A.name)||"Unknown"})]}),y.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:Js(new Date(y.subscription_end_date),"MMMM d, yyyy")})]}),y.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:Js(new Date(y.trial_expires_at),"MMMM d, yyyy")})]}),y.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:y.stripe_customer_id})]})]}),y.stripe_customer_id&&e.jsxs($,{className:"w-full",onClick:()=>v(y.stripe_customer_id),children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},y.id)})})]})})})]}),e.jsx(Qt,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(y=>{var w,S;const b=(w=y.managers)==null?void 0:w.some(A=>A.subscription_status==="active"&&(A.subscription_product_id==="prod_Tc08MupgoVySDG"||A.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(je,{children:[e.jsx(St,{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(wi,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:y.name}),e.jsxs(Vn,{children:[y.agentCount," agents"]})]})]}),e.jsx($e,{variant:b?"default":"outline",children:b?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Le,{children:((S=y.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:"}),y.managers.map(A=>{const E=A9e[A.subscription_product_id];return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:A.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:A.email})]}),e.jsx("div",{className:"text-right",children:E?e.jsxs("div",{children:[e.jsx($e,{variant:"default",children:E.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:E.price})]}):e.jsx($e,{variant:"outline",children:"No Subscription"})})]},A.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},y.id)})})}),e.jsx(Qt,{value:"websites",className:"space-y-4",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(cl,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(Vn,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Le,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:m?m.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):m.map(y=>e.jsxs(An,{children:[e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:y.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:y.agent_email})]})}),e.jsx(wt,{children:e.jsx($e,{variant:y.status==="active"?"default":y.status==="canceled"?"destructive":"outline",children:y.status})}),e.jsx(wt,{children:y.setup_fee_paid?e.jsxs($e,{variant:"secondary",children:["Paid · $",(y.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx($e,{variant:"outline",children:"Unpaid"})}),e.jsxs(wt,{className:"font-medium",children:["$",(y.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(wt,{children:y.current_period_end?e.jsx("span",{className:"text-sm",children:Js(new Date(y.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:Js(new Date(y.created_at),"MMM d, yyyy")})}),e.jsx(wt,{className:"text-right",children:y.stripe_customer_id&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>v(y.stripe_customer_id),children:e.jsx(Ir,{className:"h-4 w-4"})})})]},y.id)):e.jsx(An,{children:e.jsx(wt,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function GDn(){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 v=(g==null?void 0:g.filter(w=>w.status==="qualified").length)||0,y=(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:v,pending:y,cancelled:b,totalDiscounts:v*25})}catch(g){console.error("Error fetching referrals:",g),ne.error("Failed to load referrals")}finally{r(!1)}},h=async()=>{try{ne.loading("Processing qualifications...");const{error:g}=await q.functions.invoke("process-referral-qualifications");if(g)throw g;ne.dismiss(),ne.success("Qualifications processed successfully"),u()}catch(g){ne.dismiss(),console.error("Error processing qualifications:",g),ne.error("Failed to process qualifications")}},m=s.filter(g=>{var y,b,w,S,A,E;const x=((b=(y=g.referrer_brokerage)==null?void 0:y.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=(A=g.referred_user)==null?void 0:A.email)==null?void 0:E.toLowerCase().includes(a.toLowerCase())),v=l==="all"||g.status===l;return x&&v}),f=g=>{switch(g){case"qualified":return e.jsxs($e,{className:"bg-green-100 text-green-800",children:[e.jsx(Wl,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs($e,{variant:"secondary",children:[e.jsx(ca,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs($e,{variant:"destructive",children:[e.jsx(ju,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx($e,{children:g})}};return e.jsx(Vs,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Dm,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs($,{onClick:h,variant:"outline",children:[e.jsx(co,{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(je,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{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(je,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wl,{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(je,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ca,{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(je,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ju,{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(je,{children:e.jsx(Le,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(su,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"All Referrals"}),e.jsx(Vn,{children:"View and manage all referral relationships"})]}),e.jsxs(Le,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:m.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):m.map(g=>{var x,v,y,b;return e.jsxs(An,{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:((v=g.referred_brokerage)==null?void 0:v.name)||((y=g.referred_user)==null?void 0:y.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:Js(new Date(g.signup_date),"MMM d, yyyy")}),e.jsx(wt,{children:f(g.status)}),e.jsx(wt,{children:g.qualified_date?Js(new Date(g.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(wt,{children:g.discount_applied?e.jsx($e,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},g.id)})})]})]})]})]})})}const E9e=[{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"}],WDn=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function KDn(){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),ne.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()){ne.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;ne.success("Checklist item updated")}else{const b=s.filter(S=>S.target_role===c.target_role).reduce((S,A)=>Math.max(S,A.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;ne.success("Checklist item created")}i(!1),u()}catch(b){console.error("Error saving checklist item:",b),ne.error("Failed to save checklist item")}},g=async b=>{if(await mo("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;ne.success("Checklist item deleted"),u()}catch(w){console.error("Error deleting checklist item:",w),ne.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;ne.success(b.is_active?"Item deactivated":"Item activated"),u()}catch(w){console.error("Error toggling item:",w),ne.error("Failed to update item")}},v=s.filter(b=>b.target_role==="brokerage_manager"),y=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(cn,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx($e,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Le,{children:v.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:v.map((b,w)=>{var S;return e.jsxs(An,{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($e,{variant:"outline",children:((S=E9e.find(A=>A.value===b.action_type))==null?void 0:S.label)||b.action_type})}),e.jsx(wt,{children:e.jsx(jn,{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(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(b.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx($e,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Le,{children:y.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:y.map((b,w)=>{var S;return e.jsxs(An,{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($e,{variant:"outline",children:((S=E9e.find(A=>A.value===b.action_type))==null?void 0:S.label)||b.action_type})}),e.jsx(wt,{children:e.jsx(jn,{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(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(b.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]})]}),e.jsx(Os,{open:a,onOpenChange:i,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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:WDn.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:E9e.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(jn,{id:"is_active",checked:c.is_active,onCheckedChange:b=>d({...c,is_active:b})}),e.jsx(ee,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx($,{onClick:f,children:l?"Save Changes":"Create Item"})]})]})})]})}function YDn(){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:v}=st({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}}),y=async D=>{let U=[],W=0,V=!0;for(;V;){const{data:G,error:Z}=await D(W,W+1e3-1);if(Z)throw Z;G&&G.length>0?(U=[...U,...G],W+=1e3,V=G.length===1e3):V=!1}return U},{data:b,isLoading:w}=st({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const D=await y((Ee,ke)=>q.from("profiles").select("id, name, email, brokerage_id, created_at").range(Ee,ke)),{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:Z},{data:X},{data:ae},{data:le}]=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")]),re=new Map;W==null||W.forEach(Ee=>re.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;Z==null||Z.forEach(Ee=>ce.set(Ee.agent_id,Ee.listing_count));const ve=new Map;X==null||X.forEach(Ee=>ve.set(Ee.owner_user_id,Ee.deal_count));const fe=new Map;ae==null||ae.forEach(Ee=>fe.set(Ee.owner_user_id,{total:Ee.portal_count,active:Ee.active_portal_count}));const ue=new Map;return le==null||le.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 ke=fe.get(Ee.id),Ie=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:re.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:ve.get(Ee.id)||0,portal_count:(ke==null?void 0:ke.total)||0,active_portal_count:(ke==null?void 0:ke.active)||0,card_count:(Ie==null?void 0:Ie.total)||0,sent_card_count:(Ie==null?void 0:Ie.sent)||0,total_card_views:(Ie==null?void 0:Ie.views)||0,created_at: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,Z=parseInt(u)||0,X=parseInt(m)||0,ae=parseInt(g)||0,le=O.contact_count>=G&&O.video_count>=Z&&O.popby_count>=X&&O.listing_count>=ae;return W&&V&&le});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]),A=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(Z=>[Z.name,Z.email,Z.brokerage_name||"None",Z.contact_count,Z.video_count,Z.popby_count,Z.listing_count,Z.deal_count,`${Z.portal_count} (${Z.active_portal_count})`,Z.card_count,Z.sent_card_count,Z.total_card_views]),U=[D.join(","),...O.map(Z=>Z.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:()=>A(D),children:e.jsxs("div",{className:"flex items-center gap-1",children:[O,e.jsx(Dy,{className:`h-3 w-3 ${a===D?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(vk,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(je,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(WN,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Le,{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(je,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(pn,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(Le,{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(je,{children:[e.jsx(St,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(Vn,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:E,children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Le,{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(wi,{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"}),v==null?void 0:v.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(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(WN,{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(pn,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(fi,{children:S.length===0?e.jsx(An,{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(An,{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($e,{variant:"secondary",children:D.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(wt,{children:e.jsx($e,{variant:D.contact_count>0?"default":"outline",children:D.contact_count})}),e.jsx(wt,{children:e.jsx($e,{variant:D.video_count>0?"default":"outline",children:D.video_count})}),e.jsx(wt,{children:e.jsx($e,{variant:D.popby_count>0?"default":"outline",children:D.popby_count})}),e.jsx(wt,{children:e.jsx($e,{variant:D.listing_count>0?"default":"outline",children:D.listing_count})}),e.jsx(wt,{children:e.jsx($e,{variant:D.deal_count>0?"default":"outline",children:D.deal_count})}),e.jsx(wt,{children:D.portal_count>0?e.jsxs(ry,{children:[e.jsx(ay,{children:e.jsxs($e,{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(vx,{children:[e.jsxs("p",{children:[D.portal_count," total portals"]}),e.jsxs("p",{children:[D.active_portal_count," currently active"]})]})]}):e.jsx($e,{variant:"outline",children:"0"})}),e.jsx(wt,{children:D.card_count>0?e.jsxs(ry,{children:[e.jsx(ay,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx($e,{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(Zr,{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(Ta,{className:"h-3 w-3"}),D.total_card_views]})]})}),e.jsxs(vx,{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($e,{variant:"outline",children:"0"})})]},D.id))})]})})]})]})]})})}function ZDn(){Bi(),Zt();const[s,t]=j.useState("user-analytics"),{data:n}=st({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}=st({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}=st({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}=st({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}=st({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}=st({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(Dm,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(pa,{value:s,onValueChange:t,children:[e.jsxs(ga,{className:"grid w-full grid-cols-9",children:[e.jsxs(Xt,{value:"user-analytics",className:"gap-2",children:[e.jsx(Gl,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Xt,{value:"relationship-types",className:"gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(Xt,{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(Xt,{value:"scripts",className:"gap-2",children:[e.jsx(Qr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(Xt,{value:"video-scripts",className:"gap-2",children:[e.jsx(nf,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(Xt,{value:"plans",className:"gap-2",children:[e.jsx(Ea,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(Xt,{value:"popbys",className:"gap-2",children:[e.jsx(dl,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(Xt,{value:"settings",className:"gap-2",children:[e.jsx(Nd,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(Xt,{value:"feature-flags",className:"gap-2",children:[e.jsx(CE,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(Qt,{value:"user-analytics",className:"mt-6",children:e.jsx(YDn,{})}),e.jsx(Qt,{value:"relationship-types",className:"mt-6",children:e.jsx(XDn,{types:r||[],isLoading:a})}),e.jsx(Qt,{value:"action-types",className:"mt-6",children:e.jsx(QDn,{types:i||[],isLoading:l})}),e.jsx(Qt,{value:"scripts",className:"mt-6",children:e.jsx(JDn,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(Qt,{value:"video-scripts",className:"mt-6",children:e.jsx(nFn,{})}),e.jsx(Qt,{value:"plans",className:"mt-6",children:e.jsx(eFn,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(Qt,{value:"popbys",className:"mt-6",children:e.jsx(sFn,{items:h||[],isLoading:m})}),e.jsx(Qt,{value:"settings",className:"mt-6",children:e.jsx(rFn,{})}),e.jsx(Qt,{value:"feature-flags",className:"mt-6",children:e.jsx(tFn,{flags:n||[]})})]})]})})}function XDn({types:s,isLoading:t}){const{toast:n}=Bi(),r=Zt(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=mt({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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Et,{children:"Relationship Types"}),e.jsx(Vn,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Le,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:s.map(u=>e.jsxs(An,{children:[e.jsx(wt,{children:e.jsx(zg,{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(jn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(wt,{children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(pi,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsxs($s,{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(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function QDn({types:s,isLoading:t}){const{toast:n}=Bi(),r=Zt(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=mt({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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Et,{children:"Action Types"}),e.jsx(Vn,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Le,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:s.map(u=>e.jsxs(An,{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(jn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(wt,{children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(pi,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsxs($s,{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(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function JDn({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=Bi(),a=Zt(),[i,l]=j.useState(null),[o,c]=j.useState(!1),d=mt({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=mt({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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Et,{children:"Script Library"}),e.jsx(Vn,{children:"Create and manage scripts for each action type"})]}),e.jsxs($,{onClick:()=>{l(null),c(!0)},children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Le,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:s.map(h=>{var m;return e.jsxs(An,{children:[e.jsx(wt,{className:"font-medium",children:h.title}),e.jsx(wt,{children:e.jsx($e,{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($e,{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(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u.mutate(h.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs($s,{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(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function eFn({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=Bi(),i=Zt(),[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),[v,y]=j.useState(null),{data:b}=st({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=mt({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=mt({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"})}}),A=mt({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=mt({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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Et,{children:"Touchpoint Plans"}),e.jsx(Vn,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs($,{onClick:()=>{o(null),d(!0)},children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Le,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{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(je,{className:`cursor-pointer transition-colors ${u===R.id?"border-primary":""}`,onClick:()=>h(R.id),children:[e.jsx(St,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Et,{className:"text-base",children:R.name}),e.jsx($,{variant:"ghost",size:"icon",onClick:D=>{D.stopPropagation(),o(R),d(!0)},children:e.jsx(pi,{className:"h-4 w-4"})})]})}),e.jsxs(Le,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:R.description}),e.jsx($e,{variant:R.active?"default":"secondary",className:"mt-2",children:R.active?"Active":"Inactive"})]})]},R.id))})})]}),u&&e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Plan Schedule"}),e.jsx(Vn,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Le,{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?A.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=>{y(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(cn,{className:"h-3 w-3 mr-1"}),"New Script"]}),O&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y((v==null?void 0:v.id)===O.id?null:O),children:(v==null?void 0:v.id)===O.id?"Hide":"Preview"})]})]}),v&&(D==null?void 0:D.default_script_id)===v.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($e,{variant:"outline",children:v.title}),v.tone&&e.jsx($e,{variant:"secondary",children:v.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:v.script_body})]})]},R)})})})]}),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsxs($s,{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(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(Os,{open:m,onOpenChange:f,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Create New Script"}),e.jsxs(Er,{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(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function tFn({flags:s}){const{toast:t}=Bi(),n=Zt(),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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Feature Flags"}),e.jsx(Vn,{children:"Control which features are enabled for members"})]}),e.jsx(Le,{children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{children:"Flag"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Notes"}),e.jsx(Dt,{children:"Last Updated"})]})}),e.jsx(fi,{children:s.map(a=>e.jsxs(An,{children:[e.jsx(wt,{className:"font-mono text-sm",children:a.key}),e.jsx(wt,{children:e.jsx(jn,{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 sFn({items:s,isLoading:t}){const{toast:n}=Bi(),r=Zt(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=mt({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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Et,{children:"Popby Ideas"}),e.jsx(Vn,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Le,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{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(dl,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:s.map(h=>e.jsxs(An,{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(jn,{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(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u(h.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsxs($s,{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(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function nFn(){var f;const{toast:s}=Bi(),t=Zt(),[n,r]=j.useState(null),[a,i]=j.useState(!1),{data:l,isLoading:o}=st({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}=st({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=mt({mutationFn:async g=>{var x,v;if(g.id){const{error:y}=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(y)throw y}else{const{error:y}=await q.from("video_scripts").insert([{title:g.title,script_text:g.script_text,category_id:g.category_id||null,tags:((v=g.tags)==null?void 0:v.split(",").map(b=>b.trim()).filter(Boolean))||[]}]);if(y)throw y}},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 mo("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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Et,{children:"Video Scripts"}),e.jsx(Vn,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs($,{onClick:()=>{r(null),i(!0)},children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Le,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:c==null?void 0:c.map(g=>{var x;return e.jsxs(An,{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(jn,{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(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(g.id),children:e.jsx(qn,{className:"h-4 w-4"})})]})]},g.id)})})]})}),e.jsx(Os,{open:a,onOpenChange:i,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs($s,{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(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function rFn(){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(je,{children:e.jsx(Le,{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(ui,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(Vn,{children:"Configure the map feature for popbys"})]}),e.jsxs(Le,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx($e,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const aFn=()=>{const[s,t]=j.useState(""),[n,r]=j.useState("grid"),a=Zn(),{data:i=[],isLoading:l}=st({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(Xf,{className:"h-4 w-4"})}),e.jsx($,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(E0,{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(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx(xn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(xn,{className:"h-5 w-3/4 mb-2"}),e.jsx(xn,{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(je,{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(wn,{className:"h-8 w-8"})})}),e.jsxs(Le,{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:Fte(c.description)})]})]},c.id))})]})})},iFn=()=>{const{serviceId:s}=Wi(),t=Zn(),{data:n,isLoading:r}=st({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(xn,{className:"h-8 w-48"}),e.jsx(xn,{className:"h-64 w-full rounded-lg"}),e.jsx(xn,{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(Va,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(je,{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(wn,{className:"h-16 w-16"})})})}),e.jsx(je,{children:e.jsxs(Le,{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(Ea,{className:"h-4 w-4 mr-1"}),"Published ",Js(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(Ir,{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(Va,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},QZ=[{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 oFn(){const[s,t]=j.useState(QZ[0].id),n=QZ.find(r=>r.id===s)||QZ[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(A4,{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:QZ.map(r=>e.jsx(Ge,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(pa,{value:s,onValueChange:t,className:"w-full",children:e.jsx(ga,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:QZ.map(r=>e.jsx(Xt,{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 lFn(s,t){const n={};return(s[s.length-1]===""?[...s,""]:s).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const cFn=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,dFn=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,uFn={};function sSt(s,t){return(uFn.jsx?dFn:cFn).test(s)}const hFn=/[ \t\n\f\r]/g;function mFn(s){return typeof s=="object"?s.type==="text"?nSt(s.value):!1:nSt(s)}function nSt(s){return s.replace(hFn,"")===""}class Eie{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Eie.prototype.normal={};Eie.prototype.property={};Eie.prototype.space=void 0;function TXt(s,t){const n={},r={};for(const a of s)Object.assign(n,a.property),Object.assign(r,a.normal);return new Eie(n,r,t)}function pYe(s){return s.toLowerCase()}class Vw{constructor(t,n){this.attribute=n,this.property=t}}Vw.prototype.attribute="";Vw.prototype.booleanish=!1;Vw.prototype.boolean=!1;Vw.prototype.commaOrSpaceSeparated=!1;Vw.prototype.commaSeparated=!1;Vw.prototype.defined=!1;Vw.prototype.mustUseProperty=!1;Vw.prototype.number=!1;Vw.prototype.overloadedBoolean=!1;Vw.prototype.property="";Vw.prototype.spaceSeparated=!1;Vw.prototype.space=void 0;let fFn=0;const ed=JB(),Ey=JB(),gYe=JB(),_i=JB(),vf=JB(),y7=JB(),Nj=JB();function JB(){return 2**++fFn}const xYe=Object.freeze(Object.defineProperty({__proto__:null,boolean:ed,booleanish:Ey,commaOrSpaceSeparated:Nj,commaSeparated:y7,number:_i,overloadedBoolean:gYe,spaceSeparated:vf},Symbol.toStringTag,{value:"Module"})),T9e=Object.keys(xYe);class Kat extends Vw{constructor(t,n,r,a){let i=-1;if(super(t,n),rSt(this,"space",a),typeof r=="number")for(;++i4&&n.slice(0,4)==="data"&&vFn.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(aSt,wFn);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!aSt.test(i)){let l=i.replace(yFn,_Fn);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}a=Kat}return new a(r,t)}function _Fn(s){return"-"+s.toLowerCase()}function wFn(s){return s.charAt(1).toUpperCase()}const jFn=TXt([MXt,pFn,LXt,RXt,DXt],"html"),Yat=TXt([MXt,gFn,LXt,RXt,DXt],"svg");function NFn(s){return s.join(" ").trim()}var Zat={},iSt=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,kFn=/\n/g,SFn=/^\s*/,CFn=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,AFn=/^:\s*/,EFn=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,TFn=/^[;\s]*/,MFn=/^\s+|\s+$/g,PFn=` `,oSt="/",lSt="*",WO="",IFn="comment",LFn="declaration";function RFn(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(kFn);x&&(n+=x.length);var v=g.lastIndexOf(PFn);r=~v?g.length-v: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 v=x[0];return a(v),s=s.slice(v.length),x}}function d(){c(SFn)}function u(g){var x;for(g=g||[];x=h();)x!==!1&&g.push(x);return g}function h(){var g=i();if(!(oSt!=s.charAt(0)||lSt!=s.charAt(1))){for(var x=2;WO!=s.charAt(x)&&(lSt!=s.charAt(x)||oSt!=s.charAt(x+1));)++x;if(x+=2,WO===s.charAt(x-1))return o("End of comment missing");var v=s.slice(2,x-2);return r+=2,a(v),s=s.slice(x),r+=2,g({type:IFn,comment:v})}}function m(){var g=i(),x=c(CFn);if(x){if(h(),!c(AFn))return o("property missing ':'");var v=c(EFn),y=g({type:LFn,property:cSt(x[0].replace(iSt,WO)),value:v?cSt(v[0].replace(iSt,WO)):WO});return c(TFn),y}}function f(){var g=[];u(g);for(var x;x=m();)x!==!1&&(g.push(x),u(g));return g}return d(),f()}function cSt(s){return s?s.replace(MFn,WO):WO}var DFn=RFn,FFn=kp&&kp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Zat,"__esModule",{value:!0});Zat.default=zFn;const OFn=FFn(DFn);function zFn(s,t){let n=null;if(!s||typeof s!="string")return n;const r=(0,OFn.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 XRe={};Object.defineProperty(XRe,"__esModule",{value:!0});XRe.camelCase=void 0;var BFn=/^--[a-zA-Z0-9_-]+$/,$Fn=/-([a-z])/g,UFn=/^[^-]+$/,qFn=/^-(webkit|moz|ms|o|khtml)-/,VFn=/^-(ms)-/,HFn=function(s){return!s||UFn.test(s)||BFn.test(s)},GFn=function(s,t){return t.toUpperCase()},dSt=function(s,t){return"".concat(t,"-")},WFn=function(s,t){return t===void 0&&(t={}),HFn(s)?s:(s=s.toLowerCase(),t.reactCompat?s=s.replace(VFn,dSt):s=s.replace(qFn,dSt),s.replace($Fn,GFn))};XRe.camelCase=WFn;var KFn=kp&&kp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},YFn=KFn(Zat),ZFn=XRe;function yYe(s,t){var n={};return!s||typeof s!="string"||(0,YFn.default)(s,function(r,a){r&&a&&(n[(0,ZFn.camelCase)(r,t)]=a)}),n}yYe.default=yYe;var XFn=yYe;const QFn=ru(XFn),FXt=OXt("end"),Xat=OXt("start");function OXt(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 JFn(s){const t=Xat(s),n=FXt(s);if(t&&n)return{start:t,end:n}}function Hee(s){return!s||typeof s!="object"?"":"position"in s||"type"in s?uSt(s.position):"start"in s||"end"in s?uSt(s):"line"in s||"column"in s?vYe(s):""}function vYe(s){return hSt(s&&s.line)+":"+hSt(s&&s.column)}function uSt(s){return vYe(s&&s.start)+"-"+vYe(s&&s.end)}function hSt(s){return s&&typeof s=="number"?s:1}class E1 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=Hee(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}}E1.prototype.file="";E1.prototype.name="";E1.prototype.reason="";E1.prototype.message="";E1.prototype.stack="";E1.prototype.column=void 0;E1.prototype.line=void 0;E1.prototype.ancestors=void 0;E1.prototype.cause=void 0;E1.prototype.fatal=void 0;E1.prototype.place=void 0;E1.prototype.ruleId=void 0;E1.prototype.source=void 0;const Qat={}.hasOwnProperty,eOn=new Map,tOn=/[A-Z]/g,sOn=new Set(["table","tbody","thead","tfoot","tr"]),nOn=new Set(["td","th"]),zXt="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function rOn(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=hOn(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=uOn(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"?Yat:jFn,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=BXt(a,s,void 0);return i&&typeof i!="string"?i:a.create(s,a.Fragment,{children:i||void 0},void 0)}function BXt(s,t,n){if(t.type==="element")return aOn(s,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return iOn(s,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return lOn(s,t,n);if(t.type==="mdxjsEsm")return oOn(s,t);if(t.type==="root")return cOn(s,t,n);if(t.type==="text")return dOn(s,t)}function aOn(s,t,n){const r=s.schema;let a=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=Yat,s.schema=a),s.ancestors.push(t);const i=UXt(s,t.tagName,!1),l=mOn(s,t);let o=eit(s,t);return sOn.has(t.tagName)&&(o=o.filter(function(c){return typeof c=="string"?!mFn(c):!0})),$Xt(s,l,i,t),Jat(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function iOn(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)}lne(s,t.position)}function oOn(s,t){if(t.data&&t.data.estree&&s.evaluater)return s.evaluater.evaluateProgram(t.data.estree);lne(s,t.position)}function lOn(s,t,n){const r=s.schema;let a=r;t.name==="svg"&&r.space==="html"&&(a=Yat,s.schema=a),s.ancestors.push(t);const i=t.name===null?s.Fragment:UXt(s,t.name,!0),l=fOn(s,t),o=eit(s,t);return $Xt(s,l,i,t),Jat(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function cOn(s,t,n){const r={};return Jat(r,eit(s,t)),s.create(t,s.Fragment,r,n)}function dOn(s,t){return t.value}function $Xt(s,t,n,r){typeof n!="string"&&n!==s.Fragment&&s.passNode&&(t.node=r)}function Jat(s,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(s.children=n)}}function uOn(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 hOn(s,t){return n;function n(r,a,i,l){const o=Array.isArray(i.children),c=Xat(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 mOn(s,t){const n={};let r,a;for(a in t.properties)if(a!=="children"&&Qat.call(t.properties,a)){const i=pOn(s,a,t.properties[a]);if(i){const[l,o]=i;s.tableCellAlignToStyle&&l==="align"&&typeof o=="string"&&nOn.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 fOn(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 lne(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 lne(s,t.position);else i=r.value===null?!0:r.value;n[a]=i}return n}function eit(s,t){const n=[];let r=-1;const a=s.passKeys?new Map:eOn;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?(X4(s,s.length,0,t),s):t}const pSt={}.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 AV(s){return s.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const c4=N6(/[A-Za-z]/),Xj=N6(/[\dA-Za-z]/),SOn=N6(/[#-'*+\--9=?A-Z^-~]/);function bYe(s){return s!==null&&(s<32||s===127)}const _Ye=N6(/\d/),COn=N6(/[\dA-Fa-f]/),AOn=N6(/[!-/:-@[-`{-~]/);function Fc(s){return s!==null&&s<-2}function Iw(s){return s!==null&&(s<0||s===32)}function nm(s){return s===-2||s===-1||s===32}const EOn=N6(new RegExp("\\p{P}|\\p{S}","u")),TOn=N6(/\s/);function N6(s){return t;function t(n){return n!==null&&n>-1&&s.test(String.fromCharCode(n))}}function LK(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 Kf(s,t,n,r){const a=r?r-1:Number.POSITIVE_INFINITY;let i=0;return l;function l(c){return nm(c)?(s.enter(n),o(c)):t(c)}function o(c){return nm(c)&&i++l))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(y(r),E=I;Ew;){const A=n[S];t.containerState=A[1],A[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 ROn(s,t,n){return Kf(s,s.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function xSt(s){if(s===null||Iw(s)||TOn(s))return 1;if(EOn(s))return 2}function sit(s,t,n){const r=[];let a=-1;for(;++a1&&s[n][1].end.offset-s[n][1].start.offset>1?2:1;const h={...s[r][1].end},m={...s[n][1].start};ySt(h,-c),ySt(m,c),l={type:c>1?"strongSequence":"emphasisSequence",start:h,end:{...s[r][1].end}},o={type:c>1?"strongSequence":"emphasisSequence",start:{...s[n][1].start},end:m},i={type:c>1?"strongText":"emphasisText",start:{...s[r][1].end},end:{...s[n][1].start}},a={type:c>1?"strong":"emphasis",start:{...l.start},end:{...o.end}},s[r][1].end={...l.start},s[n][1].start={...o.end},d=[],s[r][1].end.offset-s[r][1].start.offset&&(d=CN(d,[["enter",s[r][1],t],["exit",s[r][1],t]])),d=CN(d,[["enter",a,t],["enter",l,t],["exit",l,t],["enter",i,t]]),d=CN(d,sit(t.parser.constructs.insideSpan.null,s.slice(r+1,n),t)),d=CN(d,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",a,t]]),s[n][1].end.offset-s[n][1].start.offset?(u=2,d=CN(d,[["enter",s[n][1],t],["exit",s[n][1],t]])):u=0,X4(s,r-1,n-r+3,d),n=r+d.length-u-2;break}}for(n=-1;++n0&&nm(E)?Kf(s,b,"linePrefix",i+1)(E):b(E)}function b(E){return E===null||Fc(E)?s.check(vSt,x,S)(E):(s.enter("codeFlowValue"),w(E))}function w(E){return E===null||Fc(E)?(s.exit("codeFlowValue"),b(E)):(s.consume(E),w)}function S(E){return s.exit("codeFenced"),t(E)}function A(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"),nm(G)?Kf(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"),nm(G)?Kf(E,V,"whitespace")(G):V(G)):P(G)}function V(G){return G===null||Fc(G)?(E.exit("codeFencedFence"),I(G)):P(G)}}}function WOn(s,t,n){const r=this;return a;function a(l){return l===null?n(l):(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),i)}function i(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}const P9e={name:"codeIndented",tokenize:YOn},KOn={partial:!0,tokenize:ZOn};function YOn(s,t,n){const r=this;return a;function a(d){return s.enter("codeIndented"),Kf(s,i,"linePrefix",5)(d)}function i(d){const u=r.events[r.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?l(d):n(d)}function l(d){return d===null?c(d):Fc(d)?s.attempt(KOn,l,c)(d):(s.enter("codeFlowValue"),o(d))}function o(d){return d===null||Fc(d)?(s.exit("codeFlowValue"),l(d)):(s.consume(d),o)}function c(d){return s.exit("codeIndented"),t(d)}}function ZOn(s,t,n){const r=this;return a;function a(l){return r.parser.lazy[r.now().line]?n(l):Fc(l)?(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),a):Kf(s,i,"linePrefix",5)(l)}function i(l){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(l):Fc(l)?a(l):n(l)}}const XOn={name:"codeText",previous:JOn,resolve:QOn,tokenize:e8n};function QOn(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&&JZ(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),JZ(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),JZ(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 YXt(s,t,n,r,a,i,l,o,c){const d=c||Number.POSITIVE_INFINITY;let u=0;return h;function h(y){return y===60?(s.enter(r),s.enter(a),s.enter(i),s.consume(y),s.exit(i),m):y===null||y===32||y===41||bYe(y)?n(y):(s.enter(r),s.enter(l),s.enter(o),s.enter("chunkString",{contentType:"string"}),x(y))}function m(y){return y===62?(s.enter(i),s.consume(y),s.exit(i),s.exit(a),s.exit(r),t):(s.enter(o),s.enter("chunkString",{contentType:"string"}),f(y))}function f(y){return y===62?(s.exit("chunkString"),s.exit(o),m(y)):y===null||y===60||Fc(y)?n(y):(s.consume(y),y===92?g:f)}function g(y){return y===60||y===62||y===92?(s.consume(y),f):f(y)}function x(y){return!u&&(y===null||y===41||Iw(y))?(s.exit("chunkString"),s.exit(o),s.exit(l),s.exit(r),t(y)):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):Fc(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||Fc(f)||o++>999?(s.exit("chunkString"),u(f)):(s.consume(f),c||(c=!nm(f)),f===92?m:h)}function m(f){return f===91||f===92||f===93?(s.consume(f),o++,h):h(f)}}function XXt(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):Fc(m)?(s.enter("lineEnding"),s.consume(m),s.exit("lineEnding"),Kf(s,d,"linePrefix")):(s.enter("chunkString",{contentType:"string"}),u(m))}function u(m){return m===l||m===null||Fc(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 Gee(s,t){let n;return r;function r(a){return Fc(a)?(s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),n=!0,r):nm(a)?Kf(s,r,n?"linePrefix":"lineSuffix")(a):t(a)}}const l8n={name:"definition",tokenize:d8n},c8n={partial:!0,tokenize:u8n};function d8n(s,t,n){const r=this;let a;return i;function i(f){return s.enter("definition"),l(f)}function l(f){return ZXt.call(r,s,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return a=AV(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 Iw(f)?Gee(s,d)(f):d(f)}function d(f){return YXt(s,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function u(f){return s.attempt(c8n,h,h)(f)}function h(f){return nm(f)?Kf(s,m,"whitespace")(f):m(f)}function m(f){return f===null||Fc(f)?(s.exit("definition"),r.parser.defined.push(a),t(f)):n(f)}}function u8n(s,t,n){return r;function r(o){return Iw(o)?Gee(s,a)(o):n(o)}function a(o){return XXt(s,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return nm(o)?Kf(s,l,"whitespace")(o):l(o)}function l(o){return o===null||Fc(o)?t(o):n(o)}}const h8n={name:"hardBreakEscape",tokenize:m8n};function m8n(s,t,n){return r;function r(i){return s.enter("hardBreakEscape"),s.consume(i),a}function a(i){return Fc(i)?(s.exit("hardBreakEscape"),t(i)):n(i)}}const f8n={name:"headingAtx",resolve:p8n,tokenize:g8n};function p8n(s,t){let n=s.length-2,r=3,a,i;return 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&&(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"},X4(s,r,n-r+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),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||Iw(u)?(s.exit("atxHeadingSequence"),o(u)):n(u)}function o(u){return u===35?(s.enter("atxHeadingSequence"),c(u)):u===null||Fc(u)?(s.exit("atxHeading"),t(u)):nm(u)?Kf(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||Iw(u)?(s.exit("atxHeadingText"),o(u)):(s.consume(u),d)}}const x8n=["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"],_St=["pre","script","style","textarea"],y8n={concrete:!0,name:"htmlFlow",resolveTo:_8n,tokenize:w8n},v8n={partial:!0,tokenize:N8n},b8n={partial:!0,tokenize:j8n};function _8n(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 w8n(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:re):c4(ce)?(s.consume(ce),l=String.fromCharCode(ce),v):n(ce)}function m(ce){return ce===45?(s.consume(ce),a=2,f):ce===91?(s.consume(ce),a=5,o=0,g):c4(ce)?(s.consume(ce),a=4,r.interrupt?t:re):n(ce)}function f(ce){return ce===45?(s.consume(ce),r.interrupt?t:re):n(ce)}function g(ce){const ve="CDATA[";return ce===ve.charCodeAt(o++)?(s.consume(ce),o===ve.length?r.interrupt?t:U:g):n(ce)}function x(ce){return c4(ce)?(s.consume(ce),l=String.fromCharCode(ce),v):n(ce)}function v(ce){if(ce===null||ce===47||ce===62||Iw(ce)){const ve=ce===47,fe=l.toLowerCase();return!ve&&!i&&_St.includes(fe)?(a=1,r.interrupt?t(ce):U(ce)):x8n.includes(l.toLowerCase())?(a=6,ve?(s.consume(ce),y):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||Xj(ce)?(s.consume(ce),l+=String.fromCharCode(ce),v):n(ce)}function y(ce){return ce===62?(s.consume(ce),r.interrupt?t:U):n(ce)}function b(ce){return nm(ce)?(s.consume(ce),b):D(ce)}function w(ce){return ce===47?(s.consume(ce),D):ce===58||ce===95||c4(ce)?(s.consume(ce),S):nm(ce)?(s.consume(ce),w):D(ce)}function S(ce){return ce===45||ce===46||ce===58||ce===95||Xj(ce)?(s.consume(ce),S):A(ce)}function A(ce){return ce===61?(s.consume(ce),E):nm(ce)?(s.consume(ce),A):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):nm(ce)?(s.consume(ce),E):P(ce)}function I(ce){return ce===c?(s.consume(ce),c=null,R):ce===null||Fc(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||Iw(ce)?A(ce):(s.consume(ce),P)}function R(ce){return ce===47||ce===62||nm(ce)?w(ce):n(ce)}function D(ce){return ce===62?(s.consume(ce),O):n(ce)}function O(ce){return ce===null||Fc(ce)?U(ce):nm(ce)?(s.consume(ce),O):n(ce)}function U(ce){return ce===45&&a===2?(s.consume(ce),Z):ce===60&&a===1?(s.consume(ce),X):ce===62&&a===4?(s.consume(ce),te):ce===63&&a===3?(s.consume(ce),re):ce===93&&a===5?(s.consume(ce),le):Fc(ce)&&(a===6||a===7)?(s.exit("htmlFlowData"),s.check(v8n,J,W)(ce)):ce===null||Fc(ce)?(s.exit("htmlFlowData"),W(ce)):(s.consume(ce),U)}function W(ce){return s.check(b8n,V,J)(ce)}function V(ce){return s.enter("lineEnding"),s.consume(ce),s.exit("lineEnding"),G}function G(ce){return ce===null||Fc(ce)?W(ce):(s.enter("htmlFlowData"),U(ce))}function Z(ce){return ce===45?(s.consume(ce),re):U(ce)}function X(ce){return ce===47?(s.consume(ce),l="",ae):U(ce)}function ae(ce){if(ce===62){const ve=l.toLowerCase();return _St.includes(ve)?(s.consume(ce),te):U(ce)}return c4(ce)&&l.length<8?(s.consume(ce),l+=String.fromCharCode(ce),ae):U(ce)}function le(ce){return ce===93?(s.consume(ce),re):U(ce)}function re(ce){return ce===62?(s.consume(ce),te):ce===45&&a===2?(s.consume(ce),re):U(ce)}function te(ce){return ce===null||Fc(ce)?(s.exit("htmlFlowData"),J(ce)):(s.consume(ce),te)}function J(ce){return s.exit("htmlFlow"),t(ce)}}function j8n(s,t,n){const r=this;return a;function a(l){return Fc(l)?(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),i):n(l)}function i(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}function N8n(s,t,n){return r;function r(a){return s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),s.attempt(QRe,t,n)}}const k8n={name:"htmlText",tokenize:S8n};function S8n(s,t,n){const r=this;let a,i,l;return o;function o(re){return s.enter("htmlText"),s.enter("htmlTextData"),s.consume(re),c}function c(re){return re===33?(s.consume(re),d):re===47?(s.consume(re),A):re===63?(s.consume(re),w):c4(re)?(s.consume(re),P):n(re)}function d(re){return re===45?(s.consume(re),u):re===91?(s.consume(re),i=0,g):c4(re)?(s.consume(re),b):n(re)}function u(re){return re===45?(s.consume(re),f):n(re)}function h(re){return re===null?n(re):re===45?(s.consume(re),m):Fc(re)?(l=h,X(re)):(s.consume(re),h)}function m(re){return re===45?(s.consume(re),f):h(re)}function f(re){return re===62?Z(re):re===45?m(re):h(re)}function g(re){const te="CDATA[";return re===te.charCodeAt(i++)?(s.consume(re),i===te.length?x:g):n(re)}function x(re){return re===null?n(re):re===93?(s.consume(re),v):Fc(re)?(l=x,X(re)):(s.consume(re),x)}function v(re){return re===93?(s.consume(re),y):x(re)}function y(re){return re===62?Z(re):re===93?(s.consume(re),y):x(re)}function b(re){return re===null||re===62?Z(re):Fc(re)?(l=b,X(re)):(s.consume(re),b)}function w(re){return re===null?n(re):re===63?(s.consume(re),S):Fc(re)?(l=w,X(re)):(s.consume(re),w)}function S(re){return re===62?Z(re):w(re)}function A(re){return c4(re)?(s.consume(re),E):n(re)}function E(re){return re===45||Xj(re)?(s.consume(re),E):I(re)}function I(re){return Fc(re)?(l=I,X(re)):nm(re)?(s.consume(re),I):Z(re)}function P(re){return re===45||Xj(re)?(s.consume(re),P):re===47||re===62||Iw(re)?R(re):n(re)}function R(re){return re===47?(s.consume(re),Z):re===58||re===95||c4(re)?(s.consume(re),D):Fc(re)?(l=R,X(re)):nm(re)?(s.consume(re),R):Z(re)}function D(re){return re===45||re===46||re===58||re===95||Xj(re)?(s.consume(re),D):O(re)}function O(re){return re===61?(s.consume(re),U):Fc(re)?(l=O,X(re)):nm(re)?(s.consume(re),O):R(re)}function U(re){return re===null||re===60||re===61||re===62||re===96?n(re):re===34||re===39?(s.consume(re),a=re,W):Fc(re)?(l=U,X(re)):nm(re)?(s.consume(re),U):(s.consume(re),V)}function W(re){return re===a?(s.consume(re),a=void 0,G):re===null?n(re):Fc(re)?(l=W,X(re)):(s.consume(re),W)}function V(re){return re===null||re===34||re===39||re===60||re===61||re===96?n(re):re===47||re===62||Iw(re)?R(re):(s.consume(re),V)}function G(re){return re===47||re===62||Iw(re)?R(re):n(re)}function Z(re){return re===62?(s.consume(re),s.exit("htmlTextData"),s.exit("htmlText"),t):n(re)}function X(re){return s.exit("htmlTextData"),s.enter("lineEnding"),s.consume(re),s.exit("lineEnding"),ae}function ae(re){return nm(re)?Kf(s,le,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(re):le(re)}function le(re){return s.enter("htmlTextData"),l(re)}}const nit={name:"labelEnd",resolveAll:T8n,resolveTo:M8n,tokenize:P8n},C8n={tokenize:I8n},A8n={tokenize:L8n},E8n={tokenize:R8n};function T8n(s){let t=-1;const n=[];for(;++t=3&&(d===null||Fc(d))?(s.exit("thematicBreak"),t(d)):n(d)}function c(d){return d===a?(s.consume(d),r++,c):(s.exit("thematicBreakSequence"),nm(d)?Kf(s,o,"whitespace")(d):o(d))}}const tw={continuation:{tokenize:H8n},exit:W8n,name:"list",tokenize:V8n},U8n={partial:!0,tokenize:K8n},q8n={partial:!0,tokenize:G8n};function V8n(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:_Ye(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(w3e,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 _Ye(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(QRe,r.interrupt?n:u,s.attempt(U8n,m,h))}function u(f){return r.containerState.initialBlankLine=!0,i++,m(f)}function h(f){return nm(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 H8n(s,t,n){const r=this;return r.containerState._closeFlow=void 0,s.check(QRe,a,i);function a(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Kf(s,t,"listItemIndent",r.containerState.size+1)(o)}function i(o){return r.containerState.furtherBlankLines||!nm(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(q8n,t,l)(o))}function l(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,Kf(s,s.attempt(tw,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function G8n(s,t,n){const r=this;return Kf(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 W8n(s){s.exit(this.containerState.type)}function K8n(s,t,n){const r=this;return Kf(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!nm(i)&&l&&l[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const wSt={name:"setextUnderline",resolveTo:Y8n,tokenize:Z8n};function Y8n(s,t){let n=s.length,r,a,i;for(;n--;)if(s[n][0]==="enter"){if(s[n][1].type==="content"){r=n;break}s[n][1].type==="paragraph"&&(a=n)}else s[n][1].type==="content"&&s.splice(n,1),!i&&s[n][1].type==="definition"&&(i=n);const l={type:"setextHeading",start:{...s[r][1].start},end:{...s[s.length-1][1].end}};return s[a][1].type="setextHeadingText",i?(s.splice(a,0,["enter",l,t]),s.splice(i+1,0,["exit",s[r][1],t]),s[r][1].end={...s[i][1].end}):s[r][1]=l,s.push(["exit",l,t]),s}function Z8n(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"),nm(d)?Kf(s,c,"lineSuffix")(d):c(d))}function c(d){return d===null||Fc(d)?(s.exit("setextHeadingLine"),t(d)):n(d)}}const X8n={tokenize:Q8n};function Q8n(s){const t=this,n=s.attempt(QRe,r,s.attempt(this.parser.constructs.flowInitial,a,Kf(s,s.attempt(this.parser.constructs.flow,a,s.attempt(n8n,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 J8n={resolveAll:JXt()},ezn=QXt("string"),tzn=QXt("text");function QXt(s){return{resolveAll:JXt(s==="text"?szn: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 pzn(s,t){let n=-1;const r=[];let a;for(;++n0){const bs=es.tokenStack[es.tokenStack.length-1];(bs[1]||NSt).call(es,void 0,bs[0])}for(gt.position={start:jM(ft.length>0?ft[0][1].start:{line:1,column:1,offset:0}),end:jM(ft.length>0?ft[ft.length-2][1].end:{line:1,column:1,offset:0})},as=-1;++as0&&(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 Ezn(s,t){const n={type:"element",tagName:"del",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function Tzn(s,t){const n={type:"element",tagName:"em",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function Mzn(s,t){const n=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),a=LK(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 Pzn(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 Izn(s,t){if(s.options.allowDangerousHtml){const n={type:"raw",value:t.value};return s.patch(t,n),s.applyData(t,n)}}function sQt(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 Lzn(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return sQt(s,t);const a={src:LK(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 Rzn(s,t){const n={src:LK(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 Dzn(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 Fzn(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return sQt(s,t);const a={href:LK(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 Ozn(s,t){const n={href:LK(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 zzn(s,t,n){const r=s.all(t),a=n?Bzn(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 $zn(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=Xat(t.children[1]),c=FXt(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 Gzn(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(CSt(t.slice(a),a>0,!1)),i.join("")}function CSt(s,t,n){let r=0,a=s.length;if(t){let i=s.codePointAt(r);for(;i===kSt||i===SSt;)r++,i=s.codePointAt(r)}if(n){let i=s.codePointAt(a-1);for(;i===kSt||i===SSt;)a--,i=s.codePointAt(a-1)}return a>r?s.slice(r,a):""}function Yzn(s,t){const n={type:"text",value:Kzn(String(t.value))};return s.patch(t,n),s.applyData(t,n)}function Zzn(s,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return s.patch(t,n),s.applyData(t,n)}const Xzn={blockquote:Szn,break:Czn,code:Azn,delete:Ezn,emphasis:Tzn,footnoteReference:Mzn,heading:Pzn,html:Izn,imageReference:Lzn,image:Rzn,inlineCode:Dzn,linkReference:Fzn,link:Ozn,listItem:zzn,list:$zn,paragraph:Uzn,root:qzn,strong:Vzn,table:Hzn,tableCell:Wzn,tableRow:Gzn,text:Yzn,thematicBreak:Zzn,toml:Xde,yaml:Xde,definition:Xde,footnoteDefinition:Xde};function Xde(){}const rQt=-1,JRe=0,Wee=1,GMe=2,rit=3,ait=4,iit=5,oit=6,aQt=7,iQt=8,{defineProperty:Qzn}=Object,oQt=typeof self=="object"?self:globalThis,ASt=(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 oQt[s](t)},Jzn=(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 JRe:case rQt:return n(l,a);case Wee:{const o=n([],a);for(const c of l)o.push(r(c));return o}case GMe:{const o=n({},a);for(const[c,d]of l){const u=r(c),h=r(d);u==="__proto__"?Qzn(o,u,{value:h,configurable:!0,enumerable:!0,writable:!0}):o[u]=h}return o}case rit:return n(new Date(l),a);case ait:{const{source:o,flags:c}=l;return n(new RegExp(o,c),a)}case iit:{const o=n(new Map,a);for(const[c,d]of l)o.set(r(c),r(d));return o}case oit:{const o=n(new Set,a);for(const c of l)o.add(r(c));return o}case aQt:{const{name:o,message:c}=l;return n(typeof oQt[o]=="function"?ASt(o,c):new Error(c),a)}case iQt: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(ASt(i,l),a)};return r},ESt=s=>Jzn(new Map,s)(0),LO="",{toString:e7n}={},{keys:t7n,is:s7n}=Object,eX=s=>{const t=typeof s;if(t!=="object"||!s)return[JRe,t];const n=e7n.call(s).slice(8,-1);switch(n){case"Array":return[Wee,LO];case"Object":return[GMe,LO];case"Date":return[rit,LO];case"RegExp":return[ait,LO];case"Map":return[iit,LO];case"Set":return[oit,LO];case"DataView":return[Wee,n]}return n.includes("Array")?[Wee,n]:s instanceof Error?[aQt,s.name||"Error"]:[GMe,n]},Qde=([s,t])=>s===JRe&&(t==="function"||t==="symbol"),n7n=(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]=eX(l);switch(o){case JRe:{let u=l;switch(c){case"bigint":o=iQt,u=l.toString();break;case"number":if(!l&&s7n(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([rQt],l)}return a([o,u],l)}case Wee:{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 GMe:{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 t7n(l))(s||!Qde(eX(l[m])))&&u.push([i(m),i(l[m])]);return h}case rit:return a([o,isNaN(l.getTime())?LO:l.toISOString()],l);case ait:{const{source:u,flags:h}=l;return a([o,{source:u,flags:h}],l)}case iit:{const u=[],h=a([o,u],l);for(const[m,f]of l)(s||!(Qde(eX(m))||Qde(eX(f))))&&u.push([i(m),i(f)]);return h}case oit:{const u=[],h=a([o,u],l);for(const m of l)(s||!Qde(eX(m)))&&u.push(i(m));return h}}const{message:d}=l;return a([o,{name:c,message:d}],l)};return i},TSt=(s,{json:t,lossy:n}={})=>{const r=[];return n7n(!(t||n),!!t,new Map,r)(s),r},WMe=typeof structuredClone=="function"?(s,t)=>t&&("json"in t||"lossy"in t)?ESt(TSt(s,t)):structuredClone(s):(s,t)=>ESt(TSt(s,t));function r7n(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 a7n(s,t){return"Back to reference "+(s+1)+(t>1?"-"+t:"")}function i7n(s){const t=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",n=s.options.footnoteBackContent||r7n,r=s.options.footnoteBackLabel||a7n,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 v=u[u.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const b=v.children[v.children.length-1];b&&b.type==="text"?b.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...g)}else u.push(...g);const y={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:s.wrap(u,!0)};s.patch(d,y),o.push(y)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...WMe(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 lQt=function(s){if(s==null)return d7n;if(typeof s=="function")return eDe(s);if(typeof s=="object")return Array.isArray(s)?o7n(s):l7n(s);if(typeof s=="string")return c7n(s);throw new Error("Expected function, string, or object as test")};function o7n(s){const t=[];let n=-1;for(;++n":""))+")"})}return m;function m(){let f=cQt,g,x,v;if((!t||i(c,d,u[u.length-1]||void 0))&&(f=p7n(n(c,u)),f[0]===MSt))return f;if("children"in c&&c.children){const y=c;if(y.children&&f[0]!==m7n)for(x=(r?y.children.length:-1)+l,v=u.concat(y);x>-1&&x0&&n.push({type:"text",value:` `}),n}function PSt(s){let t=0,n=s.charCodeAt(t);for(;n===9||n===32;)t++,n=s.charCodeAt(t);return s.slice(t)}function ISt(s,t){const n=x7n(s,t),r=n.one(s,void 0),a=i7n(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&i.children.push({type:"text",value:` `},a),i}function w7n(s,t){return s&&"run"in s?async function(n,r){const a=ISt(n,{file:r,...t});await s.run(a,r)}:function(n,r){return ISt(n,{file:r,...s||t})}}function LSt(s){if(s)throw s}var j3e=Object.prototype.hasOwnProperty,uQt=Object.prototype.toString,RSt=Object.defineProperty,DSt=Object.getOwnPropertyDescriptor,FSt=function(t){return typeof Array.isArray=="function"?Array.isArray(t):uQt.call(t)==="[object Array]"},OSt=function(t){if(!t||uQt.call(t)!=="[object Object]")return!1;var n=j3e.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&j3e.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var a;for(a in t);return typeof a>"u"||j3e.call(t,a)},zSt=function(t,n){RSt&&n.name==="__proto__"?RSt(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},BSt=function(t,n){if(n==="__proto__")if(j3e.call(t,n)){if(DSt)return DSt(t,n).value}else return;return t[n]},j7n=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 N5={basename:S7n,dirname:C7n,extname:A7n,join:E7n,sep:"/"};function S7n(s,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Tie(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 C7n(s){if(Tie(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 A7n(s){Tie(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 E7n(...s){let t=-1,n;for(;++t0&&s.codePointAt(s.length-1)===47&&(n+="/"),t?"/"+n:n}function M7n(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 Tie(s){if(typeof s!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(s))}const P7n={cwd:I7n};function I7n(){return"/"}function kYe(s){return!!(s!==null&&typeof s=="object"&&"href"in s&&s.href&&"protocol"in s&&s.protocol&&s.auth===void 0)}function L7n(s){if(typeof s=="string")s=new URL(s);else if(!kYe(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 R7n(s)}function R7n(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];NYe(x)&&NYe(f)&&(f=L9e(!0,x,f)),r[m]=[d,f,...g]}}}}const z7n=new lit().freeze();function O9e(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `parser`")}function z9e(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `compiler`")}function B9e(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 USt(s){if(!NYe(s)||typeof s.type!="string")throw new TypeError("Expected node, got `"+s+"`")}function qSt(s,t,n){if(!n)throw new Error("`"+s+"` finished async. Use `"+t+"` instead")}function Jde(s){return B7n(s)?s:new hQt(s)}function B7n(s){return!!(s&&typeof s=="object"&&"message"in s&&"messages"in s)}function $7n(s){return typeof s=="string"||U7n(s)}function U7n(s){return!!(s&&typeof s=="object"&&"byteLength"in s&&"byteOffset"in s)}const q7n="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",VSt=[],HSt={allowDangerousHtml:!0},V7n=/^(https?|ircs?|mailto|xmpp)$/i,H7n=[{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 G7n(s){const t=W7n(s),n=K7n(s);return Y7n(t.runSync(t.parse(n),n),s)}function W7n(s){const t=s.rehypePlugins||VSt,n=s.remarkPlugins||VSt,r=s.remarkRehypeOptions?{...s.remarkRehypeOptions,...HSt}:HSt;return z7n().use(kzn).use(n).use(w7n,r).use(t)}function K7n(s){const t=s.children||"",n=new hQt;return typeof t=="string"&&(n.value=t),n}function Y7n(s,t){const n=t.allowedElements,r=t.allowElement,a=t.components,i=t.disallowedElements,l=t.skipHtml,o=t.unwrapDisallowed,c=t.urlTransform||Z7n;for(const u of H7n)Object.hasOwn(t,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+q7n+u.id,void 0);return dQt(s,d),rOn(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 M9e)if(Object.hasOwn(M9e,f)&&Object.hasOwn(u.properties,f)){const g=u.properties[f],x=M9e[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 Z7n(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||V7n.test(s.slice(0,t))?s:""}const X7n={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(br,{to:n,className:a,children:[t,e.jsx(Mz,{className:"h-3 w-3"})]}):e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:a,children:[t,e.jsx(Mz,{className:"h-3 w-3"})]})}},Q7n=["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 J7n(){var h,m,f;const{user:s}=_s(),[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 v=[...t,{role:"user",content:x}];n([...v,{role:"assistant",content:""}]),a(""),l(!0);const y=new AbortController;o.current=y;try{const{data:w}=await q.auth.getSession(),S=(b=w.session)==null?void 0:b.access_token,A=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:v,agentName:d}),signal:y.signal});if(!A.ok||!A.body){const D=await A.json().catch(()=>({error:"Something went wrong."}));throw new Error(D.error||"Something went wrong.")}const E=A.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 Z=JSON.parse(G);Z.delta&&(R+=Z.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((A,E)=>!(E===S.length-1&&!A.content))):(ne.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(A4,{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(Sx,{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(A4,{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:Q7n.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(G7n,{components:X7n,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(w_,{className:"h-4 w-4"})}):e.jsx($,{size:"icon",disabled:!r.trim(),onClick:()=>u(r),children:e.jsx(Zr,{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 eBn({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 eue({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 tBn({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(wn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),e.jsx("span",{children:r})]})]}),e.jsx(eBn,{done:t,total:n})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(eue,{icon:e.jsx(ph,{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(Nd,{className:"h-3.5 w-3.5"})})}),e.jsx(eue,{icon:e.jsx(sh,{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(eue,{icon:e.jsx(ca,{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(eue,{icon:e.jsx(Yn,{className:"h-3.5 w-3.5"}),label:"Your sphere",value:String(c),hint:"People in your database",onClick:h})]})]})}const GSt="agent-os-onboarding-completed",tue=[{icon:By,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:Qp,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:Yn,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:Wc,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:dl,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:Gl,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"]}],sBn=()=>{const[s,t]=j.useState(!1),[n,r]=j.useState(0),[a,i]=j.useState(!1);j.useEffect(()=>{if(!localStorage.getItem(GSt)){const g=setTimeout(()=>t(!0),500);return()=>clearTimeout(g)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(GSt,"true"),t(!1)},d=tue[n],u=d.icon,h=n===tue.length-1,m=f=>{f||c(),t(f)};return e.jsx(Os,{open:s,onOpenChange:m,children:e.jsxs(Fs,{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(wn,{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($s,{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(Er,{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(ma,{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:tue.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}=_s();return st({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})},rBn=()=>{const s=Zt(),{user:t}=_s();return mt({mutationFn:async({contactId:n,days:r})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=Am(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"})}})},aBn=()=>{const s=Zt();return mt({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"})}})},iBn=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function tDe({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=j.useState(null),l=rBn(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>Js(Am(new Date,d),"MMM d, yyyy");return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ca,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(Er,{children:["Postpone the next scheduled touch for ",r,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:iBn.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(Ea,{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 oBn={Crown:Og,FileText:Qr,Users:Yn,Globe:cl,Star:ei,Phone:Da,MessageSquare:no,PenTool:PE,Video:fa,Gift:dl};function lBn({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=Zn(),[c,d]=j.useState("name"),[u,h]=j.useState("asc"),[m,f]=j.useState(null),[g,x]=j.useState(""),v=A=>{c===A?h(E=>E==="asc"?"desc":"asc"):(d(A),h("asc"))},y=j.useMemo(()=>[...s].sort((A,E)=>{var P,R;let I=0;switch(c){case"name":{const D=`${A.contact.first_name} ${A.contact.last_name||""}`.toLowerCase(),O=`${E.contact.first_name} ${E.contact.last_name||""}`.toLowerCase();I=D.localeCompare(O);break}case"relationship_type":I=(A.relationshipTypeName||"").localeCompare(E.relationshipTypeName||"");break;case"action_type":I=(((P=A.actionType)==null?void 0:P.name)||"").localeCompare(((R=E.actionType)==null?void 0:R.name)||"");break;case"last_touch":I=(A.monthNumber||0)-(E.monthNumber||0);break}return u==="asc"?I:-I}),[s,c,u]),b=A=>oBn[A||"Phone"]||Da,w=({field:A,children:E})=>e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>v(A),children:[E,c===A?u==="asc"?e.jsx(Zf,{className:"ml-2 h-4 w-4"}):e.jsx(Lg,{className:"ml-2 h-4 w-4"}):e.jsx(Dy,{className:"ml-2 h-4 w-4 opacity-50"})]}),S=(A,E,I)=>{f(A),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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:y.map((A,E)=>{var U,W,V,G,Z,X;const I=A.isSpecialDate,P=A.specialDateType,R=I?P==="birthday"?Rg:va:b(((U=A.actionType)==null?void 0:U.icon)||null),D=A.contact.phone,O=A.contact.email;return e.jsxs(An,{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/${A.contact.id}`),className:"truncate max-w-[160px] text-left hover:text-primary hover:underline transition-colors",children:[A.contact.first_name," ",A.contact.last_name]})})}),e.jsx(wt,{children:A.relationshipTypeName?e.jsx($e,{variant:"secondary",className:"text-xs",children:A.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($e,{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(Rg,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(va,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(R,{className:"h-3 w-3"}),(W=A.actionType)==null?void 0:W.name]})})}),e.jsx(wt,{children:D?e.jsx("span",{className:"text-sm font-mono",children:A.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:${A.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(A.contact.phone,(V=A.script)==null?void 0:V.script_body,A.contact),className:"p-1.5 rounded bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 transition-colors",title:"Text",children:e.jsx(no,{className:"h-3.5 w-3.5"})}),O&&(l?e.jsx("button",{onClick:()=>l({id:A.contact.id,first_name:A.contact.first_name,last_name:A.contact.last_name,email:A.contact.email}),className:"p-1.5 rounded bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 transition-colors",title:"Compose Email",children:e.jsx(pn,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(A.contact.email,(G=A.script)==null?void 0:G.script_body,(Z=A.script)==null?void 0:Z.email_subject,(X=A.actionType)==null?void 0:X.name,A.contact),className:"p-1.5 rounded bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 transition-colors",title:"Email",children:e.jsx(pn,{className:"h-3.5 w-3.5"})})),I&&e.jsxs("button",{onClick:()=>{const ae=`${A.contact.first_name}${A.contact.last_name?" "+A.contact.last_name:""}`,le=P==="birthday"?"birthday":"home_anniversary",re=new URLSearchParams({cardType:le,contactId:A.contact.id,name:ae,...A.contact.address?{address:A.contact.address}:{},...P==="anniversary"&&A.contact.home_anniversary?{date:A.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${re.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(pn,{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(A.contact.id,A.contact.first_name,A.contact.last_name),title:"Snooze",children:e.jsx(Cv,{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(A.contact.id,A.actionType.id,(ae=A.script)==null?void 0:ae.id)},disabled:r,children:[e.jsx(Vr,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${A.contact.id}-${E}`)})})]})}),e.jsx(tDe,{open:!!m,onOpenChange:A=>!A&&f(null),contactId:m||"",contactName:g})]})}function cBn(){const s=Zn(),{data:t}=vUt(),{data:n}=Jae(),r=y6e(),{isGmailConnected:a,gmailEmail:i}=Gy(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(new Set),m=Eg(new Date),f=Am(m,30),g=A=>{if(!A)return null;const E=A.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 A=[];for(const E of t){if(E.birthday){const I=g(E.birthday);I&&(sf(I,m)||L4(I,m)&&nC(I,f))&&A.push({contact:E,type:"birthday",date:I,daysUntil:db(I,m),dateStr:E.birthday})}if(E.home_anniversary){const I=g(E.home_anniversary);I&&(sf(I,m)||L4(I,m)&&nC(I,f))&&A.push({contact:E,type:"anniversary",date:I,daysUntil:db(I,m),dateStr:E.home_anniversary})}if(E.wedding_anniversary){const I=g(E.wedding_anniversary);I&&(sf(I,m)||L4(I,m)&&nC(I,f))&&A.push({contact:E,type:"wedding_anniversary",date:I,daysUntil:db(I,m),dateStr:E.wedding_anniversary})}}return A.sort((E,I)=>E.daysUntil-I.daysUntil),A},[t]),v=A=>A==="birthday"?"Birthday":A==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",y=async A=>{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:A.contact.id,actionTypeId:E.id,notes:`${v(A.type)} outreach`}),h(I=>new Set(I).add(`${A.contact.id}-${A.type}`)),_a({title:"Touch logged!",description:`Logged outreach for ${A.contact.first_name}`})}catch{_a({title:"Error",description:"Failed to log touch",variant:"destructive"})}},b=A=>{const E=`${A.contact.first_name}${A.contact.last_name?" "+A.contact.last_name:""}`,I=A.type==="birthday"?"birthday":A.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",P=new URLSearchParams({cardType:I,contactId:A.contact.id,name:E,...A.contact.address?{address:A.contact.address}:{},...(A.type==="anniversary"||A.type==="wedding_anniversary")&&A.dateStr?{date:A.dateStr}:{}});s(`/mission-control/card-studio?${P.toString()}`)},w=A=>A===0?"Today!":A===1?"Tomorrow":`${A} days`,S=A=>A===0?"bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/30":A<=3?"bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30":A<=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(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Et,{className:"text-lg flex items-center gap-2",children:[e.jsx(Wc,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx($e,{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(Le,{className:"space-y-2",children:[x.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Rg,{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((A,E)=>{var D,O;const I=`${A.contact.id}-${A.type}`,P=u.has(I),R=`${((D=A.contact.first_name)==null?void 0:D[0])||""}${((O=A.contact.last_name)==null?void 0:O[0])||""}`.toUpperCase();return e.jsxs("div",{className:Pt("p-3 rounded-lg border transition-colors",A.daysUntil===0&&A.type==="birthday"?"bg-pink-500/10 border-pink-500/30 dark:bg-pink-900/20 dark:border-pink-800/40":A.daysUntil===0&&(A.type==="anniversary"||A.type==="wedding_anniversary")?"bg-blue-500/10 border-blue-500/30 dark:bg-blue-900/20 dark:border-blue-800/40":A.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",A.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",A.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:A.type==="birthday"?"🎂":A.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:[A.contact.first_name," ",A.contact.last_name||""]}),e.jsx($e,{variant:"outline",className:Pt("text-[10px] shrink-0 whitespace-nowrap",S(A.daysUntil)),children:w(A.daysUntil)})]}),e.jsxs("div",{className:Pt("text-xs flex items-center gap-1.5 mt-0.5",A.type==="birthday"?"text-pink-600/80 dark:text-pink-400/80":"text-blue-600/80 dark:text-blue-400/80"),children:[A.type==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(Rg,{className:"h-3 w-3"})," Birthday"]}):A.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:Js(A.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[A.contact.phone&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Call",asChild:!0,children:e.jsx("a",{href:`tel:${A.contact.phone}`,children:e.jsx(Da,{className:"h-3.5 w-3.5"})})}),A.contact.phone&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Text",asChild:!0,children:e.jsx("a",{href:`sms:${A.contact.phone}`,children:e.jsx(no,{className:"h-3.5 w-3.5"})})}),A.contact.email&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Email",onClick:()=>{a?(o({id:A.contact.id,first_name:A.contact.first_name,last_name:A.contact.last_name,email:A.contact.email}),d(!0)):window.location.href=`mailto:${A.contact.email}`},children:e.jsx(pn,{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=${A.contact.id}`),children:e.jsx(fa,{className:"h-3.5 w-3.5"})}),e.jsxs($,{variant:"ghost",size:"sm",className:Pt("h-7 px-2 gap-1 text-xs",A.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 ${A.type==="birthday"?"birthday":"anniversary"} card`,onClick:()=>b(A),children:[e.jsx(wn,{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:()=>y(A),children:e.jsx(Vr,{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/${A.contact.id}`),children:e.jsx(Ta,{className:"h-3.5 w-3.5"})})]})]},`${I}-${E}`)})]})]}),a&&l&&e.jsx(Nk,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function dBn(s){const[t,n]=j.useState([]),[r,a]=j.useState(!1),{data:i,isLoading:l}=st({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 v=u.find(y=>y.auth_user_id===x.user_id);v&&!v.contact_id&&x.contact_id&&(v.contact_id=x.contact_id),v&&!m[v.contact_id||""]&&x.name&&(m[v.contact_id||v.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,v;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:((v=m[g.contact_id||g.auth_user_id||""])==null?void 0:v.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?uBn([...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 uBn(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const hBn={property_view:{label:"Viewed",icon:Ta,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:lc,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 mBn(){const{user:s}=_s(),t=Zn(),{isGmailConnected:n,gmailEmail:r}=Gy(),{leadSite:a}=tg(),{count:i}=dBn(a==null?void 0:a.id),[l,o]=j.useState(!1),[c,d]=j.useState(null),{data:u,isLoading:h}=st({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:b}=await q.rpc("get_lead_site_activity",{_user_id:s.id});if(b)throw b;return y},enabled:!!s,refetchInterval:6e4});if(h||!(u!=null&&u.has_site))return null;const m=(u.activities||[]).filter(y=>y.visitor_name&&y.visitor_name!=="Site Visitor"),f=m.filter(y=>y.activity_type==="new_lead"),g=(u.activities||[]).filter(y=>y.activity_type==="property_view").length,x=(u.activities||[]).filter(y=>y.activity_type==="saved_listing").length,v=y=>{if(y.visitor_email)if(n){const b=(y.visitor_name||"").split(" ");d({id:y.contact_id||"",first_name:b[0]||"",last_name:b.slice(1).join(" ")||null,email:y.visitor_email}),o(!0)}else window.location.href=`mailto:${y.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(cl,{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(Qa,{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(lc,{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(Ta,{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((y,b)=>{const w=hBn[y.activity_type],S=w.icon,A=hu(new Date(y.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:()=>{y.contact_id&&t(`/mission-control/contacts/${y.contact_id}`)},children:y.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:w.label}),y.mls_number&&e.jsxs("span",{children:["· MLS# ",y.mls_number]}),y.lead_type&&e.jsxs("span",{children:["· ",y.lead_type]}),e.jsxs("span",{children:["· ",A]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[y.visitor_email&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>v(y),children:e.jsx(pn,{className:"h-3.5 w-3.5"})}),y.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:${y.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:${y.visitor_phone}`,children:e.jsx(no,{className:"h-3.5 w-3.5"})})]}),y.contact_id&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${y.contact_id}`),children:e.jsx(Di,{className:"h-3.5 w-3.5"})})]})]},`${y.activity_type}-${y.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(Qa,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(je,{children:e.jsxs(Le,{className:"p-6 text-center",children:[e.jsx(rf,{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(Qa,{className:"h-3.5 w-3.5 ml-1"})]})]})}),n&&c&&e.jsx(Nk,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const WSt={Crown:Og,FileText:Qr,Users:Yn,Globe:cl,Star:ei,Phone:Da,MessageSquare:no,PenTool:PE,Video:fa,Gift:dl},fBn={"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 pBn(){var ft,gt,es,Ht,as,bs;const s=Zn(),{user:t}=_s(),{data:n}=Uw(),{data:r}=bUt(),{data:a}=L_(),{data:i}=Jae(),{data:l}=Yst(),o=EHs(),c=v6e(),d=SHs(90),u=y6e(),[h,m]=j.useState(null),[f,g]=j.useState(null),[x,v]=j.useState(!1),[y,b]=j.useState(""),[w,S]=j.useState(!1),[A,E]=j.useState(""),[I,P]=j.useState(kUt()),[R,D]=j.useState("cards"),[O,U]=j.useState(!1),[W,V]=j.useState(null),[G,Z]=j.useState(null),[X,ae]=j.useState(""),{isGmailConnected:le,gmailEmail:re}=Gy(),te=()=>{const Ut=parseInt(A,10);if(isNaN(Ut)||Ut<1){_a({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}P(Ut),CHs(Ut),S(!1),_a({title:"Goal updated",description:`Weekly touch goal set to ${Ut}`})},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=Eg(new Date),ve=Am(ce,7),fe=Ut=>{if(!Ut)return null;const Ft=Ut.split(/[-/T]/);if(Ft.length<3)return null;const is=parseInt(Ft[1],10)-1,jt=parseInt(Ft[2],10);return isNaN(is)||isNaN(jt)?null:new Date(ce.getFullYear(),is,jt)},ue=(a==null?void 0:a.filter(Ut=>{const Ft=fe(Ut.birthday),is=fe(Ut.home_anniversary);return Ft&&sf(Ft,ce)||is&&sf(is,ce)}))||[],be=(a==null?void 0:a.filter(Ut=>{if(!Ut.birthday&&!Ut.home_anniversary)return!1;const Ft=is=>{if(!is)return!1;const jt=fe(is);return jt?L4(jt,ce)&&nC(jt,ve):!1};return Ft(Ut.birthday)||Ft(Ut.home_anniversary)}).slice(0,5))||[],Ee=[],ke=(i==null?void 0:i.find(Ut=>Ut.name==="Call"))||(i==null?void 0:i[0]);for(const Ut of ue){const Ft=fe(Ut.birthday),is=fe(Ut.home_anniversary),jt=Ft&&sf(Ft,ce),zs=is&&sf(is,ce);jt&&Ee.push({contact:Ut,actionType:ke||{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:((es=(gt=(ft=Ut.tags)==null?void 0:ft[0])==null?void 0:gt.relationship_type)==null?void 0:es.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),zs&&Ee.push({contact:Ut,actionType:ke||{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:((bs=(as=(Ht=Ut.tags)==null?void 0:Ht[0])==null?void 0:as.relationship_type)==null?void 0:bs.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Fe=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((Ut,Ft)=>{var jt,zs,yt;const is=i==null?void 0:i[Ft%((i==null?void 0:i.length)||1)];return is?{contact:Ut,actionType:is,planName:"Quick Touch",relationshipTypeName:((yt=(zs=(jt=Ut.tags)==null?void 0:jt[0])==null?void 0:zs.relationship_type)==null?void 0:yt.name)||"",monthNumber:0}:null}).filter(Boolean))||[],Ne=[...Ee,...Fe],{data:Be}=cK(7),Se=(Be||[]).filter(Ut=>sf(new Date(Ut.completed_at),ce)).length,Ae=Se+Ne.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.`:be.length>0?`${be.length} milestone${be.length===1?"":"s"} coming up this week — get ahead of them.`:"Consistency beats intensity. A few real conversations today is a win.",ze=async(Ut,Ft,is)=>{await u.mutateAsync({contactId:Ut,actionTypeId:Ft,scriptUsedId:is}),v(!1),g(null)},Ve=Ut=>{Ut.script?(g(Ut),v(!0)):ze(Ut.contact.id,Ut.actionType.id)},ht=Ut=>WSt[Ut||"Phone"]||Da,Qe=Ut=>WSt[Ut||"Users"]||Yn,at=(Ut,Ft)=>Ut.replace(/\{\{FirstName\}\}/g,Ft.first_name).replace(/\{\{LastName\}\}/g,Ft.last_name||"").replace(/\{\{AgentName\}\}/g,y||"there"),rt=(Ut,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}`})[Ut]||`Hello ${Ft}!`,Ke=(Ut,Ft,is)=>{const jt=`sms:${Ut}`;if(Ft&&is){const zs=at(Ft,is);return`${jt}?body=${encodeURIComponent(zs)}`}return jt},Je=(Ut,Ft,is,jt,zs)=>{const yt=`mailto:${Ut}`,gs=[];if(zs){const Ss=is||rt(jt||"Email",zs.first_name);if(gs.push(`subject=${encodeURIComponent(Ss)}`),Ft){const Ds=at(Ft,zs);gs.push(`body=${encodeURIComponent(Ds)}`)}}return gs.length>0?`${yt}?${gs.join("&")}`:yt};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(nf,{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(Yn,{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(fa,{className:"h-4 w-4"}),"Library"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/plans"),className:"gap-1.5",children:[e.jsx(Nd,{className:"h-4 w-4"}),"Plans"]})]})]}),e.jsx(tBn,{agentName:y,todayDone:Se,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(mBn,{}),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(Ut=>Ut.active).map(Ut=>{const Ft=Qe(Ut.icon),is=(r==null?void 0:r[Ut.id])||0,jt=h===Ut.id,zs=fBn[Ut.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{jt?(m(null),s("/mission-control/contacts")):(m(Ut.id),s(`/mission-control/contacts?type=${Ut.id}`))},className:` inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-all ${jt?zs:"bg-card hover:bg-accent"} `,children:[e.jsx(Ft,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-medium",children:Ut.name}),e.jsx("span",{className:`rounded-full px-1.5 py-0.5 text-[11px] tabular-nums ${jt?"bg-black/15":"bg-muted text-muted-foreground"}`,children:is})]},Ut.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($e,{variant:"outline",className:"gap-1",children:[e.jsx(wn,{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(Xf,{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(E0,{className:"h-4 w-4"})})]})]}),e.jsx(je,{children:e.jsx(Le,{className:"p-4",children:Ne.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(lBn,{actions:Ne,onMarkComplete:ze,onViewScript:Ve,isLoading:u.isPending,buildSmsLink:Ke,buildEmailLink:Je,onGmailCompose:le?Ut=>{V(Ut),U(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[Ne.map((Ut,Ft)=>{var Bt,zt,vs,dn,Ks,Cn,Rr;const is=Ut.isSpecialDate,jt=Ut.specialDateType,zs=is?jt==="birthday"?Rg:va:ht(((Bt=Ut.actionType)==null?void 0:Bt.icon)||null),yt=Ut.contact.phone,gs=Ut.contact.email,Ss=is?jt==="birthday"?"#EC4899":"#8B5CF6":((zt=Ut.actionType)==null?void 0:zt.color)||"#3B82F6",Ds=is?jt==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(vs=Ut.actionType)==null?void 0:vs.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${is?"ring-2 ring-offset-2":""}`,style:is?{"--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(zs,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:Ds})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${Ut.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[Ut.contact.first_name," ",Ut.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[yt&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${Ut.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(Ut.contact.phone,(dn=Ut.script)==null?void 0:dn.script_body,Ut.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(no,{className:"h-3 w-3"}),"Text"]})]}),gs&&(le?e.jsxs("button",{onClick:()=>{V({id:Ut.contact.id,first_name:Ut.contact.first_name,last_name:Ut.contact.last_name,email:Ut.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(pn,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:Je(Ut.contact.email,(Ks=Ut.script)==null?void 0:Ks.script_body,(Cn=Ut.script)==null?void 0:Cn.email_subject,(Rr=Ut.actionType)==null?void 0:Rr.name,Ut.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(pn,{className:"h-3 w-3"}),"Email"]}))]}),is&&e.jsxs("button",{onClick:()=>{const ia=`${Ut.contact.first_name}${Ut.contact.last_name?" "+Ut.contact.last_name:""}`,Hs=jt==="birthday"?"birthday":"home_anniversary",Br=new URLSearchParams({cardType:Hs,contactId:Ut.contact.id,name:ia,...Ut.contact.address?{address:Ut.contact.address}:{},...jt==="anniversary"&&Ut.contact.home_anniversary?{date:Ut.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${Br.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(pn,{className:"h-3 w-3"}),"Send ",jt==="birthday"?"Birthday":"Anniversary"," Card"]}),!yt&&!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:[Ut.relationshipTypeName&&e.jsx($e,{variant:"secondary",className:"text-xs",children:Ut.relationshipTypeName}),Ut.monthNumber>0&&e.jsxs($e,{variant:"outline",className:"text-xs",children:["Month ",Ut.monthNumber]})]}),Ut.script&&e.jsx($,{size:"sm",variant:"outline",className:"w-full",onClick:()=>Ve(Ut),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs($,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{Z(Ut.contact.id),ae(`${Ut.contact.first_name} ${Ut.contact.last_name||""}`.trim())},children:[e.jsx(Cv,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx($,{size:"sm",className:"flex-1",onClick:()=>{var ia;return ze(Ut.contact.id,Ut.actionType.id,(ia=Ut.script)==null?void 0:ia.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},Ut.contact.id+Ft)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsxs($,{variant:"ghost",className:"h-full w-full",children:[e.jsx(o_,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(Cu,{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(sh,{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(Os,{open:w,onOpenChange:S,children:e.jsxs(Fs,{className:"sm:max-w-[360px]",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Set Weekly Goal"}),e.jsx(Er,{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:A,onChange:Ut=>E(Ut.target.value),placeholder:"20",onKeyDown:Ut=>{Ut.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(qUt,{}),e.jsx(cBn,{})]})]}),e.jsx(Os,{open:x,onOpenChange:v,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{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:at(f.script.script_body,f.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",className:"flex-1",onClick:()=>v(!1),children:"Close"}),e.jsx($,{className:"flex-1",onClick:()=>{var Ut;return ze(f.contact.id,f.actionType.id,(Ut=f.script)==null?void 0:Ut.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(sBn,{})]}),le&&W&&e.jsx(Nk,{open:O,onOpenChange:U,contact:W,gmailEmail:re}),e.jsx(tDe,{open:!!G,onOpenChange:Ut=>!Ut&&Z(null),contactId:G||"",contactName:X})]})}const DN=s=>(s||"").trim(),mQt=["Home","Vacation home","Work","Mailing","Rental"];function KSt(s){return s?!!(DN(s.address2)||DN(s.address2_city)):!1}function gBn(s){const t=DN(s==null?void 0:s.address),n=DN(s==null?void 0:s.city);return{line:t,city:n,state:DN(s==null?void 0:s.state),zip:DN(s==null?void 0:s.zip_code)||DN(s==null?void 0:s.zip),label:"Home",isSecondary:!1,hasAddress:!!(t||n)}}function SYe(s){const t=DN(s==null?void 0:s.address2),n=DN(s==null?void 0:s.address2_city);return{line:t,city:n,state:DN(s==null?void 0:s.address2_state),zip:DN(s==null?void 0:s.address2_zip),label:DN(s==null?void 0:s.address2_label)||"Second address",isSecondary:!0,hasAddress:!!(t||n)}}function tX(s){const t=SYe(s);return s!=null&&s.mail_to_secondary&&t.hasAddress?t:gBn(s)}function xBn(s){const t=[s.city,s.state].filter(Boolean).join(", ");return[s.line,[t,s.zip].filter(Boolean).join(" ")].filter(Boolean).join(", ")}const yBn=[{value:"bidirectional",label:"Two-Way",icon:Dy,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:Lg,tooltip:"Only pull BoldTrail → Agent OS"}];function KMe({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(jV,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:yBn.map(a=>e.jsxs(ry,{children:[e.jsx(ay,{asChild:!0,children:e.jsxs(f7,{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(vx,{children:a.tooltip})]},a.value))})]})}function vBn(){const s=Zt(),[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:v}=st({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}}),y=(v==null?void 0:v.sync_direction)||"bidirectional",b=d??y,w=mt({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=>{ne.error(R.message||"Failed to generate sync preview")}}),S=mt({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,Z=O.pull_total||0,X=O.update_total||0,ae=0,le=0,re=0;for(;W!=="finalize"&&!x.current;){const ce=G+Z+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... (${le}/${Z})`),g(ce>0?(G+le)/ce*90:0)):W==="update"&&(m(`Updating existing contacts... (${re}/${X})`),g(ce>0?(G+Z+re)/ce*90:0));const{data:ve,error:fe}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:W,offset:V,sync_log_id:U,sync_direction:b}});if(fe)throw fe;if(ve!=null&&ve.error)throw new Error(ve.error);const ue=ve;ae+=ue.chunk_pushed||0,le+=ue.chunk_pulled||0,re+=ue.chunk_updated||0,ue.push_total!==void 0&&(G=ue.push_total||0),ue.pull_total!==void 0&&(Z=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`];ne.success(`Sync complete! ${D.join(", ")}.`)},onError:R=>{m(null),g(0),ne.error(R.message||"Sync failed")}});if(!(v!=null&&v.connected))return null;const A=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=A>0||E>0||I>0;return e.jsxs(e.Fragment,{children:[e.jsxs(ry,{children:[e.jsx(ay,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",onClick:()=>w.mutate(),disabled:w.isPending,className:"shrink-0",children:w.isPending?e.jsx(co,{className:"h-4 w-4 animate-spin"}):e.jsx(Dy,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(vx,{children:"Sync with BoldTrail"})]}),e.jsx(Os,{open:t,onOpenChange:R=>{S.isPending||n(R)},children:e.jsxs(Fs,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Dy,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Er,{children:"Review what will happen when you sync your contacts."})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(KMe,{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:A}),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(Lg,{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(Wq,{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(Yn,{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(Wq,{className:"h-3 w-3 inline mr-1"}),I," contacts have missing fields that will be filled from the other system"]}),A>0&&e.jsxs(y1,{open:i,onOpenChange:l,children:[e.jsx(v1,{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"}),A," contacts to push to BoldTrail"]}),e.jsx(wl,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(b1,{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(y1,{open:o,onOpenChange:c,children:[e.jsx(v1,{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(Lg,{className:"h-3 w-3 text-blue-600"}),E," contacts to pull from BoldTrail"]}),e.jsx(wl,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(b1,{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(co,{className:"h-4 w-4 animate-spin"}):e.jsx(Dy,{className:"h-4 w-4"}),S.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const bBn=[{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"}],_Bn="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 YMe(s){return Object.entries(s).filter(([t,n])=>t!=="id"&&n!==null&&n!==void 0&&String(n).trim()!=="").length}function wBn(s){return st({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 jBn(s,t){return st({queryKey:["merge-candidates",[...s].sort().join(",")],enabled:t&&s.length>1,queryFn:async()=>{const{data:n,error:r}=await q.from("innercircle_contacts").select(_Bn).in("id",s);if(r)throw r;return n??[]}})}function fQt(){const s=Zt();return mt({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 YSt(s){return[s.first_name,s.last_name].filter(Boolean).join(" ")||"Unnamed contact"}function sue(s,t){const n=s==null?void 0:s[t];return n==null||String(n).trim()===""?null:String(n)}function pQt({open:s,onOpenChange:t,contactIds:n,onMerged:r}){const{data:a,isLoading:i}=jBn(n,s),l=fQt(),[o,c]=j.useState(null),[d,u]=j.useState({}),h=j.useMemo(()=>a??[],[a]);j.useEffect(()=>{if(!s){c(v=>v===null?v:null),u(v=>Object.keys(v).length===0?v:{});return}if(h.length&&!o){const v=[...h].sort((y,b)=>YMe(b)-YMe(y))[0];c(v.id)}},[s,h,o]),j.useEffect(()=>{u(v=>Object.keys(v).length===0?v:{})},[o]);const m=j.useMemo(()=>bBn.map(v=>{const y=h.map(w=>({id:w.id,value:sue(w,v.key)})).filter(w=>w.value!==null),b=Array.from(new Set(y.map(w=>w.value)));return{...v,values:y,distinct:b}}).filter(v=>v.distinct.length>1),[h]),f=h.find(v=>v.id===o)??null,g=async()=>{if(!f)return;const v={};for(const[y,b]of Object.entries(d)){const w=h.find(A=>A.id===b);if(!w)continue;const S=sue(w,y);S!==null&&S!==sue(f,y)&&(v[y]=w[y])}try{const y=await l.mutateAsync({primaryId:f.id,duplicateIds:h.filter(b=>b.id!==f.id).map(b=>b.id),overrides:v});y.failed.length?_a({title:`Merged ${y.merged} of ${y.merged+y.failed.length}`,description:y.failed[0].message,variant:"destructive"}):_a({title:`Merged into ${YSt(f)}`,description:"Nothing in their history was lost."}),t(!1),r==null||r()}catch(y){_a({title:"Could not merge",description:y.message,variant:"destructive"})}},x=n.length>10;return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Vz,{className:"h-4 w-4"}),"Merge contacts"]}),e.jsx(Er,{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(Ct,{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(go,{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(v=>e.jsxs("button",{type:"button",onClick:()=>c(v.id),className:`rounded-lg border p-3 text-left transition-colors ${o===v.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:YSt(v)}),o===v.id&&e.jsx($e,{variant:"secondary",children:"Keep"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:v.email||"No email"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:v.phone||"No phone"}),v.created_at&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["Added ",new Date(String(v.created_at)).toLocaleDateString()]})]},v.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(v=>{var b;const y=d[v.key]??(f&&sue(f,v.key)!==null?f.id:(b=v.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:v.label}),e.jsx("div",{className:"flex flex-wrap gap-2",children:v.values.map(w=>e.jsx("button",{type:"button",onClick:()=>u(S=>({...S,[v.key]:w.id})),className:`rounded-md border px-2.5 py-1.5 text-sm transition-colors ${y===w.id?"border-primary bg-primary/10 font-medium":"hover:bg-accent text-muted-foreground"}`,children:w.value},w.id))})]},v.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(Nr,{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(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Merge — this can't be undone"]})]})]})})}const NBn={email:"Same email",phone:"Same phone",name:"Same name"};function kBn(s){return[s.first_name,s.last_name].filter(Boolean).join(" ")||"Unnamed contact"}function SBn({open:s,onOpenChange:t}){const{data:n,isLoading:r,isError:a,error:i}=wBn(s),l=fQt(),[o,c]=j.useState(new Set),[d,u]=j.useState(null),[h,m]=j.useState(!1),f=j.useMemo(()=>(n??[]).filter(v=>v.contact_ids.length>1&&!o.has(v.contact_ids.join(","))),[n,o]),g=f.filter(v=>v.match_type!=="name"),x=async()=>{m(!0);let v=0,y=0;try{for(const b of g){const w=[...b.contacts].sort((E,I)=>YMe(I)-YMe(E))[0],S=(w==null?void 0:w.id)??b.contact_ids[0],A=await l.mutateAsync({primaryId:S,duplicateIds:b.contact_ids.filter(E=>E!==S)});v+=A.merged,y+=A.failed.length}_a({title:`Merged ${v} duplicate${v===1?"":"s"}`,description:y?`${y} could not be merged.`:"Name-only matches still need your review.",variant:y?"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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"flex h-[90dvh] max-h-[90dvh] max-w-2xl flex-col overflow-hidden",children:[e.jsxs(Us,{className:"shrink-0",children:[e.jsx($s,{children:"Find duplicates"}),e.jsx(Er,{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(Ct,{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(v=>{const y=v.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($e,{variant:"secondary",children:NBn[v.match_type]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:v.match_value}),e.jsxs("span",{className:"ml-auto text-xs text-muted-foreground",children:[v.contact_ids.length," records"]})]}),e.jsx("div",{className:"space-y-1",children:v.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:kBn(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(v.contact_ids),children:"Review & merge"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>c(b=>new Set(b).add(y)),children:"Not a duplicate"})]})]},`${v.match_type}-${y}`)})})}),e.jsxs(Nr,{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(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(wn,{className:"mr-2 h-4 w-4"}),"Merge all safe matches (",g.length,")"]})]})]})}),e.jsx(pQt,{open:!!d,onOpenChange:v=>{v||u(null)},contactIds:d??[]})]})}const CBn=()=>{const{user:s}=_s();return st({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})},sDe=s=>{const{user:t}=_s();return st({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})},cit=()=>{const{user:s}=_s();return st({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})},gQt=()=>{const{user:s}=_s();return st({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})},ABn=()=>{const{data:s}=L_(),{data:t}=Uw(),{data:n}=sDe(),{data:r}=gQt(),{data:a}=cit(),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=Eg(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 v=u.tags.map(y=>l.get(y.relationship_type_id)).filter(y=>y!==void 0);v.length>0&&(h=Math.min(...v))}const m=i.get(u.id)||null,f=m?ck(c,Eg(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)},xQt=()=>ABn().filter(t=>t.isDue),EBn=()=>{const s=Zt(),{user:t}=_s();return mt({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"})}})},TBn=()=>{const s=Zt(),{user:t}=_s();return mt({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"})}})},MBn=()=>{const s=Zt(),{user:t}=_s();return mt({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"})}})},PBn=()=>{const{data:s}=sDe(30),t=xQt(),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 IBn(){const{user:s}=_s();return st({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 yQt(s){const{data:t}=IBn(),{data:n}=gQt(),{data:r}=cit(),{data:a}=nBn();return j.useMemo(()=>{const i=a==null?void 0:a.find(v=>v.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=Eg(new Date);if(l&&!nC(l,o))return{nextTouchDate:l,daysUntil:ck(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(v=>v.contact_id===s.id))||[]).sort((v,y)=>new Date(y.completed_at).getTime()-new Date(v.completed_at).getTime())[0],u=d?new Date(d.completed_at):null;let h=90;const m=n==null?void 0:n.find(v=>v.contact_id===s.id&&v.is_active);if(m)h=m.frequency_days;else if(s.tags&&s.tags.length>0){const v=s.tags.map(y=>{const b=r==null?void 0:r.find(w=>w.relationship_type_id===y.relationship_type_id);return b==null?void 0:b.frequency_days}).filter(y=>y!==void 0);v.length>0&&(h=Math.min(...v))}if(!u)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:h,lastTouchDate:null,snoozedUntil:null};const f=Am(Eg(u),h),g=ck(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 ZSt({contact:s}){const t=yQt(s),r=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:vl,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:ca,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:Vr,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:Cv,text:`Snoozed until ${Js(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:Ea,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs($e,{variant:r.variant,className:Pt("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function LBn({contact:s,onLogTouch:t,onSnooze:n}){const r=yQt(s),a=aBn(),[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(vl,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(ca,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(Vr,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(Cv,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(Ea,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ea,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Le,{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:"})," ",Js(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:"})," ",Js(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:"})," ",Js(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(mr,{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(Cv,{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(tDe,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const $9e=768;function RK(){const[s,t]=j.useState(void 0);return j.useEffect(()=>{const n=window.matchMedia(`(max-width: ${$9e-1}px)`),r=()=>{t(window.innerWidth<$9e)};return n.addEventListener("change",r),t(window.innerWidth<$9e),()=>n.removeEventListener("change",r)},[]),!!s}function RBn(){const{user:s}=_s(),{hasLeadSite:t,leadSite:n}=tg(),{data:r,isLoading:a}=st({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 DBn={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"}},FBn={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 CYe({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=DBn[s.status],l=FBn[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(vk,{children:e.jsxs(ry,{children:[e.jsx(ay,{asChild:!0,children:o}),e.jsx(vx,{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 OBn=[{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}],nue=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]},zBn=({open:s,onOpenChange:t,relationshipTypes:n,onSuccess:r})=>{const{user:a}=_s(),{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,v]=j.useState([]),[y,b]=j.useState([]),[w,S]=j.useState([]),[A,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:Ie}=await q.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");b(Ie||[])})()},[s,a==null?void 0:a.id]);const G=Ie=>{S(Fe=>Fe.includes(Ie)?Fe.filter(Ne=>Ne!==Ie):[...Fe,Ie])},Z=async()=>{const Ie=A.trim();if(!(!Ie||!(a!=null&&a.id))){P(!0);try{const{data:Fe,error:Ne}=await q.from("contact_custom_tags").insert({owner_user_id:a.id,name:Ie}).select("id, name, color").single();if(Ne)throw Ne;Fe&&(b(Be=>[...Be,Fe].sort((Se,Ae)=>Se.name.localeCompare(Ae.name))),S(Be=>[...Be,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({}),v([]),S([]),E(""),D([]),V(null),l.current&&(l.current.value="")},ae=()=>{X(),t(!1)},le=Ie=>{const Fe=Ie.split(` `).map(qe=>qe.trim()).filter(qe=>qe);if(Fe.length===0)return{headers:[],data:[]};const Ne=qe=>{const ze=[];let Ve="",ht=!1;for(let Qe=0;Qe0&&(Be[0]=Be[0].replace(/^\uFEFF/,""));const Se=new Map,Ae=Be.map((qe,ze)=>{let Ve=(qe||"").trim();Ve||(Ve=`Column ${ze+1}`);const ht=Se.get(Ve)||0;return Se.set(Ve,ht+1),ht===0?Ve:`${Ve} (${ht+1})`}),Ce=Fe.slice(1).map(Ne);return{headers:Ae,data:Ce}},re=Ie=>{var Be;const Fe=(Be=Ie.target.files)==null?void 0:Be[0];if(!Fe)return;const Ne=new FileReader;Ne.onload=Se=>{var Ve;const Ae=(Ve=Se.target)==null?void 0:Ve.result,{headers:Ce,data:qe}=le(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(ht=>{const Qe=ht.toLowerCase().replace(/[_\s-]/g,"");Qe.includes("firstname")||Qe==="first"?ze.first_name=ht:Qe.includes("lastname")||Qe==="last"?ze.last_name=ht:Qe.includes("spouse")&&Qe.includes("email")?ze.spouse_email=ht:Qe.includes("spouse")||Qe.includes("partner")?ze.spouse_name=ht:Qe.includes("email")?ze.email=ht:Qe.includes("phone")||Qe.includes("mobile")||Qe.includes("cell")?ze.phone=ht:(Qe.includes("address")||Qe.includes("street"))&&(Qe.includes("2")||Qe.includes("second")||Qe.includes("secondary"))?ze.address2=ht:Qe.includes("address")||Qe.includes("street")?ze.address=ht:Qe==="city"?ze.city=ht:Qe==="state"||Qe==="province"?ze.state=ht:Qe==="zip"||Qe==="zipcode"||Qe==="postalcode"?ze.zip=ht:Qe.includes("company")||Qe.includes("organization")||Qe.includes("business")?ze.company_name=ht:Qe.includes("jobtitle")||Qe.includes("title")&&!Qe.includes("spouse")?ze.job_title=ht:Qe.includes("birthday")||Qe.includes("dob")||Qe.includes("birthdate")?ze.birthday=ht:Qe.includes("anniversary")||Qe.includes("homeanniversary")?ze.home_anniversary=ht:(Qe.includes("notes")||Qe.includes("comment"))&&(ze.notes=ht)}),g(ze),c("mapping")},Ne.readAsText(Fe)},te=(Ie,Fe)=>{g(Ne=>{if(Fe==="none"){const{[Ie]:Be,...Se}=Ne;return Se}return{...Ne,[Ie]:Fe}})},J=Ie=>{v(Fe=>Fe.includes(Ie)?Fe.filter(Ne=>Ne!==Ie):[...Fe,Ie])},ce=async()=>{if(!(a!=null&&a.id))return;const{data:Ie}=await q.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),Fe=new Set((Ie||[]).filter(Se=>Se.email).map(Se=>Se.email.toLowerCase())),Ne=new Set((Ie||[]).filter(Se=>Se.phone).map(Se=>Se.phone.replace(/[^0-9]/g,""))),Be=h.map(Se=>{const Ae=Qe=>{const at=f[Qe];if(!at)return"";const rt=d.indexOf(at);return rt>=0?(Se[rt]||"").trim():""},Ce=Ae("first_name"),qe=Ae("email"),ze=Ae("phone"),Ve=Ce.length>0,ht=!!(qe&&Fe.has(qe.toLowerCase())||ze&&Ne.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:Ve,isDuplicate:ht,error:Ve?void 0:"First name is required"}});D(Be),c("preview")},ve=Ie=>{const Fe=Ie.trim().split(/\s+/);return{first_name:Fe[0],last_name:Fe.length>1?Fe.slice(1).join(" "):null}},fe=async()=>{if(!(a!=null&&a.id))return;const Ie=R.filter(Se=>Se.isValid);if(Ie.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}U(!0);let Fe=0,Ne=0,Be=0;try{for(const Se of Ie)try{let Ae=null;if(Se.email){const{data:ze}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Se.email).maybeSingle();Ae=ze}if(!Ae&&Se.phone){const ze=Se.phone.replace(/[^0-9]/g,""),{data:Ve}=await q.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(Ve){const ht=Ve.find(Qe=>Qe.phone&&Qe.phone.replace(/[^0-9]/g,"")===ze);ht&&(Ae={id:ht.id})}}const Ce={owner_user_id:a.id,first_name:Se.first_name,last_name:Se.last_name||null,email:Se.email||null,phone:Se.phone||null,address:Se.address||null,city:Se.city||null,state:Se.state||null,zip:Se.zip||null,address2_label:Se.address2_label||null,address2:Se.address2||null,address2_city:Se.address2_city||null,address2_state:Se.address2_state||null,address2_zip:Se.address2_zip||null,spouse_name:Se.spouse_name||null,spouse_email:Se.spouse_email||null,company_name:Se.company_name||null,job_title:Se.job_title||null,birthday:nue(Se.birthday),home_anniversary:nue(Se.home_anniversary),notes:Se.notes||null};let qe=null;if(Ae){const{data:ze}=await q.from("innercircle_contacts").select("*").eq("id",Ae.id).single();if(ze){const Ve={},ht=["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 Qe of ht){const at=ze[Qe],rt=Ce[Qe];(!at||at==="")&&rt&&(Ve[Qe]=rt)}Object.keys(Ve).length>0&&await q.from("innercircle_contacts").update(Ve).eq("id",Ae.id)}qe=Ae.id,Ne++}else{const{data:ze,error:Ve}=await q.from("innercircle_contacts").insert(Ce).select("id").single();Ve?(console.error("Insert error for contact:",Se.first_name,Ve),Be++):ze?(qe=ze.id,x.length>0&&await q.from("innercircle_contact_tags").insert(x.map(ht=>({contact_id:ze.id,relationship_type_id:ht}))),Fe++):Be++}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&&Se.spouse_name){const ze=ve(Se.spouse_name);let Ve=null;if(Se.spouse_email){const{data:Qe}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Se.spouse_email).maybeSingle();Ve=Qe}if(!Ve){const{data:Qe}=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||Se.last_name||"").maybeSingle();Ve=Qe}let ht=null;if(Ve){ht=Ve.id;const Qe=nue(Se.home_anniversary);Qe&&await q.from("innercircle_contacts").update({home_anniversary:Qe}).eq("id",Ve.id).is("home_anniversary",null)}else{const{data:Qe}=await q.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:ze.first_name,last_name:ze.last_name||Se.last_name||null,email:Se.spouse_email||null,address:Se.address||null,city:Se.city||null,state:Se.state||null,zip:Se.zip||null,home_anniversary:nue(Se.home_anniversary),spouse_name:`${Se.first_name}${Se.last_name?" "+Se.last_name:""}`,spouse_email:Se.email||null,notes:`Spouse of ${Se.first_name} ${Se.last_name||""} (imported via CSV)`.trim()}).select("id").single();Qe&&(ht=Qe.id,Fe++)}ht&&(await q.from("innercircle_contacts").update({spouse_contact_id:ht}).eq("id",qe),await q.from("innercircle_contacts").update({spouse_contact_id:qe}).eq("id",ht))}}catch(Ae){console.error("Error importing contact:",Ae),Be++}V({created:Fe,updated:Ne,failed:Be}),c("result"),(Fe>0||Ne>0)&&r(),i({title:"Import Complete",description:`${Fe} created, ${Ne} updated${Be>0?`, ${Be} failed`:""}.`})}catch(Se){console.error("Import error:",Se),i({title:"Import Failed",description:Se.message||"Failed to import contacts",variant:"destructive"})}finally{U(!1)}},ue=R.filter(Ie=>Ie.isValid).length,be=R.filter(Ie=>!Ie.isValid).length,Ee=R.filter(Ie=>Ie.isValid&&Ie.isDuplicate).length,ke=ue-Ee;return e.jsx(Os,{open:s,onOpenChange:ae,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(KN,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(Er,{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:re,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 Ie;return(Ie=l.current)==null?void 0:Ie.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Supported Fields:"}),e.jsx("p",{className:"text-muted-foreground text-xs mb-3",children:"First Name, Last Name, Email, Phone, Street Address, City, State, Zip, Spouse Name, Spouse Email, Company, Job Title, Birthday, Home Anniversary, Notes"}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{const Ie=`First Name,Last Name,Email,Phone,Street Address,City,State,Zip,Spouse Name,Spouse Email,Company,Job Title,Birthday,Home Anniversary,Notes John,Doe,john@example.com,555-123-4567,123 Main St,Austin,TX,78701,Jane Doe,jane@example.com,ABC Realty,Real Estate Agent,1985-06-15,2020-03-22,Met at open house`,Fe=new Blob([Ie],{type:"text/csv"}),Ne=URL.createObjectURL(Fe),Be=document.createElement("a");Be.href=Ne,Be.download="contact_import_template.csv",Be.click(),URL.revokeObjectURL(Ne)},children:[e.jsx(ji,{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:OBn.map(Ie=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(ee,{className:"w-40 text-sm",children:[Ie.label,Ie.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(ms,{value:f[Ie.key]||"none",onValueChange:Fe=>te(Ie.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))]})]})]},Ie.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(Ie=>e.jsx($e,{variant:x.includes(Ie.id)?"default":"outline",className:"cursor-pointer",onClick:()=>J(Ie.id),children:Ie.name},Ie.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."}),y.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:y.map(Ie=>{const Fe=w.includes(Ie.id);return e.jsxs($e,{variant:Fe?"default":"outline",className:"cursor-pointer gap-1",style:Fe&&Ie.color?{backgroundColor:Ie.color,borderColor:Ie.color}:void 0,onClick:()=>G(Ie.id),children:[Ie.name,Fe&&e.jsx(mr,{className:"h-3 w-3"})]},Ie.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:A,onChange:Ie=>E(Ie.target.value),onKeyDown:Ie=>{Ie.key==="Enter"&&(Ie.preventDefault(),Z())},className:"max-w-xs"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:Z,disabled:!A.trim()||I,children:[I?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(cn,{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(Vr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[ke," new"]})]}),Ee>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(vl,{className:"h-4 w-4"}),e.jsxs("span",{children:[Ee," existing (will merge gaps)"]})]}),be>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(vl,{className:"h-4 w-4"}),e.jsxs("span",{children:[be," 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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:R.slice(0,100).map((Ie,Fe)=>e.jsxs(An,{children:[e.jsx(wt,{children:Ie.first_name}),e.jsx(wt,{children:Ie.last_name}),e.jsx(wt,{children:Ie.email}),e.jsx(wt,{children:Ie.phone}),e.jsx(wt,{children:Ie.isValid?Ie.isDuplicate?e.jsx($e,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx($e,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx($e,{variant:"destructive",children:Ie.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(Vr,{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(Nr,{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:fe,disabled:O||ue===0,children:O?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{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 BBn(){return"contacts"in navigator&&"ContactsManager"in window}function $Bn(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 UBn({open:s,onOpenChange:t,onComplete:n}){const{user:r}=_s(),{data:a}=L_(),i=x6e(),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,v]=j.useState(0),y=BBn(),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(),Z=(ae=V.phone)==null?void 0:ae.replace(/\D/g,"");return G&&U.has(G)?{...V,isDuplicate:!0,duplicateField:"email"}:Z&&Z.length>=7&&W.has(Z)?{...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(Z=>{var le,re,te,J;const ae=(((le=Z.name)==null?void 0:le[0])||"").split(" ");return{first_name:ae[0]||"",last_name:ae.slice(1).join(" "),email:((re=Z.email)==null?void 0:re[0])||"",phone:((te=Z.tel)==null?void 0:te[0])||"",address:(J=Z.address)!=null&&J[0]?[Z.address[0].streetAddress,Z.address[0].city,Z.address[0].region,Z.address[0].postalCode].filter(Boolean).join(", "):""}}),V=b(W);u(V);const G=new Set;V.forEach((Z,X)=>{Z.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 re;const Z=(re=G.target)==null?void 0:re.result,X=$Bn(Z);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 le=new Set;ae.forEach((te,J)=>{te.isDuplicate||le.add(J)}),m(le),c("preview")},W.readAsText(U),l.current&&(l.current.value="")},A=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++,v(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),v(0),o==="done"&&n()),t(O)},R=d.filter(O=>O.isDuplicate).length,D=h.size;return e.jsx(Os,{open:s,onOpenChange:P,children:e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(g1,{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(Er,{children:"Add contacts from your phone directly into Agent OS."})]}),o==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[y&&e.jsxs($,{onClick:w,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(g1,{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:[y&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),y&&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:y?"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:y?"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"}),!y&&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(go,{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($e,{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:A,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(Ct,{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(ma,{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"})]})]})})}function qBn(s){return st({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 VBn(){const{user:s}=_s();return st({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 HBn(){const{user:s}=_s();return st({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 vQt(){const{user:s}=_s(),t=Zt();return mt({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 bQt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function _Qt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const GBn=100;function WBn({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=Zn(),o=Sa(),c=vQt(),[d,u]=j.useState([]),[h,m]=j.useState(!1),[f,g]=j.useState(""),[x,v]=j.useState(null),[y,b]=j.useState(""),[w,S]=j.useState(""),[A,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>GBn;j.useEffect(()=>{s&&(v(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 le=x.share_token?`https://video.relevelup.com/share/video/${x.share_token}`:"",re=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(""),ve=ae?_Qt(ae):le,fe=ae?``:"";return`
${ce}

▶ Watch Video

${fe}
`},V=async()=>{if(!x)return;E(!0),P({done:0,total:R.length,failed:0});let X=0,ae=0;for(const le of R)try{let re;try{re=(await c.mutateAsync({video_id:x.id,recipient_email:le.email,recipient_name:`${le.first_name} ${le.last_name||""}`.trim(),contact_id:le.id,sent_via:"gmail"})).share_token}catch(fe){console.warn("Tracking record failed for",le.email,fe)}const te=W(le.first_name,re),J=y.replace(/\{\{first_name\}\}/gi,le.first_name),{data:ce,error:ve}=await q.functions.invoke("gmail-send",{body:{to:le.email,subject:J,body:te,contactId:le.id}});if(ve||!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||(ve==null?void 0:ve.message)||"Send failed");X+=1}catch(re){console.error("Failed to send to",le.email,re),ae+=1}finally{P({done:X+ae,total:R.length,failed:ae}),await new Promise(re=>setTimeout(re,250))}E(!1),ae===0?ne.success(`Video sent to ${X} ${X===1?"contact":"contacts"}!`):ne.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:y,initialBodyHtml:X}}),t(!1)},Z=!!x&&!!y.trim()&&R.length>0&&(O?a:r);return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"h-5 w-5 text-primary"}),"Send Video to ",R.length," ",R.length===1?"Contact":"Contacts"]}),e.jsxs(Er,{children:[O?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(gm,{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(pn,{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(vl,{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(vl,{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(cn,{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(xn,{className:"h-14 w-full"}),e.jsx(xn,{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:()=>v(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(nf,{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(Ou,{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(Vc,{}),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:y,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"})]}),A&&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:A,children:"Cancel"}),O?e.jsxs($,{onClick:G,disabled:!Z,className:"gap-2",children:[e.jsx(gm,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs($,{onClick:V,disabled:!Z||A,className:"gap-2",children:[A?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),A?"Sending…":`Send to ${R.length}`]})]})]})]})})}function Mie(){const s=Sa();return st({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 KBn(s){return st({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 YBn(){const s=Sa(),t=Zt();return mt({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 wQt(){const s=Zt();return mt({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 ZBn(){const s=Zt();return mt({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 dit(){const s=Sa(),t=Zt();return mt({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 jQt(s){return st({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 XBn(){const s=Zt();return mt({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 QBn(){const s=Zt();return mt({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 JBn(){const s=Zt();return mt({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 e9n(s){return st({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 t9n(s){return st({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 uit(){const s=Zt();return mt({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 s9n(){const s=Zt();return mt({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 n9n=[{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"}],nDe={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"},r9n={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 a9n({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(""),[v,y]=j.useState(!1);j.useEffect(()=>{if(!s)return;let w=!1;return(async()=>{var S,A;o(!0);try{const{data:E}=await q.auth.getSession();g||x(((A=(S=E==null?void 0:E.session)==null?void 0:S.user)==null?void 0:A.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||ne.error("Could not build preview")}finally{w||o(!1)}})(),()=>{w=!0}},[s,n,r,a]);const b=async()=>{if(g.trim()){y(!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?ne.success(`Test email sent to ${g.trim()}`):ne.error((w==null?void 0:w.error)||"Could not send test email",{duration:1e4})}catch{ne.error("Could not send test email")}finally{y(!1)}}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{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($s,{children:["Email preview",i?` — ${i}`:""]}),e.jsx(Er,{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(ZN,{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(g1,{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(Ct,{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:v||!g.trim(),children:[v?e.jsx(Ct,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4 mr-1.5"}),"Send test"]})]})]})]})})}function e9({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:v})=>{u(v||[]),m(!1)}))},[o,s]);const x=d.filter(v=>!f||(v.title||v.recipient_name||"").toLowerCase().includes(f.toLowerCase()));return e.jsxs(Os,{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(nf,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(Fs,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx($s,{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:v=>g(v.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(xn,{className:"h-16 w-full"}),e.jsx(xn,{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(v=>e.jsxs("button",{onClick:()=>{t(v.playback_url||""),n==null||n(v),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:v.thumbnail_url?e.jsx("img",{src:v.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:y=>{const b=y.currentTarget.parentElement;if(b){y.currentTarget.remove();const w=document.createElement("span");w.innerHTML="🎬",w.className="text-lg",b.appendChild(w)}}}):e.jsx(fa,{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:v.title||v.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.duration_seconds?`${Math.round(v.duration_seconds)}s`:"",v.created_at?` · ${new Date(v.created_at).toLocaleDateString()}`:""]})]})]},v.id))})]})]})}function i9n(){return st({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 o9n(s){return st({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 l9n(){const{user:s}=_s();return st({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 c9n(){const{user:s}=_s(),t=Zt();return mt({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 d9n(s){const{user:t}=_s();return st({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 u9n(s){return st({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 f3(){const{user:s}=_s(),t=Zt();return mt({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 h9n(){const s=Zt();return mt({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 m9n(){const s=Zt();return mt({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 rDe(){const{user:s}=_s();return st({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 NQt(){const{data:s,isLoading:t}=rDe(),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 k6(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 S6(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 hk(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 f9n(){const{user:s}=_s(),t=Zt();return mt({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 kQt({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=L_(),{data:a}=rDe(),i=f3(),l=j.useRef(null),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,v]=j.useState(!1),[y,b]=j.useState(0),[w,S]=j.useState("idle"),A=(a==null?void 0:a.total_storage_mb)||0,I=((a==null?void 0:a.max_storage_mb)||1024)-A,P=U=>{var G;const W=(G=U.target.files)==null?void 0:G[0];if(!W)return;if(!W.type.startsWith("video/")){ne.error("Please select a video file");return}const V=W.size/(1024*1024);if(V>500){ne.error("Video file must be less than 500MB");return}if(V>I){ne.error(`Not enough storage. You have ${I.toFixed(1)} MB remaining.`);return}c(W),d||u(W.name.replace(/\.[^/.]+$/,""))},R=async()=>{if(!o){ne.error("Please select a video file");return}v(!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:Z,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((re,te)=>{const J=new XMLHttpRequest;J.upload.addEventListener("progress",ce=>{if(ce.lengthComputable){const ve=Math.round(ce.loaded/ce.total*100);b(ve)}}),J.addEventListener("load",()=>{J.status>=200&&J.status<300?re():te(new Error(`Upload failed with status ${J.status}`))}),J.addEventListener("error",()=>te(new Error("Upload failed"))),J.open("PUT",Z.uploadUrl),J.setRequestHeader("AccessKey",Z.apiKey),J.send(o)}),S("processing");const ae=o.size/(1024*1024),le=`https://iframe.mediadelivery.net/embed/${G}/${V}`;await i.mutateAsync({bunny_video_id:V,playback_url:le,file_size_mb:ae,title:d||o.name,notes:h||void 0,contact_id:f||void 0,status:"processing",touch_type:"video_upload"}),ne.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(le),D()}catch(U){console.error("Upload error:",U),ne.error(U instanceof Error?U.message:"Failed to upload video")}finally{v(!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... ${y}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(Os,{open:s,onOpenChange:D,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Upload Video"}),e.jsx(Er,{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(fa,{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(mr,{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(Ct,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:O()})]}),e.jsx(Yi,{value:w==="uploading"?y:w==="processing"?100:10})]})]}),e.jsxs(Nr,{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(Ct,{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 p9n=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],g9n={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},XSt=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 SQt({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}=KBn(o||void 0),{data:u,isLoading:h}=jQt(o||void 0),m=YBn(),f=wQt(),g=XBn(),[x,v]=j.useState(""),[y,b]=j.useState(""),[w,S]=j.useState("nurture"),[A,E]=j.useState("🌱"),[I,P]=j.useState("");j.useEffect(()=>{d?(v(d.name),b(d.description||""),S(d.category),E(d.icon),P(d.goal||"")):c||(v(""),b(""),S("nurture"),E("🌱"),P(""))},[d,c,s]);const R=r9n[w],D=async()=>{if(!x.trim()){ne.error("Give your campaign a name");return}try{if(c&&o)await f.mutateAsync({id:o,name:x,description:y,category:w,icon:A,goal:I,cover_color:R}),ne.success("Campaign updated");else{const U=await m.mutateAsync({name:x,description:y,category:w,icon:A,goal:I,cover_color:R});return ne.success("Campaign created — now add your first step!"),a(U.id),l("steps"),U}}catch(U){ne.error(U.message||"Failed to save")}},O=async()=>{if(!o){ne.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{ne.error("Failed to add step")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{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:A}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx($s,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(Er,{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(pa,{value:i,onValueChange:U=>l(U),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(ga,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(Xt,{value:"details",children:"Details"}),e.jsxs(Xt,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(Qt,{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=>v(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:y,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(nDe).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:p9n.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 ${A===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(Qt,{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(wn,{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(cn,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((U,W)=>e.jsx(x9n,{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(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(cn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(Nr,{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(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function x9n({step:s,index:t,totalSteps:n}){const r=QBn(),a=JBn(),i=Sa(),[l,o]=j.useState(!1),[c,d]=j.useState(()=>({...s,body:XSt(s.body)})),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(""),[v,y]=j.useState(!1),[b,w]=j.useState(!1);j.useEffect(()=>{d({...s,body:XSt(s.body)})},[s]);const S=JSON.stringify(c)!==JSON.stringify(s),A=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}),ne.success(`Step ${t+1} saved`)}catch{ne.error("Failed to save step")}finally{h(!1)}},E=async()=>{if(await mo(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),ne.success("Step deleted")}catch{ne.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(Ea,{className:"h-3 w-3"}):e.jsx(ca,{className:"h-3 w-3"}),e.jsx("span",{children:P()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(pn,{className:"h-3 w-3"}):e.jsx(no,{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(xb,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(wl,{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:"}),n9n.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(fa,{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(e9,{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:()=>y(!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(Sd,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(kQt,{open:v,onOpenChange:y,onUploadComplete:R=>d({...c,video_url:R})}),e.jsx(Os,{open:m,onOpenChange:f,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Add video URL"}),e.jsx(Er,{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(Nr,{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(qn,{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(Ta,{className:"h-3.5 w-3.5 mr-1.5"})," Preview"]}),e.jsxs($,{size:"sm",onClick:A,disabled:!S||u,children:[u&&e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]}),e.jsx(a9n,{open:b,onOpenChange:w,subject:c.subject||"",body:c.body||"",ownerUserId:i,stepLabel:`Step ${t+1}`})]})]})}function y9n({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=Mie(),l=uit(),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState(!1),f=(a||[]).filter(v=>!v.is_starter),g=f.filter(v=>v.name.toLowerCase().includes(o.toLowerCase())||(v.description||"").toLowerCase().includes(o.toLowerCase())),x=async()=>{if(d)try{const v=await l.mutateAsync({campaignId:d,contactIds:n}),y=[`${v.enrolled} enrolled`];v.skipped>0&&y.push(`${v.skipped} skipped`),v.errors>0&&y.push(`${v.errors} errors`),ne.success(y.join(" · ")),t(!1),u(null),r==null||r()}catch(v){ne.error(v.message||"Failed to enroll contacts")}};return e.jsxs(Os,{open:s,onOpenChange:t,children:[e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(Er,{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:v=>c(v.target.value),className:"pl-9 h-9"})]}),e.jsx(go,{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(wn,{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(cn,{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(v=>e.jsxs("button",{onClick:()=>u(v.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===v.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 ${v.cover_color} flex items-center justify-center text-lg`,children:v.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:v.name}),v.is_active&&e.jsx($e,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:v.description})]}),d===v.id&&e.jsx(ma,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},v.id))})})]}),e.jsxs(Nr,{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(cn,{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(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(SQt,{open:h,onOpenChange:m})]})}function v9n({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=Zn(),{data:c}=Uw(),d=pHs(),u=Zt(),{isGmailConnected:h}=Gy(),{isReady:m}=FB(),{data:f}=QB(),g=Hat(),x=CXt(),[v,y]=j.useState(!1),[b,w]=j.useState(!1),[S,A]=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),Z=s.size;if(Z===0)return null;const X=async ve=>{y(!0);try{const ue=Array.from(s).map(Ee=>({contact_id:Ee,relationship_type_id:ve})),{error:be}=await q.from("innercircle_contact_tags").upsert(ue,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(be)throw be;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),_a({title:`Assigned type to ${Z} contacts`}),n()}catch(fe){_a({title:"Error assigning type",description:fe.message,variant:"destructive"})}finally{y(!1)}},ae=async ve=>{y(!0);try{const fe=Array.from(s);for(const ue of fe)try{await x.mutateAsync({contactId:ue,tagId:ve})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),_a({title:`Tagged ${Z} contacts`}),R(!1),O("")}catch(fe){_a({title:"Error adding tags",description:fe.message,variant:"destructive"})}finally{y(!1)}},le=async()=>{if(D.trim()){y(!0);try{const ve=await g.mutateAsync({name:D.trim()});await ae(ve.id)}catch(ve){_a({title:"Error creating tag",description:ve.message,variant:"destructive"}),y(!1)}}},re=(f==null?void 0:f.filter(ve=>ve.name.toLowerCase().includes(D.toLowerCase())))||[],te=f==null?void 0:f.find(ve=>ve.name.toLowerCase()===D.trim().toLowerCase()),J=()=>{const ve=t.filter(Fe=>s.has(Fe.id)),fe=["First Name","Last Name","Email","Phone","Street Address","City","State","ZIP","Full Address","Birthday","Home Anniversary","Notes","Relationship Types"],ue=ve.map(Fe=>{var Ve;const Ne=Fe,Be=Ne.address||"",Se=Ne.city||"",Ae=Ne.state||"",Ce=Ne.zip||Ne.zip_code||"",qe=[Se,[Ae,Ce].filter(Boolean).join(" ")].filter(Boolean).join(", "),ze=[Be,qe].filter(Boolean).join(", ");return[Fe.first_name,Fe.last_name||"",Fe.email||"",Fe.phone||"",Be,Se,Ae,Ce,ze,Fe.birthday||"",Fe.home_anniversary||"",Fe.notes||"",((Ve=Fe.tags)==null?void 0:Ve.map(ht=>{var Qe;return(Qe=ht.relationship_type)==null?void 0:Qe.name}).join("; "))||""]}),be=[fe.join(","),...ue.map(Fe=>Fe.map(Ne=>`"${(Ne||"").replace(/"/g,'""')}"`).join(","))].join(` `),Ee=new Blob([be],{type:"text/csv"}),ke=URL.createObjectURL(Ee),Ie=document.createElement("a");Ie.href=ke,Ie.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,Ie.click(),URL.revokeObjectURL(ke),_a({title:`Exported ${Z} contacts`})},ce=async()=>{if(!await mo(`Are you sure you want to delete ${Z} contacts? This cannot be undone.`))return;const ve=Array.from(s);y(!0),G({done:0,total:ve.length});try{const fe=await d.mutateAsync({ids:ve,onProgress:(ue,be)=>G({done:ue,total:be})});n(),_a({title:`Deleted ${fe.toLocaleString()} contacts`})}catch(fe){const ue=typeof(fe==null?void 0:fe.deleted)=="number"?fe.deleted:0;_a({title:"Error deleting contacts",description:ue>0?`${ue.toLocaleString()} of ${ve.length.toLocaleString()} were deleted before this failed: ${fe.message}`:fe.message,variant:"destructive"})}finally{G(null),y(!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($e,{variant:"secondary",className:"font-semibold",children:[Z," 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:v,children:[e.jsx(us,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Cp,{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(ve=>ve.active).map(ve=>e.jsx(Ge,{value:ve.id,children:ve.name},ve.id))})]}),e.jsxs(Gd,{open:P,onOpenChange:R,children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",disabled:v,children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(Dd,{className:"w-56 p-2",align:"start",children:[e.jsx(pe,{placeholder:"Search or create tag...",value:D,onChange:ve=>O(ve.target.value),onKeyDown:ve=>{ve.key==="Enter"&&D.trim()&&!te?(ve.preventDefault(),le()):ve.key==="Enter"&&te&&(ve.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:[re.map(ve=>e.jsxs("button",{onClick:()=>ae(ve.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:ve.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:ve.name})]},ve.id)),D.trim()&&!te&&e.jsxs("button",{onClick:le,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(cn,{className:"h-3.5 w-3.5"}),'Create "',D.trim(),'"']}),re.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:v,children:[e.jsx(pn,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),m&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{const ve=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${ve}`)},disabled:v,children:[e.jsx(gm,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>A(!0),disabled:v,children:[e.jsx(fa,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>I(!0),disabled:v,children:[e.jsx(wn,{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:v,children:[e.jsx(p1,{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:v,children:[e.jsx(S4,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),Z>=2&&Z<=10&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>W(!0),disabled:v,children:[e.jsx(Vz,{className:"h-3.5 w-3.5 mr-1"}),"Merge"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:J,disabled:v,children:[e.jsx(ji,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:ce,disabled:v,className:"text-destructive hover:text-destructive",children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:n,className:"ml-auto",children:[e.jsx(mr,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(pQt,{open:U,onOpenChange:W,contactIds:Array.from(s),onMerged:n}),e.jsx(y9n,{open:E,onOpenChange:I,contactIds:Array.from(s),onSuccess:n}),e.jsx(Nk,{open:b,onOpenChange:w,bulkContacts:Array.from(s).map(ve=>{const fe=t.find(ue=>ue.id===ve);return fe?{id:fe.id,first_name:fe.first_name,last_name:fe.last_name,email:fe.email||""}:null}).filter(ve=>ve!==null&&ve.email!==""),onSendComplete:()=>{w(!1),n()}}),e.jsx(WBn,{open:S,onOpenChange:A,contacts:Array.from(s).map(ve=>t.find(fe=>fe.id===ve)).filter(ve=>!!ve).map(ve=>({id:ve.id,first_name:ve.first_name,last_name:ve.last_name,email:ve.email})),isGmailConnected:!!h,isMassEmailReady:!!m,onSendComplete:()=>{A(!1),n()}})]})}function QSt({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=Zn(),{isReady:d}=FB(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(o_,{className:"h-4 w-4"})})}),e.jsxs(Cu,{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(fa,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(ja,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(ui,{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(pn,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(ja,{onClick:()=>r(s.id,u),children:[e.jsx(Cv,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(ja,{onClick:()=>a(s.id),children:[e.jsx(p1,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(ja,{onClick:()=>l(s.id),children:[e.jsx(S4,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(ja,{onClick:()=>t(s),children:[e.jsx(pi,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ja,{onClick:()=>n(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(qn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function JSt({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=Gat(),a=AXt(),i=EXt(),[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(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Sw,{className:"h-3.5 w-3.5"}),"Smart Filters",r&&r.length>0&&e.jsx($e,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r.length}),e.jsx(wl,{className:"h-3.5 w-3.5"})]})}),e.jsxs(Cu,{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(qn,{className:"h-3 w-3 text-destructive"})})]},m.id)),e.jsx(P0,{})]}):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(OI,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Fs,{className:"max-w-sm",children:[e.jsx(Us,{children:e.jsx($s,{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 ZMe=[{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"}],CQt=[{value:"home_anniversary",label:"Home anniversary"},{value:"wedding_anniversary",label:"Wedding anniversary"}],b9n=[{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 _9n({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}=OB(),g=j.useMemo(()=>{const y=new Map;return(f||[]).forEach(b=>{y.set(b.name.trim().toLowerCase(),{value:`name:${b.name}`,label:b.name})}),(c||[]).forEach(b=>{const w=b.trim().toLowerCase();!w||y.has(w)||y.set(w,{value:`name:${b}`,label:b})}),Array.from(y.values()).sort((b,w)=>b.label.localeCompare(w.label))},[f,c]);j.useEffect(()=>{s&&u(r)},[s,r]);const x=y=>u(b=>({...b,...y})),v=Object.entries(d).filter(([,y])=>y!==void 0&&y!==!1&&y!=="").length;return e.jsx(Vy,{open:s,onOpenChange:t,children:e.jsxs(uy,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(I0,{children:[e.jsxs(L0,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(IB,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(pa,{value:h,onValueChange:y=>m(y),className:"mt-4",children:[e.jsxs(ga,{className:"grid w-full grid-cols-3",children:[e.jsxs(Xt,{value:"contact",className:"gap-1.5",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(Xt,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(rf,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(Xt,{value:"engagement",children:"Engagement"})]}),e.jsxs(Qt,{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(y=>e.jsx(Ge,{value:y.id,children:y.name},y.id))]})]})]}),e.jsxs(sA,{title:"Contact Info Present",children:[e.jsx(Wb,{label:"Has email",checked:d.hasEmail===!0,onChange:y=>x({hasEmail:y||void 0})}),e.jsx(Wb,{label:"Has phone",checked:d.hasPhone===!0,onChange:y=>x({hasPhone:y||void 0})}),e.jsx(Wb,{label:"Has address",checked:d.hasAddress===!0,onChange:y=>x({hasAddress:y||void 0})}),e.jsx(Wb,{label:"Has birthday",checked:d.hasBirthday===!0,onChange:y=>x({hasBirthday:y||void 0})}),e.jsx(Wb,{label:"Has spouse",checked:d.hasSpouse===!0,onChange:y=>x({hasSpouse:y||void 0})}),e.jsx(Wb,{label:"Has company / job",checked:d.hasCompany===!0,onChange:y=>x({hasCompany:y||void 0})}),e.jsx(Wb,{label:"Has notes",checked:d.hasNotes===!0,onChange:y=>x({hasNotes:y||void 0})})]}),e.jsxs(sA,{title:"Location",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(U9e,{label:"City",value:d.city||"",onChange:y=>x({city:y||void 0}),placeholder:"Any city"}),e.jsx(U9e,{label:"State",value:d.state||"",onChange:y=>x({state:y||void 0}),placeholder:"Any state"})]}),e.jsx(U9e,{label:"ZIP / Postal",value:d.zip||"",onChange:y=>x({zip:y||void 0}),placeholder:"Any ZIP"})]}),e.jsxs(sA,{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:y=>x({birthdayMonth:y==="all"?void 0:Number(y)}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Any month"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any month"}),ZMe.map(y=>e.jsx(Ge,{value:String(y.value),children:y.label},y.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:y=>x({anniversaryField:y}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Field"})}),e.jsx(hs,{children:CQt.map(y=>e.jsx(Ge,{value:y.value,children:y.label},y.value))})]}),e.jsxs(ms,{value:d.anniversaryMonth?String(d.anniversaryMonth):"all",onValueChange:y=>x({anniversaryMonth:y==="all"?void 0:Number(y)}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Any month"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any month"}),ZMe.map(y=>e.jsx(Ge,{value:String(y.value),children:y.label},y.value))]})]})]})]})]}),e.jsx(sA,{title:"Date Added",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(eCt,{label:"From",value:d.dateAddedFrom,onChange:y=>x({dateAddedFrom:y||void 0})}),e.jsx(eCt,{label:"To",value:d.dateAddedTo,onChange:y=>x({dateAddedTo:y||void 0})})]})}),e.jsx(sA,{title:"Lead Source",children:e.jsxs(ms,{value:d.leadSourceId||"all",onValueChange:y=>x({leadSourceId:y==="all"?void 0:y}),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(y=>e.jsx(Ge,{value:y.value,children:y.label},y.value))]})]})})]}),e.jsx(Qt,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(sA,{title:"Last Active On Site",children:[e.jsx(yw,{value:d.lastActive||"",onValueChange:y=>x({lastActive:y||void 0}),className:"grid grid-cols-2 gap-2",children:b9n.map(y=>e.jsxs("label",{className:"flex items-center gap-2 rounded-md border px-3 py-2 cursor-pointer hover:bg-accent",children:[e.jsx(Km,{value:y.value}),e.jsx("span",{className:"text-sm",children:y.label})]},y.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(sA,{title:"Registration",children:[e.jsx(Wb,{label:"Registered on lead site",checked:d.registered==="yes",onChange:y=>x({registered:y?"yes":void 0})}),e.jsx(Wb,{label:"Anonymous visitors only",checked:d.registered==="no",onChange:y=>x({registered:y?"no":void 0})})]}),e.jsxs(sA,{title:"Property Activity",children:[e.jsx(Wb,{label:"Viewed any listing",checked:d.viewedListing==="any",onChange:y=>x({viewedListing:y?"any":void 0})}),e.jsx(Wb,{label:"Hot buyer — 3+ views in last 7 days",checked:d.viewedListing==="multiple7d",onChange:y=>x({viewedListing:y?"multiple7d":void 0})}),e.jsx(Wb,{label:"Saved a property",checked:!!d.savedProperty,onChange:y=>x({savedProperty:y||void 0})}),e.jsx(Wb,{label:"Has an active saved search / alert",checked:!!d.hasSavedSearch,onChange:y=>x({hasSavedSearch:y||void 0})})]}),e.jsxs(sA,{title:"Requests",children:[e.jsx(Wb,{label:"Requested a showing / asked a question",checked:!!d.requestedShowing,onChange:y=>x({requestedShowing:y||void 0})}),e.jsx(Wb,{label:"Requested a home valuation",checked:!!d.requestedValuation,onChange:y=>x({requestedValuation:y||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(Qt,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(Wb,{label:"Any website activity",checked:!!d.websiteActiveOnly,onChange:y=>x({websiteActiveOnly:y||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(TOt,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx($,{variant:"ghost",onClick:()=>u({}),disabled:v===0,children:"Clear behavior filters"}),e.jsx($,{onClick:()=>{a(d),t(!1)},children:"Apply"})]})]})})}function sA({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 Wb({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(jn,{checked:t,onCheckedChange:n})]})}function U9e({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(mr,{className:"h-3 w-3"})})]})]})}function eCt({label:s,value:t,onChange:n}){const[r,a]=j.useState(!1),i=t?pv(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(Gd,{open:r,onOpenChange:a,children:[e.jsx(Wd,{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(Ea,{className:"mr-2 h-3.5 w-3.5"}),i?Js(i,"MMM d, yyyy"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Dd,{className:"w-auto p-0",align:"start",children:e.jsx(A2,{mode:"single",selected:i,onSelect:l=>{n(l?Js(l,"yyyy-MM-dd"):void 0),a(!1)},initialFocus:!0})})]})]})}function w9n({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=ZMe.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=ZMe.find(i=>i.value===s.anniversaryMonth),a=((n=CQt.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 ${Js(pv(s.dateAddedFrom),"MMM d, yyyy")}`}),s.dateAddedTo&&t.push({key:"dateAddedTo",label:`Added on/before ${Js(pv(s.dateAddedTo),"MMM d, yyyy")}`}),s.leadSourceId&&t.push({key:"leadSourceId",label:s.leadSourceId==="none"?"No lead source":"Lead source"}),t}function N9n(){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 k9n(){const s=Sa();return st({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 dSr(){const s=Sa();return st({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 uSr(){const s=Sa(),t=Zt();return mt({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 hSr(){const s=Zt();return mt({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 S9n(){const s=Sa();return st({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 mSr(){const s=Sa(),t=Zt();return mt({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 fSr(){const s=Zt();return mt({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 pSr(){const s=Sa();return st({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 gSr(){const s=Sa(),t=Zt();return mt({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 xSr(){const s=Zt();return mt({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 ySr(){const s=Zt();return mt({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 vSr(){const s=Zt();return mt({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 bSr(){const s=Sa();return st({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 _Sr(){const s=Sa();return st({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 wSr(){const s=Sa();return st({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 jSr(s){const{leadSiteId:t,filters:n,enabled:r}=s,a=JSON.stringify(n);return st({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 AQt(s,t,n){const r=Zt(),{token:a}=N9n();return mt({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:v}=await q.from(s).update({latitude:x,longitude:g}).eq("id",d.id);v||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 NSr(){return AQt("listings","sphere-map-listings",{one:"listing",many:"listings"})}function kSr(){return AQt("open_houses","sphere-map-open-houses",{one:"open house",many:"open houses"})}const SSr={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 C9n(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 CSr(s){return s===null?"never":s>=365?"red":s>=180?"orange":s>=90?"yellow":"green"}function A9n(s){return`${s.first_name??""} ${s.last_name??""}`.trim()||"Unnamed contact"}function E9n(s){return[s.address,[s.city,s.state].filter(Boolean).join(", "),s.zip].filter(Boolean).join(" · ")}function ASr(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=>C9n(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?A9n(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:E9n(r[0]),gapDays:i}})}const T9n=3958.8;function EQt(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*T9n*Math.asin(Math.sqrt(o))}function M9n(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 ESr(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 TSr(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 MSr(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=EQt(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)M9n(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 TQt(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 I9n({selected:s,onChange:t,className:n}){const{neighborhoods:r,unmappedCount:a,isLoading:i}=hit(),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(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:`gap-1.5 h-8 rounded-lg ${n??""}`,children:[e.jsx(ui,{className:"h-3.5 w-3.5"}),"Neighborhoods",s.length>0&&e.jsx($e,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:s.length})]})}),e.jsxs(Dd,{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(Ct,{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(br,{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(br,{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 D$(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 sX(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function L9n(){const{user:s}=_s(),{leadSite:t,hasLeadSite:n}=tg(),{data:r,isLoading:a}=st({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=(y,b)=>{const w=i.get(y)||sX();i.set(y,{...w,...b})},o=await D$((y,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(y,b)),c=new Map,d=new Map;o.forEach(y=>{if(!y.contact_id)return;c.set(y.id,y.contact_id),y.email&&d.set(y.email.toLowerCase(),y.contact_id);const b=i.get(y.contact_id);(!b||!b.lastActiveAt||y.last_seen_at>b.lastActiveAt)&&l(y.contact_id,{lastActiveAt:y.last_seen_at})});const u=await D$((y,b)=>q.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(y,b)),h=new Map;u.forEach(y=>{y.contact_id&&(h.set(y.user_id,y.contact_id),l(y.contact_id,{registered:!0}))});const m=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await D$((y,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(y,b))).forEach(y=>{const b=y.visitor_id?c.get(y.visitor_id):null;if(!b)return;const w=i.get(b)||sX();w.propertyViewCount+=1,y.viewed_at>=m&&(w.propertyViewCount7d+=1),i.set(b,w)}),(await D$((y,b)=>q.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(y,b))).forEach(y=>{const b=h.get(y.user_id);if(!b)return;const w=i.get(b)||sX();w.savedListingCount+=1,i.set(b,w)}),(await D$((y,b)=>q.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(y,b))).forEach(y=>{const b=h.get(y.user_id);if(!b)return;const w=i.get(b)||sX();w.activeSavedSearchCount+=1,i.set(b,w)}),(await D$((y,b)=>q.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(y,b))).forEach(y=>{if(!y.email)return;const b=d.get(y.email.toLowerCase());if(!b)return;const w=i.get(b)||sX(),S=(y.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 MQt="innercircle_geocode_cache_v1";function R9n(){try{return JSON.parse(localStorage.getItem(MQt)||"{}")}catch{return{}}}function D9n(s){try{localStorage.setItem(MQt,JSON.stringify(s))}catch{}}function F9n(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 O9n({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),[v,y]=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 A=R9n(),E=n.map(V=>({c:V,addr:F9n(V)})).filter(V=>V.addr),I=[],P=[];for(const{c:V,addr:G}of E){const Z=A[G];Z!==null&&(Z?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:Z.lat,lng:Z.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={...A},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 A=(S.city||"").trim();if(!A)continue;const E=(S.state||"").trim()||null,I=`${A.toLowerCase()}|${E||""}`,P=w.get(I);P?P.count++:w.set(I,{city:A,state:E,count:1})}return Array.from(w.values()).sort((S,A)=>A.count-S.count)},[n]);return j.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return _u.accessToken=l,i.current=new _u.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new _u.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 _u.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",v==="heat"?"visible":"none"),w.getLayer("contacts-points")&&(w.setPaintProperty("contacts-points","circle-opacity",v==="points"?.9:0),w.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!w._fitDone){const P=new _u.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,v]),e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{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($s,{className:"flex items-center gap-2",children:[e.jsx(sh,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs($e,{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(Ct,{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:v==="heat"?"default":"ghost",onClick:()=>y("heat"),className:"h-8",children:[e.jsx(sh,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs($,{size:"sm",variant:v==="points"?"default":"ghost",onClick:()=>y("points"),className:"h-8",children:[e.jsx(T4,{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(Ct,{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(vl,{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(ui,{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(go,{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 A=((I=b[0])==null?void 0:I.count)||1,E=w.count/A*100;return e.jsx(je,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{r==null||r(w.city,w.state),t(!1)},children:e.jsxs(Le,{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($e,{variant:"secondary",className:"shrink-0",children:w.count})]})]})},`${w.city}-${w.state}-${S}`)})]})})]})]})]})})}function RO(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 tCt({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=Zn(),c=q9e(s,"birthday",7),d=q9e(t,"anniversary",7),u=q9e(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($e,{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(pn,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx($e,{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(pn,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),u&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs($e,{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(pn,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function sCt({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs($e,{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 nCt({count:s,className:t}){return!s||s<=0?null:e.jsxs($e,{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(XI,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function z9n(){const s=Sa();return st({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 B9n(){const s=Sa();return st({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 $9n="#6366F1";function rCt(s,t){return`color-mix(in srgb, ${s} ${t}%, transparent)`}function U9n(s){return`color-mix(in oklab, ${s} 78%, hsl(var(--foreground)))`}function PQt({label:s,color:t,className:n,onClick:r,title:a}){const i=t||$9n,l=r?"button":"span";return e.jsxs(l,{type:r?"button":void 0,onClick:r,title:a??s,style:{backgroundColor:rCt(i,14),color:U9n(i),boxShadow:`inset 0 0 0 1px ${rCt(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 q9n({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(PQt,{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 aCt({contactId:s,compact:t=!1}){const{data:n}=QB(),{data:r}=yDn(s),a=Hat(),i=CXt(),l=_Dn(),[o,c]=j.useState(!1),[d,u]=j.useState(""),h=j.useRef(null),m=new Set((r==null?void 0:r.map(y=>y.tag_id))||[]),f=(n==null?void 0:n.filter(y=>y.name.toLowerCase().includes(d.toLowerCase())))||[],g=n==null?void 0:n.find(y=>y.name.toLowerCase()===d.trim().toLowerCase()),x=async y=>{m.has(y.id)?await l.mutateAsync({contactId:s,tagId:y.id}):await i.mutateAsync({contactId:s,tagId:y.id})},v=async()=>{if(!(!d.trim()||g))try{const y=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:y.id}),u("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r==null?void 0:r.map(y=>{var b,w,S;return e.jsxs($e,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((b=y.tag)==null?void 0:b.color)||"#6366F1",color:((w=y.tag)==null?void 0:w.color)||"#6366F1"},children:[e.jsx(Cp,{className:"h-2.5 w-2.5"}),(S=y.tag)==null?void 0:S.name,e.jsx("button",{onClick:A=>{A.stopPropagation(),l.mutate({contactId:s,tagId:y.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(mr,{className:"h-2.5 w-2.5"})})]},y.id)}),e.jsxs(Gd,{open:o,onOpenChange:c,children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:t?"h-6 w-6 p-0":"h-6 px-2 text-xs",onClick:y=>y.stopPropagation(),children:[e.jsx(cn,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(Dd,{className:"w-56 p-2",align:"start",onClick:y=>y.stopPropagation(),children:[e.jsx(pe,{ref:h,placeholder:"Search or create tag...",value:d,onChange:y=>u(y.target.value),onKeyDown:y=>{y.key==="Enter"&&d.trim()&&!g?(y.preventDefault(),v()):y.key==="Enter"&&g&&!m.has(g.id)&&(y.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(y=>e.jsxs("button",{onClick:()=>x(y),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:y.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:y.name}),m.has(y.id)&&e.jsx(ma,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},y.id)),d.trim()&&!g&&e.jsxs("button",{onClick:v,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(cn,{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 iCt({contactId:s,tags:t,max:n=2}){return!t||t.length===0?null:e.jsx(q9n,{tags:t,max:n})}const rue=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function V9n({open:s,onOpenChange:t}){const{data:n,isLoading:r}=QB(),a=Hat(),i=bDn(),l=vDn(),[o,c]=j.useState(""),[d,u]=j.useState(rue[0]),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,v]=j.useState(""),y=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(rue[0]),_a({title:"Tag created"})}catch(A){_a({title:"Error",description:A.message,variant:"destructive"})}},b=async A=>{if(f.trim())try{await i.mutateAsync({id:A,name:f.trim(),color:x}),m(null),_a({title:"Tag updated"})}catch(E){_a({title:"Error",description:E.message,variant:"destructive"})}},w=async(A,E)=>{if(await mo(`Delete tag "${E}"? It will be removed from all contacts.`))try{await l.mutateAsync(A),_a({title:"Tag deleted"})}catch(I){_a({title:"Error",description:I.message,variant:"destructive"})}},S=A=>{m(A.id),g(A.name),v(A.color)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{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:A=>c(A.target.value),onKeyDown:A=>A.key==="Enter"&&y(),className:"flex-1 h-9"}),e.jsxs($,{size:"sm",onClick:y,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(cn,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:rue.map(A=>e.jsx("button",{onClick:()=>u(A),className:`h-6 w-6 rounded-full border-2 transition-transform ${d===A?"border-foreground scale-110":"border-transparent hover:scale-105"}`,style:{backgroundColor:A}},A))})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[320px] overflow-y-auto",children:[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(A=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:h===A.id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:rue.map(E=>e.jsx("button",{onClick:()=>v(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(A.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(A.id),children:e.jsx(ma,{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(mr,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-3.5 w-3.5 rounded-full shrink-0",style:{backgroundColor:A.color}}),e.jsx("span",{className:"flex-1 text-sm",children:A.name}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>S(A),children:e.jsx(pi,{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(A.id,A.name),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})},A.id))]})]})})}function H9n({open:s,onOpenChange:t}){const{data:n,isLoading:r}=OB(),a=snt(),i=vWs(),l=bWs(),[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(y){ne.error(y.message||"Failed to add lead source")}},g=async y=>{if(h.trim())try{await i.mutateAsync({id:y,name:h.trim()}),u(null)}catch(b){ne.error(b.message||"Failed to update")}},x=async(y,b)=>{if(await mo(`Remove lead source "${b}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(y)}catch(w){ne.error(w.message||"Failed to remove")}},v=y=>{u(y.id),m(y.name)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"New lead source name...",value:o,onChange:y=>c(y.target.value),onKeyDown:y=>y.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(cn,{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(y=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===y.id?e.jsxs(e.Fragment,{children:[e.jsx(pe,{value:h,onChange:b=>m(b.target.value),onKeyDown:b=>b.key==="Enter"&&g(y.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(y.id),children:e.jsx(ma,{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(mr,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:y.name}),y.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:()=>v(y),children:e.jsx(pi,{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(y.id,y.name),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]}),!y.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},y.id))]})]})})}function IQt({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=OB(),a=snt(),[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(mr,{className:"h-4 w-4"}):e.jsx(cn,{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 AYe({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=Zn(),c=Sa(),[d,u]=j.useState(!1),[h,m]=j.useState(""),{data:f}=st({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:x,error:v}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(v)throw v;return x},enabled:!!t}),{data:g}=st({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:v,error:y}=await x;if(y)throw y;return v},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(e7,{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(Qa,{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(Gd,{open:d,onOpenChange:u,children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(nu,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(Dd,{className:"w-72 p-2",align:"end",children:e.jsx(oCt,{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(Gd,{open:d,onOpenChange:u,children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(nu,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(Dd,{className:"w-72 p-2",align:"start",children:e.jsx(oCt,{search:h,setSearch:m,results:g,onSelect:x=>{a(x),u(!1),m("")}})})]})]}):null}function oCt({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(go,{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 G9n={warm:"stroke-emerald-500",cooling:"stroke-amber-500","at-risk":"stroke-red-500"},W9n={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 K9n({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:G9n[t]})]}),e.jsx("span",{className:Pt("absolute inset-0 flex items-center justify-center font-semibold tabular-nums",W9n[t],n>=56?"text-lg":"text-[11px]"),children:o})]})}const aue=new Map;async function Y9n(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 Z9n(s,t=256){const n=s.trim().toLowerCase();if(!n||!n.includes("@"))return null;const r=`${n}|${t}`;if(aue.has(r))return aue.get(r)??null;try{const i=`https://gravatar.com/avatar/${await Y9n(n)}?s=${t}&d=404`;return aue.set(r,i),i}catch{return aue.set(r,null),null}}function X9n(s,t=256){const[n,r]=j.useState(null);return j.useEffect(()=>{let a=!0;if(!s){r(null);return}return Z9n(s,t).then(i=>{a&&r(i)}),()=>{a=!1}},[s,t]),n}function mit({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=X9n(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 Q9n({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(ry,{children:[e.jsx(ay,{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(Yn,{className:"h-3 w-3"})})}),e.jsx(vx,{children:r})]})}function J9n({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(cn,{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(sh,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Heat Map"]}),e.jsxs(Bu,{children:[e.jsx($u,{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(wl,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(Cu,{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(g1,{className:"mr-2 h-4 w-4"})," Import from Phone"]}),e.jsxs(ja,{onClick:o,children:[e.jsx(Cp,{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:Yn,show:!0},{key:"team",label:"Team",icon:Yn,show:!!h},{key:"lead-pond",label:"Pond",icon:p1,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 e$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(xn,{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(xn,{className:"h-9 w-9 rounded-full"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(xn,{className:"h-3.5 w-36"}),e.jsx(xn,{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(xn,{className:"h-3.5 w-20"})},i))]},r))})}function t$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(xn,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(xn,{className:"h-4 w-2/5"}),e.jsx(xn,{className:"h-3 w-3/5"})]})]}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx(xn,{className:"h-6 w-16 rounded-full"}),e.jsx(xn,{className:"h-6 w-20 rounded-full"})]})]},n))})}function lCt({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 LQt(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 cCt(s){if(!s)return null;const t=kh(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:lc,color:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",icon:ca,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:Zj,color:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",icon:Rg,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:wx,color:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",icon:cl,color:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",icon:wn,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:Xq,color:"text-orange-600 dark:text-orange-400",match:(s,t)=>!t.hasCriteria},{key:"missing-info",title:"Missing Info",icon:Al,color:"text-slate-600 dark:text-slate-400",match:s=>LQt(s)}];function s$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}=Gat(),f=AXt(),g=EXt(),[x,v]=j.useState(!1),[y,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:cCt(P.birthday),daysToAnniv:cCt(P.home_anniversary),hasCriteria:!!(r!=null&&r.has(P.id))};for(const D of dCt)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),A=async()=>{y.trim()&&(await f.mutateAsync({name:y.trim(),filters:o,sort_by:c}),b(""),v(!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(Yn,{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(mr,{className:"h-3 w-3"})})]},I.id)}),e.jsx("div",{className:"h-5 w-px bg-border shrink-0"}),dCt.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:()=>v(!0),children:[e.jsx(OI,{className:"h-3.5 w-3.5"}),"Save view"]})]}),e.jsx(Os,{open:x,onOpenChange:v,children:e.jsxs(Fs,{className:"sm:max-w-sm",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Save this view"}),e.jsx(Er,{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:y,onChange:I=>b(I.target.value),onKeyDown:I=>I.key==="Enter"&&A()}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx($,{onClick:A,disabled:!y.trim()||f.isPending,children:"Save view"})]})]})})]})}const uCt=[{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"}],V9e={relationship:!0,buyerCriteria:!0,stage:!0,leadSource:!0,tags:!0,lastTouch:!0,nextAction:!0,dealValue:!0,email:!1,phone:!1,address:!1,birthday:!1},hCt="innercircle:contact-columns:v1";function n$n(){const[s,t]=j.useState(()=>{try{const a=localStorage.getItem(hCt);if(a)return{...V9e,...JSON.parse(a)}}catch{}return V9e});j.useEffect(()=>{try{localStorage.setItem(hCt,JSON.stringify(s))}catch{}},[s]);const n=j.useCallback(a=>{t(i=>({...i,[a]:!i[a]}))},[]),r=j.useCallback(()=>t(V9e),[]);return{columns:s,toggle:n,reset:r}}function r$n({columns:s,onToggle:t,onReset:n}){const r=uCt.filter(a=>s[a.key]).length;return e.jsxs(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded-lg text-xs",children:[e.jsx(sP,{className:"h-3.5 w-3.5"}),"Columns",e.jsx($e,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r})]})}),e.jsxs(Dd,{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(Sx,{className:"h-3 w-3"}),"Reset"]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-0.5",children:uCt.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 EV=1e3;function RQt(){const s=Sa();return st({queryKey:["contact-criteria-map",s],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const t=[];for(let r=0;;r+=EV){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+EV-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+=EV){const{data:c,error:d}=await q.from("contact_property_alerts").select("id, contact_id").eq("owner_user_id",t).range(o,o+EV-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 o$n(){const s=Zt();return mt({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 iq=s=>String(s??"").trim().toLowerCase();function l$n(s,t){const n=iq(s).replace(/[\s_-]+/g,""),r=iq(t).replace(/[\s_-]+/g,"");return!n||!r?!1:n===r||n.includes(r)||r.includes(n)}function c$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(y=>iq(y)===iq(t.city)),v=!!t.zip&&(s.zip_codes||[]).some(y=>iq(y)===iq(t.zip));x?n.push(`Wants ${t.city}`):v?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(v=>l$n(v,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 d$n(s,t,n,r={}){const a=[];for(const i of s){const l=t[i.id];if(!l)continue;const o=c$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 iue=s=>s>=1e3?`$${Math.round(s/1e3)}k`:`$${s}`;function DQt(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 u$n(s){var r;if(!s)return"";const t=[];s.min_price&&s.max_price?t.push(`${iue(s.min_price)}–${iue(s.max_price)}`):s.max_price?t.push(`up to ${iue(s.max_price)}`):s.min_price&&t.push(`${iue(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 mCt({criteria:s,onEdit:t,showAlertState:n,matchCount:r,className:a,compact:i}){const l=u$n(s);return DQt(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(zy,{className:"h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400"}):e.jsx(KS,{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(cn,{className:"h-3 w-3"}),"Add home search"]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}const FQt=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function h$n(){const s=Sa();return st({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 fCt({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(cn,{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(ui,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function OQt({value:s,onChange:t,hasIdx:n=!0,idxNote:r}){const[a,i]=j.useState(""),[l,o]=j.useState(""),{data:c}=h$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 v;const x=g.trim();x&&!((v=s.cities)!=null&&v.includes(x))&&t(y=>({...y,cities:[...y.cities||[],x]})),i("")},m=g=>{var v;const x=g.trim();x&&!((v=s.zip_codes)!=null&&v.includes(x))&&t(y=>({...y,zip_codes:[...y.zip_codes||[],x]})),o("")},f=g=>{t(x=>{const v=x.property_types||[];return{...x,property_types:v.includes(g)?v.filter(y=>y!==g):[...v,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(su,{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(C4,{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(C0,{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(M4,{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(ui,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(fCt,{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($e,{variant:"secondary",className:"gap-1",children:[g,e.jsx("button",{type:"button",onClick:()=>t(x=>{var v;return{...x,cities:(v=x.cities)==null?void 0:v.filter(y=>y!==g)}}),children:e.jsx(mr,{className:"h-3 w-3"})})]},g))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(fCt,{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($e,{variant:"secondary",className:"gap-1",children:[g,e.jsx("button",{type:"button",onClick:()=>t(x=>{var v;return{...x,zip_codes:(v=x.zip_codes)==null?void 0:v.filter(y=>y!==g)}}),children:e.jsx(mr,{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:FQt.map(g=>{var x;return e.jsx($e,{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(jn,{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(XS,{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 m$n({open:s,onOpenChange:t,contactId:n,contactName:r,existing:a}){const{hasIdx:i}=tg(),l=i$n(),o=o$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}),ne.success(`Home search saved for ${r}`),t(!1)}catch(m){ne.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}),ne.success("Home search removed"),t(!1)}catch(m){ne.error((m==null?void 0:m.message)||"Could not remove home search")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{children:["Home search for ",r]}),e.jsx(Er,{children:"What are they looking for? This shows on your contacts dashboard so you can match new listings to them."})]}),e.jsx(OQt,{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(br,{to:"/mission-control/website",children:"Explore IDX websites"})})}),e.jsxs(Nr,{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(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(qn,{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(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(tl,{className:"h-4 w-4 mr-1"}),"Save"]})]})]})})}const f$n={city:"",state:"",zip:"",price:null,bedrooms:null,bathrooms:null,sqft:null,propertyType:"",address:""};function p$n({open:s,onOpenChange:t,contacts:n}){const r=Zn(),{data:a}=RQt(),{data:i}=Bst(),[l,o]=j.useState(f$n),[c,d]=j.useState(!0),[u,h]=j.useState(""),m=y=>o(b=>({...b,...y})),f=y=>{h(y);const b=(i||[]).find(w=>w.id===y);b&&m({address:b.property_address||"",city:b.city||"",state:b.state||"",zip:"",price:b.price??null,bedrooms:b.bedrooms??null,bathrooms:b.bathrooms??null,sqft:b.square_footage??null,propertyType:b.property_type||""})},g=!!(l.city||l.zip||l.price),x=j.useMemo(()=>!a||!g?[]:d$n(n,a,l,{includeNearMatches:c}),[n,a,l,c,g]),v=j.useMemo(()=>Object.keys(a||{}).length,[a]);return e.jsx(Vy,{open:s,onOpenChange:t,children:e.jsxs(uy,{side:"right",className:"w-full sm:max-w-xl overflow-y-auto",children:[e.jsxs(I0,{children:[e.jsxs(L0,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4 text-primary"}),"Who wants this house?"]}),e.jsx(IB,{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(pa,{defaultValue:i!=null&&i.length?"listing":"manual",children:[e.jsxs(ga,{className:"grid w-full grid-cols-2",children:[e.jsx(Xt,{value:"listing",children:"My listings"}),e.jsx(Xt,{value:"manual",children:"Enter a property"})]}),e.jsx(Qt,{value:"listing",className:"pt-3",children:i!=null&&i.length?e.jsxs(ms,{value:u,onValueChange:f,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose a listing…"})}),e.jsx(hs,{children:i.map(y=>e.jsxs(Ge,{value:y.id,children:[[y.property_address,y.city].filter(Boolean).join(", "),y.price?` — ${Xm(Number(y.price))}`:""]},y.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(Qt,{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:y=>m({address:y.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:y=>m({city:y.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:y=>m({zip:y.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:y=>m({price:y.target.value?Number(y.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:y=>m({sqft:y.target.value?Number(y.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:y=>m({bedrooms:y.target.value?Number(y.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:y=>m({bathrooms:y.target.value?Number(y.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:y=>m({propertyType:y==="any"?"":y}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"any",children:"Any"}),FQt.map(y=>e.jsx(Ge,{value:y,children:y},y))]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[v," ",v===1?"contact has":"contacts have"," a saved home search"]}),e.jsx($,{variant:c?"secondary":"outline",size:"sm",className:"h-7 text-xs",onClick:()=>d(y=>!y),children:c?"Including close matches":"Exact matches only"})]}),g?x.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:[x.length," ",x.length===1?"match":"matches"]}),x.map(({contact:y,result:b})=>{const w=`${y.first_name} ${y.last_name||""}`.trim();return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border p-3",children:[e.jsx(mit,{firstName:y.first_name,lastName:y.last_name||void 0,avatarUrl:y.avatar_url||void 0,email:y.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/${y.id}`),children:w}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[b.reasons.slice(0,4).map(S=>e.jsx($e,{variant:"secondary",className:"text-[10px]",children:S},S)),b.misses.map(S=>e.jsx($e,{variant:"outline",className:"text-[10px] text-muted-foreground",children:S},S))]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[y.email&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",title:`Email ${w}`,asChild:!0,children:e.jsx("a",{href:`mailto:${y.email}?subject=${encodeURIComponent(`Thought of you: ${l.address||l.city||"this home"}`)}`,children:e.jsx(pn,{className:"h-4 w-4"})})}),y.phone&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",title:`Text ${w}`,asChild:!0,children:e.jsx("a",{href:`sms:${y.phone}`,children:e.jsx(no,{className:"h-4 w-4"})})})]})]},y.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."]})]})]})})}function g$n(){var Yc;const s=Zn(),[t,n]=Nc(),{user:r}=_s(),a=RK(),i=Zt(),{columns:l,toggle:o,reset:c}=n$n(),d=t.get("type"),u=t.get("filter")??t.get("status"),h=t.get("new")==="true",{contactsWithScores:m,isLoading:f}=sie(),{activeContactIds:g,hasLeadSite:x}=RBn(),{data:v}=z9n(),{data:y}=Uw(),{data:b}=B9n(),{data:w}=QB(),{data:S}=Aie(),{hasIdx:A}=tg(),{data:E}=RQt(),{data:I}=a$n(!!A),P=j.useMemo(()=>new Set(Object.entries(E||{}).filter(([,ws])=>DQt(ws)).map(([ws])=>ws)),[E]),[R,D]=j.useState(null),[O,U]=j.useState(!1),[W,V]=j.useState(new Set),[G,Z]=j.useState("any"),X=x6e(),ae=Kst(),le=wUt(),re=_Ut(),[te,J]=j.useState(""),[ce,ve]=j.useState(!1),[fe,ue]=j.useState(d||"all"),[be,Ee]=j.useState(u||"all"),[ke,Ie]=j.useState("date-added"),[Fe,Ne]=j.useState("all"),[Be,Se]=j.useState({}),Ae=j.useMemo(()=>Object.values(Be).filter(ws=>ws!==void 0&&ws!==!1&&ws!=="").length,[Be]),[Ce,qe]=j.useState(!1),[ze,Ve]=j.useState([]),{neighborhoods:ht}=hit(),Qe=j.useMemo(()=>TQt(ht,ze),[ht,ze]),{behaviorMap:at,hasLeadSite:rt}=L9n(),[Ke,Je]=j.useState(h),[ft,gt]=j.useState(null),[es,Ht]=j.useState(!1),[as,bs]=j.useState(!1),[Ut,Ft]=j.useState(null),[is,jt]=j.useState(""),[zs,yt]=j.useState(new Set),[gs,Ss]=j.useState(!1),[Ds,Bt]=j.useState(!1),zt=Math.max(1,parseInt(t.get("page")||"1",10)||1),[vs,dn]=j.useState(zt),Ks=j.useCallback(ws=>{dn(Xa=>{const No=typeof ws=="function"?ws(Xa):ws;return n(Ba=>{const ao=new URLSearchParams(Ba);return No<=1?ao.delete("page"):ao.set("page",String(No)),ao},{replace:!0}),No})},[]),[Cn,Rr]=j.useState(50),[ia,Hs]=j.useState("my"),[Br,Ur]=j.useState(!1),[Wn,Sn]=j.useState(!1),{data:Fn}=Ow(),{addToLeadPond:bn}=jWt(Fn==null?void 0:Fn.teamId),{ponds:xs}=Mrt(Fn==null?void 0:Fn.teamId),Tr=xs.filter(ws=>ws.has_access),[Lr,la]=j.useState(null),[Xn,wr]=j.useState(""),Bn=!!((Yc=Fn==null?void 0:Fn.team)!=null&&Yc.lead_pond_enabled&&(Fn!=null&&Fn.teamId)),cr=!!(Fn!=null&&Fn.teamId),[Pa,ii]=j.useState([]),[$i,Ln]=j.useState(!1),xa=ws=>{ii([ws]),Ln(!0)},Ka=ws=>{ii(ws),Ln(!0)},uo=(ws,Xa)=>{Fn!=null&&Fn.teamId&&ws.forEach(No=>{bn.mutate({contact_id:No,team_id:Fn.teamId,pond_id:Xa||null})})},Tc=ws=>{var Xa;if(Fn!=null&&Fn.teamId){if(Tr.length>1){wr(Tr[0].id),la(ws);return}uo(ws,((Xa=Tr[0])==null?void 0:Xa.id)||null)}},Fd=ws=>Tc([ws]),Nl=ws=>Tc(ws),Ho=j.useCallback(ws=>{Bt(!1),yt(Xa=>{const No=new Set(Xa);return No.has(ws)?No.delete(ws):No.add(ws),No})},[]);j.useEffect(()=>{if(!(r!=null&&r.id))return;const ws=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(ws)}},[i,r==null?void 0:r.id]),j.useEffect(()=>{u&&Ee(u)},[u]);const[ti,Yr]=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,Th]=j.useState(!1);j.useEffect(()=>{h&&Je(!0)},[h]),j.useEffect(()=>{var ws;ft&&Yr({first_name:ft.first_name||"",last_name:ft.last_name||"",email:ft.email||"",phone:ft.phone||"",address:ft.address||"",city:ft.city||"",state:ft.state||"",zip_code:ft.zip_code||"",address2_label:ft.address2_label||"",address2:ft.address2||"",address2_city:ft.address2_city||"",address2_state:ft.address2_state||"",address2_zip:ft.address2_zip||"",mail_to_secondary:!!ft.mail_to_secondary,birthday:ft.birthday||"",home_anniversary:ft.home_anniversary||"",spouse_name:ft.spouse_name||"",spouse_email:ft.spouse_email||"",lead_source_id:ft.lead_source_id||"",notes:ft.notes||"",tagIds:((ws=ft.tags)==null?void 0:ws.map(Xa=>Xa.relationship_type_id))||[]})},[ft]);const rh=j.useMemo(()=>{const ws=new Set;return w==null||w.forEach(Xa=>{(Xa.name==="Recruits"||Xa.name==="Brokerage Agents")&&ws.add(Xa.id)}),ws},[w]),ro=j.useMemo(()=>Array.from(W).some(ws=>rh.has(ws)),[W,rh]),ea=j.useMemo(()=>{const ws={};return(m||[]).forEach(Xa=>{ws[Xa.id]=`${Xa.first_name||""} ${Xa.last_name||""}`.trim()}),ws},[m]),pc=j.useMemo(()=>{const ws=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&&ws.add(No)}),Array.from(ws).sort((Xa,No)=>Xa.localeCompare(No))},[m]),ml=j.useMemo(()=>{if(!m)return[];let ws=m.filter(Ba=>{var Kd,Vh,cf,Wy,ah,gh,xt,We,ct,Nt,Rt;const ao=Ba.synced_source;if(!ro&&(ao==="recruit"||ao==="brokerage_agent")||Qe&&!Qe.has(Ba.id))return!1;const qi=te===""||`${Ba.first_name} ${Ba.last_name}`.toLowerCase().includes(te.toLowerCase())||((Kd=Ba.email)==null?void 0:Kd.toLowerCase().includes(te.toLowerCase()))||((Vh=Ba.phone)==null?void 0:Vh.includes(te))||((cf=Ba.city)==null?void 0:cf.toLowerCase().includes(te.toLowerCase()))||((Wy=Ba.state)==null?void 0:Wy.toLowerCase().includes(te.toLowerCase()))||((ah=Ba.address)==null?void 0:ah.toLowerCase().includes(te.toLowerCase()))||((gh=Ba.zip_code)==null?void 0:gh.toLowerCase().includes(te.toLowerCase())),cm=fe==="all"||((xt=Ba.tags)==null?void 0:xt.some($t=>$t.relationship_type_id===fe)),Zo=W.size===0||(()=>{const $t=(S==null?void 0:S.filter(Wt=>Wt.contact_id===Ba.id).map(Wt=>Wt.tag_id))||[];return G==="any"?$t.some(Wt=>W.has(Wt)):Array.from(W).every(Wt=>$t.includes(Wt))})(),vo=!!((We=Ba.address)!=null&&We.trim()||(ct=Ba.city)!=null&&ct.trim()||(Nt=Ba.state)!=null&&Nt.trim()||(Rt=Ba.zip_code)!=null&&Rt.trim()),Gg=Fe==="all"||Fe==="has-address"&&vo||Fe==="no-address"&&!vo,Fl=Ba,Ol=Be,fy=(Ol.hasEmail===void 0||!!Fl.email===Ol.hasEmail)&&(Ol.hasPhone===void 0||!!Fl.phone===Ol.hasPhone)&&(Ol.hasAddress===void 0||vo===Ol.hasAddress)&&(Ol.hasBirthday===void 0||!!Fl.birthday===Ol.hasBirthday)&&(Ol.hasSpouse===void 0||!!(Fl.spouse_name||Fl.spouse_contact_id||Fl.spouse_email)===Ol.hasSpouse)&&(Ol.hasCompany===void 0||!!(Fl.company_name||Fl.job_title)===Ol.hasCompany)&&(Ol.hasNotes===void 0||!!(Fl.notes&&Fl.notes.trim())===Ol.hasNotes)&&(!Ol.city||(Fl.city||"").toLowerCase().includes(Ol.city.toLowerCase()))&&(!Ol.state||(Fl.state||"").toLowerCase().includes(Ol.state.toLowerCase()))&&(!Ol.zip||((Fl.zip||"")+(Fl.zip_code||"")).toLowerCase().includes(Ol.zip.toLowerCase()))&&(!Ol.birthdayMonth||!!Fl.birthday&&kh(Fl.birthday).getMonth()+1===Ol.birthdayMonth)&&(!Ol.anniversaryMonth||((Ol.anniversaryField||"home_anniversary")==="home_anniversary"?!!Fl.home_anniversary&&kh(Fl.home_anniversary).getMonth()+1===Ol.anniversaryMonth:!!Fl.wedding_anniversary&&kh(Fl.wedding_anniversary).getMonth()+1===Ol.anniversaryMonth))&&(!Ol.dateAddedFrom||!!Fl.created_at&&Fl.created_at.slice(0,10)>=Ol.dateAddedFrom)&&(!Ol.dateAddedTo||!!Fl.created_at&&Fl.created_at.slice(0,10)<=Ol.dateAddedTo)&&(()=>{var js;const $t=Ol.leadSourceId;if(!$t)return!0;const Wt=(((js=Fl.lead_source_ref)==null?void 0:js.name)||Fl.lead_source||"").trim();return $t==="none"?!Wt&&!Fl.lead_source_id:$t.startsWith("name:")?Wt.toLowerCase()===$t.slice(5).toLowerCase():Fl.lead_source_id===$t})();return qi&&cm&&Zo&&Gg&&fy});be==="not-touched-90"?ws=ws.filter(Ba=>{const ao=Ba.relationshipScore.daysSinceTouch;return ao===null||ao>90}):be==="at-risk"?ws=ws.filter(Ba=>Ba.relationshipScore.status==="at-risk"):be==="cooling"?ws=ws.filter(Ba=>Ba.relationshipScore.status==="cooling"):be==="warm"?ws=ws.filter(Ba=>Ba.relationshipScore.status==="warm"):be==="has-deal"?ws=ws.filter(Ba=>b&&b[Ba.id]):be==="no-deal"?ws=ws.filter(Ba=>!b||!b[Ba.id]):be==="open-house"?ws=ws.filter(Ba=>{var ko;return(((ko=Ba.lead_source_ref)==null?void 0:ko.name)||Ba.lead_source)==="Open House"}):be==="website-active"?ws=ws.filter(Ba=>g.has(Ba.id)):be==="never-contacted"?ws=ws.filter(Ba=>Ba.relationshipScore.daysSinceTouch===null):be==="vips"?ws=ws.filter(Ba=>Ba.relationshipScore.score>=80):be==="missing-info"?ws=ws.filter(Ba=>LQt(Ba)):be==="birthdays-soon"?ws=ws.filter(Ba=>{const ao=RO(Ba.birthday);return ao!==null&&ao<=30}):be==="anniversary-soon"?ws=ws.filter(Ba=>{const ao=RO(Ba.home_anniversary);return ao!==null&&ao<=30}):be==="in-drip"?ws=ws.filter(Ba=>((v==null?void 0:v[Ba.id])??0)>0):be==="not-in-drip"?ws=ws.filter(Ba=>((v==null?void 0:v[Ba.id])??0)===0):be==="active-buyers"?ws=ws.filter(Ba=>P.has(Ba.id)):be==="missing-criteria"&&(ws=ws.filter(Ba=>!P.has(Ba.id)));const Xa=Be;if(Xa.lastActive||Xa.registered||Xa.viewedListing||Xa.savedProperty||Xa.hasSavedSearch||Xa.requestedShowing||Xa.requestedValuation||Xa.websiteActiveOnly){const Ba=Date.now(),ao={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};ws=ws.filter(ko=>{const qi=at.get(ko.id);if(Xa.lastActive==="never"){if(qi!=null&&qi.lastActiveAt)return!1}else if(Xa.lastActive){const cm=Ba-ao[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 ws=[...ws].sort((Ba,ao)=>{switch(ke){case"important-dates":{const ko=RO(Ba.birthday),qi=RO(ao.birthday),cm=RO(Ba.home_anniversary),Zo=RO(ao.home_anniversary),vo=[ko,cm].filter(Fl=>Fl!==null).sort((Fl,Ol)=>(Fl??1/0)-(Ol??1/0))[0]??1/0,Gg=[qi,Zo].filter(Fl=>Fl!==null).sort((Fl,Ol)=>(Fl??1/0)-(Ol??1/0))[0]??1/0;return vo-Gg}case"last-touched":{const ko=Ba.relationshipScore.lastTouchDate,qi=ao.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=ao.relationshipScore.daysSinceTouch;return ko===null&&qi===null?0:ko===null?-1:qi===null?1:qi-ko}case"score":return Ba.relationshipScore.score-ao.relationshipScore.score;case"date-added":{const ko=Ba.created_at,qi=ao.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=(ao.last_name||"").toLowerCase();if(ko!==qi)return ko.localeCompare(qi);const cm=(Ba.first_name||"").toLowerCase(),Zo=(ao.first_name||"").toLowerCase();return cm.localeCompare(Zo)}case"name":default:{const ko=`${Ba.first_name||""} ${Ba.last_name||""}`.toLowerCase(),qi=`${ao.first_name||""} ${ao.last_name||""}`.toLowerCase();return ko.localeCompare(qi)}}}),ws},[m,te,fe,W,G,be,ke,b,S,g,v,Fe,Be,at,ro,P,Qe]),Co=ml.length,mu=Math.max(1,Math.ceil(Co/Cn)),cc=Math.min(vs,mu),nd=j.useMemo(()=>{const ws=(cc-1)*Cn;return ml.slice(ws,ws+Cn)},[ml,cc,Cn]),Dr=j.useMemo(()=>{const ws=(m||[]).length;return{total:ws,label:ws===0?"Build your database — add or import your first contacts.":`${ws.toLocaleString()} ${ws===1?"person":"people"} in your database`}},[m]),Hi=j.useMemo(()=>{const ws=m||[],Xa=ws.filter(ko=>{var qi;return((qi=ko.relationshipScore)==null?void 0:qi.status)==="at-risk"}).length,No=ws.filter(ko=>{var cm;const qi=(cm=ko.relationshipScore)==null?void 0:cm.daysSinceTouch;return typeof qi=="number"&&qi<=7}).length,Ba=new Date().getMonth()+1,ao=ws.filter(ko=>ko.birthday?String(ko.birthday).split(/[-/T]/).map(Number)[1]===Ba:!1).length;return[{label:"Total contacts",value:Dr.total.toLocaleString(),onClick:()=>{Ee("all"),Ks(1)},active:be==="all"},{label:"Needs attention",value:Xa,onClick:()=>{Ee("at-risk"),Ks(1)},active:be==="at-risk"},{label:"Touched this week",value:No,onClick:()=>{Ee("warm"),Ks(1)},active:be==="warm"},{label:"Birthdays this month",value:ao,onClick:()=>{Ee("birthdays-soon"),Ks(1)},active:be==="birthdays-soon"}]},[m,Dr.total,be,Ks]),zc=j.useCallback(ws=>{const Xa=new URLSearchParams;te&&Xa.set("search",te),fe!=="all"&&Xa.set("type",fe),be!=="all"&&Xa.set("filter",be),W.size>0&&(Xa.set("tags",Array.from(W).join(",")),Xa.set("tagMode",G));const No=Xa.toString();s(`/mission-control/contacts/${ws}${No?`?${No}`:""}`)},[s,te,fe,be,W,G]),Bc=j.useRef(!1);j.useEffect(()=>{if(!Bc.current){Bc.current=!0;return}Ks(1)},[te,fe,W,G,be,ke,Fe,Be]);const gc=j.useCallback(()=>{Bt(!1),yt(ws=>ws.size>0?new Set:new Set(nd.map(Xa=>Xa.id)))},[nd]),$l=j.useCallback(()=>{Bt(!0),yt(new Set(ml.map(ws=>ws.id)))},[ml]),[sg,Mx]=j.useState(null),Yo=j.useCallback((ws,Xa)=>{J(ws.search||""),ue(ws.type||"all"),Ee(ws.status||"all"),Se(ws.behavior||{}),Ie(Xa||"name")},[]),Mc=()=>{Yr({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:[]})},Mh=async ws=>{ws.preventDefault();const Xa={...ti,lead_source_id:ti.lead_source_id||null};ft?(await ae.mutateAsync({id:ft.id,...Xa}),gt(null)):(await X.mutateAsync(Xa),Je(!1)),Mc()},lm=async ws=>{await mo("Are you sure you want to delete this contact?")&&await le.mutateAsync(ws)};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(J9n,{totalLabel:Dr.label,stats:Hi,search:te,onSearchChange:J,onAddContact:()=>Je(!0),onImportCsv:()=>Ht(!0),onImportPhone:()=>bs(!0),onManageTags:()=>Ur(!0),onHeatMap:()=>ve(!0),viewMode:ia,onViewModeChange:ws=>Hs(ws),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(PJ,{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(Vz,{className:"h-4 w-4"}),"Find duplicates"]}),e.jsx(vBn,{})]})}),e.jsx(SBn,{open:gs,onOpenChange:Ss}),e.jsx(p$n,{open:O,onOpenChange:U,contacts:m||[]}),R&&e.jsx(m$n,{open:!!R,onOpenChange:ws=>{ws||D(null)},contactId:R.id,contactName:R.name,existing:(E==null?void 0:E[R.id])??null}),ia==="team"?e.jsx(nRe,{}):ia==="lead-pond"&&Fn?e.jsx(rRe,{teamId:Fn.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(s$n,{contacts:m,contactDealsMap:b,websiteActiveIds:g,criteriaContactIds:P,totalCount:(m||[]).length,activeViewId:sg,currentFilters:{search:te,type:fe,status:be,behavior:Be},currentSortBy:ke,onApplyView:(ws,Xa,No)=>{Mx(ws),Yo(Xa,No),Ks(1)},onClearAll:()=>{Mx(null),Yo({search:"",type:"all",status:"all",behavior:{}},"name"),Ks(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"}[be]??null,onSelectSegment:ws=>{const No=ws?{"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"}[ws]:"all";Ee(No),Ks(1)}}),e.jsxs(je,{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(Vy,{children:[e.jsx(Tae,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"h-10 flex-1 rounded-xl relative gap-2","aria-label":"Filters",children:[e.jsx(YI,{className:"h-4 w-4"}),"Filters & Views",(()=>{const ws=(fe!=="all"?1:0)+(be!=="all"?1:0)+(Fe!=="all"?1:0)+W.size+Ae;return ws>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:ws}):null})()]})}),e.jsxs(uy,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(I0,{className:"text-left",children:e.jsx(L0,{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:fe,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"}),y==null?void 0:y.filter(ws=>ws.active).map(ws=>e.jsx(Ge,{value:ws.id,children:ws.name},ws.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:be,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:ws=>Ne(ws),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:()=>Z("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:()=>Z("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(ws=>{const Xa=W.has(ws.id);return e.jsxs("button",{onClick:()=>{V(No=>{const Ba=new Set(No);return Ba.has(ws.id)?Ba.delete(ws.id):Ba.add(ws.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:ws.color}}),ws.name]},ws.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:ke,onValueChange:Ie,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(wn,{className:"h-4 w-4"})," Advanced"]}),e.jsxs($,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Ur(!0),children:[e.jsx(Cp,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(JSt,{currentFilters:{search:te,type:fe,status:be,behavior:Be},currentSortBy:ke,onApplySmartList:Yo})}),e.jsx($,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{ue("all"),Ee("all"),Ne("all"),V(new Set),Se({})},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(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(c2,{className:"h-4 w-4"})})}),e.jsxs(Dd,{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(ws=>e.jsx("button",{onClick:()=>Ie(ws.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${ke===ws.v?"bg-accent font-medium text-primary":""}`,children:ws.l},ws.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:fe,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"}),y==null?void 0:y.filter(ws=>ws.active).map(ws=>e.jsx(Ge,{value:ws.id,children:ws.name},ws.id))]})]}),e.jsxs(ms,{value:be,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:ws=>Ne(ws),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(Gd,{children:[e.jsx(Wd,{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(Cp,{className:"h-3.5 w-3.5"}),W.size===0?"Filter by Tags":`${W.size} tag${W.size>1?"s":""}`]})}),e.jsx(Dd,{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:()=>Z("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:()=>Z("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(ws=>{const Xa=W.has(ws.id);return e.jsxs("button",{onClick:()=>{V(No=>{const Ba=new Set(No);return Ba.has(ws.id)?Ba.delete(ws.id):Ba.add(ws.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:ws.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:ws.name})]},ws.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(Bu,{children:[e.jsx($u,{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(Nd,{className:"h-3.5 w-3.5"})})}),e.jsxs(Cu,{align:"end",children:[e.jsxs(ja,{onClick:()=>Ur(!0),children:[e.jsx(Cp,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(ja,{onClick:()=>Sn(!0),children:[e.jsx(p1,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(JSt,{currentFilters:{search:te,type:fe,status:be,behavior:Be},currentSortBy:ke,onApplySmartList:Yo}),e.jsx("div",{className:"h-5 w-px bg-border"}),e.jsx(I9n,{selected:ze,onChange:Ve}),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(wn,{className:"h-3.5 w-3.5"}),"Advanced Filters",Ae>0&&e.jsx($e,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:Ae})]}),e.jsx(r$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(w9n,{behavior:Be,onRemove:ws=>Se(Xa=>{const No={...Xa};return delete No[ws],No}),onClearAll:()=>Se({})})})]}),e.jsx(_9n,{open:Ce,onOpenChange:qe,hasLeadSite:rt||x,behavior:Be,onApply:Se,selectedType:fe,onSelectedTypeChange:ue,relationshipTypes:y,contactLeadSources:pc}),e.jsx(v9n,{selectedIds:zs,contacts:ml,onClearSelection:()=>{yt(new Set),Bt(!1)},showLeadPondAction:Bn,onSendToLeadPond:Nl,showTransferAction:cr,onTransfer:Ka}),zs.size>0&&zs.size===nd.length&&!Ds&&Co>Cn&&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 ",nd.length," contacts on this page are selected."]}),e.jsxs($,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:$l,children:["Select all ",Co.toLocaleString()," matching contacts"]})]}),Ds&&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:()=>{yt(new Set),Bt(!1)},children:"Clear selection"})]}),Co>Cn&&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 ",(cc-1)*Cn+1,"–",Math.min(cc*Cn,Co)," of ",Co.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"sm",disabled:cc<=1,onClick:()=>Ks(1),children:"First"}),e.jsx($,{variant:"outline",size:"sm",disabled:cc<=1,onClick:()=>Ks(ws=>ws-1),children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",cc," of ",mu]}),e.jsx($,{variant:"outline",size:"sm",disabled:cc>=mu,onClick:()=>Ks(ws=>ws+1),children:e.jsx(Di,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",disabled:cc>=mu,onClick:()=>Ks(mu),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:f?e.jsx(t$n,{}):ml.length===0?e.jsx(je,{children:e.jsx(lCt,{filtered:!!te||fe!=="all"||be!=="all"||Fe!=="all"||W.size>0,onAdd:()=>Je(!0),onImport:()=>Ht(!0),onClearFilters:()=>{J(""),ue("all"),Ee("all"),Ne("all"),V(new Set),Se({})}})}):nd.map(ws=>{var No,Ba,ao;const{relationshipScore:Xa}=ws;return e.jsx(je,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>zc(ws.id),children:e.jsx(Le,{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:[ws.first_name," ",ws.last_name]}),e.jsx(nCt,{count:(v==null?void 0:v[ws.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:[ws.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(pn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:ws.email})]}),ws.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:ws.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(CYe,{score:Xa,size:"sm"}),e.jsx(ZSt,{contact:ws}),(((No=ws.lead_source_ref)==null?void 0:No.name)||ws.lead_source)&&e.jsx($e,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((Ba=ws.lead_source_ref)==null?void 0:Ba.name)||ws.lead_source}),(ao=ws.tags)==null?void 0:ao.map(ko=>{var qi;return e.jsx($e,{variant:"secondary",className:"text-xs",children:(qi=ko.relationship_type)==null?void 0:qi.name},ko.id)}),e.jsx(iCt,{contactId:ws.id,tags:S==null?void 0:S.filter(ko=>ko.contact_id===ws.id)}),e.jsx(sCt,{deal:b==null?void 0:b[ws.id]})]}),e.jsx("div",{className:"mb-2",children:e.jsx(mCt,{criteria:E==null?void 0:E[ws.id],onEdit:()=>D({id:ws.id,name:`${ws.first_name}${ws.last_name?" "+ws.last_name:""}`}),showAlertState:!!A,matchCount:I==null?void 0:I[ws.id],compact:!0})}),e.jsx(tCt,{birthday:ws.birthday,homeAnniversary:ws.home_anniversary,weddingAnniversary:ws.wedding_anniversary,className:"mb-2",contactId:ws.id,contactName:`${ws.first_name}${ws.last_name?" "+ws.last_name:""}`,contactAddress:[ws.address,ws.city,ws.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(ca,{className:"h-3 w-3"}),Js(new Date(Xa.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),ws.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ea,{className:"h-3 w-3"}),Js(kh(ws.birthday),"MMM d")]}),ws.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(va,{className:"h-3 w-3"}),Js(kh(ws.home_anniversary),"MMM d")]}),ws.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(cn,{className:"h-3 w-3"}),"Added ",Js(new Date(ws.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:ko=>ko.stopPropagation(),children:e.jsx(QSt,{contact:ws,onEdit:gt,onDelete:lm,onSnooze:(ko,qi)=>{Ft(ko),jt(qi)},showLeadPondAction:Bn,onSendToLeadPond:Fd,showTransferAction:cr,onTransfer:xa})})]})})},ws.id)})}):e.jsx(je,{children:e.jsx(Le,{className:"p-0 overflow-x-auto",children:e.jsxs(hi,{className:"min-w-[800px]",children:[e.jsx(mi,{className:"sticky top-0 z-10 bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs(An,{className:"hover:bg-transparent",children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(ai,{checked:nd.length>0&&nd.every(ws=>zs.has(ws.id)),onCheckedChange:()=>gc()})}),e.jsx(Dt,{children:e.jsxs("button",{onClick:()=>Ie(ws=>ws==="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",ke==="name"&&e.jsx(Di,{className:"h-3 w-3 rotate-90 text-primary"}),ke==="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(fi,{children:f?e.jsx(e$n,{columns:2+Object.values(l).filter(Boolean).length}):ml.length===0?e.jsx(An,{className:"hover:bg-transparent",children:e.jsx(wt,{colSpan:3+Object.values(l).filter(Boolean).length,className:"p-0",children:e.jsx(lCt,{filtered:!!te||fe!=="all"||be!=="all"||Fe!=="all"||W.size>0,onAdd:()=>Je(!0),onImport:()=>Ht(!0),onClearFilters:()=>{J(""),ue("all"),Ee("all"),Ne("all"),V(new Set),Se({})}})})}):nd.map(ws=>{var Ba;const{relationshipScore:Xa}=ws,No=b==null?void 0:b[ws.id];return e.jsxs(An,{className:`group cursor-pointer border-border/60 transition-colors hover:bg-accent/40 [&>td]:py-3.5 ${zs.has(ws.id)?"bg-accent/30":""}`,onClick:()=>zc(ws.id),children:[e.jsx(wt,{onClick:ao=>ao.stopPropagation(),children:e.jsx(ai,{checked:zs.has(ws.id),onCheckedChange:()=>Ho(ws.id)})}),e.jsx(wt,{className:"min-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(mit,{firstName:ws.first_name,lastName:ws.last_name,avatarUrl:ws.avatar_url,email:ws.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:[ws.first_name," ",ws.last_name]}),e.jsx(Q9n,{linked:!!ws.spouse_contact_id||!!ws.spouse_name,spouseName:ws.spouse_contact_id&&ea[ws.spouse_contact_id]||ws.spouse_name||null}),e.jsx(nCt,{count:(v==null?void 0:v[ws.id])??0})]}),ws.email&&!l.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ws.email}),ws.phone&&!l.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:ws.phone})]})]})}),l.relationship&&e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(K9n,{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(mCt,{criteria:E==null?void 0:E[ws.id],onEdit:()=>D({id:ws.id,name:`${ws.first_name}${ws.last_name?" "+ws.last_name:""}`}),showAlertState:!!A,matchCount:I==null?void 0:I[ws.id]})}),l.stage&&e.jsx(wt,{children:e.jsx(sCt,{deal:No})}),l.leadSource&&e.jsx(wt,{className:"text-sm text-muted-foreground max-w-[160px] truncate",children:((Ba=ws.lead_source_ref)==null?void 0:Ba.name)||ws.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(iCt,{contactId:ws.id,tags:S==null?void 0:S.filter(ao=>ao.contact_id===ws.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(ca,{className:"h-3.5 w-3.5"}),Js(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(ZSt,{contact:ws}),e.jsx(tCt,{birthday:ws.birthday,homeAnniversary:ws.home_anniversary,weddingAnniversary:ws.wedding_anniversary,contactId:ws.id,contactName:`${ws.first_name}${ws.last_name?" "+ws.last_name:""}`,contactAddress:[ws.address,ws.city,ws.state].filter(Boolean).join(", ")})]})}),l.dealValue&&e.jsx(wt,{children:(()=>{const ao=(No==null?void 0:No.sale_price)??(No==null?void 0:No.expected_price);return ao?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:Xm(Number(ao))}),(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:ws.email||"—"}),l.phone&&e.jsx(wt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:ws.phone||"—"}),l.address&&e.jsx(wt,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:[ws.address,ws.city,ws.state].filter(Boolean).join(", ")||"—"}),l.birthday&&e.jsx(wt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:ws.birthday?(()=>{const[ao,ko,qi]=String(ws.birthday).split(/[-/T]/).map(Number);return ko&&qi?`${ko}/${qi}${ao&&ao>1900?`/${ao}`:""}`:"—"})():"—"}),e.jsx(wt,{onClick:ao=>ao.stopPropagation(),children:e.jsx(QSt,{contact:ws,onEdit:gt,onDelete:lm,onSnooze:(ao,ko)=>{Ft(ao),jt(ko)},showLeadPondAction:Bn,onSendToLeadPond:Fd,showTransferAction:cr,onTransfer:xa})})]},ws.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 ",(cc-1)*Cn+1,"–",Math.min(cc*Cn,Co)," of ",Co.toLocaleString()," contacts"]}),e.jsxs(ms,{value:String(Cn),onValueChange:ws=>{Rr(Number(ws)),Ks(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:cc<=1,onClick:()=>Ks(1),children:"First"}),e.jsx($,{variant:"outline",size:"sm",disabled:cc<=1,onClick:()=>Ks(ws=>ws-1),children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",cc," of ",mu]}),e.jsx($,{variant:"outline",size:"sm",disabled:cc>=mu,onClick:()=>Ks(ws=>ws+1),children:e.jsx(Di,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",disabled:cc>=mu,onClick:()=>Ks(mu),children:"Last"})]})]}),e.jsx(Os,{open:Ke||!!ft,onOpenChange:ws=>{ws||(Je(!1),gt(null),Mc())},children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{children:ft?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:Mh,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:ws=>Yr({...ti,first_name:ws.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:ws=>Yr({...ti,last_name:ws.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:ti.email,onChange:ws=>Yr({...ti,email:ws.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Phone"}),e.jsx(pe,{id:"phone",value:ti.phone,onChange:ws=>Yr({...ti,phone:ws.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address",children:"Address"}),e.jsx(pe,{id:"address",value:ti.address,onChange:ws=>Yr({...ti,address:ws.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:ws=>Yr({...ti,city:ws.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:ti.state,onChange:ws=>Yr({...ti,state:ws.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:ws=>Yr({...ti,zip_code:ws.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:ws=>Yr({...ti,address2_label:ws.target.value}),placeholder:"Vacation home"}),e.jsx("datalist",{id:"contact-address-labels-new",children:mQt.map(ws=>e.jsx("option",{value:ws},ws))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2",children:"Street Address"}),e.jsx(pe,{id:"address2",value:ti.address2,onChange:ws=>Yr({...ti,address2:ws.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:ws=>Yr({...ti,address2_city:ws.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:ws=>Yr({...ti,address2_state:ws.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:ws=>Yr({...ti,address2_zip:ws.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(jn,{id:"mail_to_secondary",checked:ti.mail_to_secondary,onCheckedChange:ws=>Yr({...ti,mail_to_secondary:ws})})]})]}):e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"justify-start px-0 text-primary",onClick:()=>Th(!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:ws=>Yr({...ti,birthday:ws.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:ws=>Yr({...ti,home_anniversary:ws.target.value})})]})]}),ft&&e.jsx(AYe,{contactId:ft.id,currentSpouseContactId:(ft==null?void 0:ft.spouse_contact_id)||null,currentSpouseName:(ft==null?void 0:ft.spouse_name)||null,currentSpouseEmail:(ft==null?void 0:ft.spouse_email)||null,onLink:ws=>re.mutate({contactId:ft.id,spouseContactId:ws}),onUnlink:()=>re.mutate({contactId:ft.id,spouseContactId:null}),isEditing:!0}),e.jsx(IQt,{value:ti.lead_source_id,onChange:ws=>Yr({...ti,lead_source_id:ws})}),e.jsxs("div",{children:[e.jsx(ee,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:y==null?void 0:y.filter(ws=>ws.active).map(ws=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(ai,{checked:ti.tagIds.includes(ws.id),onCheckedChange:Xa=>{Yr(Xa?{...ti,tagIds:[...ti.tagIds,ws.id]}:{...ti,tagIds:ti.tagIds.filter(No=>No!==ws.id)})}}),e.jsx("span",{className:"text-sm",children:ws.name})]},ws.id))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"notes",children:"Notes"}),e.jsx(Rs,{id:"notes",value:ti.notes,onChange:ws=>Yr({...ti,notes:ws.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>{Je(!1),gt(null),Mc()},children:"Cancel"}),e.jsxs($,{type:"submit",disabled:X.isPending||ae.isPending,children:[ft?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(zBn,{open:es,onOpenChange:Ht,relationshipTypes:(y==null?void 0:y.filter(ws=>ws.active))||[],onSuccess:()=>{Ht(!1)}}),e.jsx(UBn,{open:as,onOpenChange:bs,onComplete:()=>bs(!1)}),e.jsx(tDe,{open:!!Ut,onOpenChange:ws=>{ws||Ft(null)},contactId:Ut||"",contactName:is}),e.jsx(V9n,{open:Br,onOpenChange:Ur}),e.jsx(H9n,{open:Wn,onOpenChange:Sn}),e.jsx(O9n,{open:ce,onOpenChange:ve,contacts:m||[],onCitySelect:ws=>{J(ws),Ks(1)}}),e.jsx(NWt,{open:$i,onOpenChange:Ln,contactIds:Pa,contactNames:Pa.map(ws=>{const Xa=ml.find(No=>No.id===ws);return Xa?`${Xa.first_name} ${Xa.last_name||""}`.trim():""}),onComplete:()=>{ii([]),yt(new Set),Bt(!1)}}),e.jsx(Os,{open:!!Lr,onOpenChange:ws=>!ws&&la(null),children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{children:"Choose a Lead Pond"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sharing ",(Lr==null?void 0:Lr.length)||0," contact",((Lr==null?void 0:Lr.length)||0)===1?"":"s"," with your team."]}),e.jsxs(ms,{value:Xn,onValueChange:wr,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a pond"})}),e.jsx(hs,{children:Tr.map(ws=>e.jsx(Ge,{value:ws.id,children:ws.name},ws.id))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>la(null),children:"Cancel"}),e.jsx($,{onClick:()=>{Lr&&uo(Lr,Xn),la(null)},disabled:!Xn,children:"Share to Pond"})]})]})]})})]})]})})}const x$n=5*1024*1024;function y$n({contactId:s,firstName:t,lastName:n,avatarUrl:r,email:a,size:i=88}){const l=j.useRef(null),o=Zt(),[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>x$n){_a({title:"Image too large",description:"Please use an image under 5MB.",variant:"destructive"});return}d(!0);try{const{data:v}=await q.auth.getUser(),y=(x=v.user)==null?void 0:x.id,b=(g.name.split(".").pop()||"jpg").toLowerCase(),w=`contacts/${y}/${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:A}=q.storage.from("avatars").getPublicUrl(w);await h(A.publicUrl),_a({title:"Photo updated"})}catch(v){_a({title:"Upload failed",description:v.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(mit,{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(Ct,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(jx,{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(Ct,{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(qn,{className:"h-3.5 w-3.5"}),"Remove"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:g=>{var v;const x=(v=g.target.files)==null?void 0:v[0];x&&m(x)}})]})}const v$n={job_title:"Job title",company_name:"Company",city:"City",state:"State",avatar_url:"Profile photo",email:"Email",phone:"Phone"},b$n=4e3,_$n=5*60*1e3;function w$n({open:s,onOpenChange:t,contactId:n,contactName:r,hasEmail:a}){var W;const{toast:i}=Bi(),l=Zt(),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState(null),[x,v]=j.useState(!1),[y,b]=j.useState(null),[w,S]=j.useState(null),[A,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,Z=null;const X=async()=>{if(!V)try{const{data:ae,error:le}=await q.functions.invoke("enrich-contact",{body:{contact_id:n,batch_id:w}});if(le)throw le;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)):(v(!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,b$n),Z=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"}))},_$n),()=>{V=!0,G&&clearInterval(G),Z&&clearTimeout(Z)}},[w,s,n,i]);const D=async()=>{u(!0),v(!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)){v(!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,Z;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]}),(Z=f.phones)!=null&&Z.length&&V.push({key:"phone",value:f.phones[0]}),!f.city&&!f.state&&f.location){const[X,ae]=f.location.split(",").map(le=>le.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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-4 w-4 text-primary"}),"Find person details — ",r]}),e.jsx(Er,{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(Ct,{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(A/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(go,{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}),y&&e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:["matched via ",y]})]}),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(wi,{className:"h-3 w-3"}),f.company_name]}),f.location&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ui,{className:"h-3 w-3"}),f.location]}),f.industry&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(wx,{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(ly,{className:"h-3 w-3"})," LinkedIn ",e.jsx(Ir,{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(Z=>({...Z,[V.key]:G===!0}))}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"font-medium",children:[v$n[V.key],": "]}),e.jsx("span",{className:"text-muted-foreground break-all",children:V.value})]})]},V.key))]})]})})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),!f&&!w?e.jsxs($,{onClick:D,disabled:d,children:[d?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(wn,{className:"h-4 w-4 mr-2"}),d?"Searching…":"Find profile"]}):w?e.jsxs($,{disabled:!0,children:[e.jsx(Ct,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save selected"]})]})]})})}const j$n=["jeremy@relevelup.com"];function N$n(){const{user:s}=_s(),t=((s==null?void 0:s.email)||"").toLowerCase();return j$n.includes(t)}const pCt="America/New_York";function k$n(s){const t=new Date(s),n=new Intl.DateTimeFormat("en-US",{timeZone:pCt,month:"short",day:"numeric",year:"numeric"}).format(t),r=new Intl.DateTimeFormat("en-US",{timeZone:pCt,hour:"numeric",minute:"2-digit"}).format(t);return`${n} · ${r}`}function S$n(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 C$n({contactId:s,ownerUserId:t,legacyNote:n}){const r=Zt(),[a,i]=j.useState(""),{data:l=[],isLoading:o}=st({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=mt({mutationFn:async u=>{var x,v,y;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)||[(v=m==null?void 0:m.user_metadata)==null?void 0:v.first_name,(y=m==null?void 0:m.user_metadata)==null?void 0:y.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=mt({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(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(no,{className:"h-4 w-4 text-primary"}),"Notes",l.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1 rounded-full text-[11px]",children:l.length})]})}),e.jsxs(Le,{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(Ct,{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(ca,{className:"h-3 w-3"}),k$n(u.created_at)]}),e.jsxs("span",{children:["· ",S$n(u.created_at)]}),u.source!=="agent"?e.jsxs($e,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(wn,{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(qn,{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 A$n="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function E$n({open:s,onOpenChange:t,contact:n}){var W;const{user:r}=_s(),a=Zn(),i=Zt(),{intakePage:l,isLoading:o}=_6e(),{isGmailConnected:c,gmailEmail:d}=Gy(),u=y6e(),{data:h}=st({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]),[v,y]=j.useState("gmail"),[b,w]=j.useState(""),[S,A]=j.useState(""),[E,I]=j.useState(!1);j.useEffect(()=>{s&&(w(`Quick favor, ${n.first_name} — can you update your info?`),A(x),y(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:Z,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=Z==null?void 0:Z.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){ne.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!b.trim()||!S.trim()){ne.error("Subject and message are required");return}I(!0);const V=await R(),G=D(V),Z=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(v==="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 le=X&&X.error?X:null;if(ae){le={error:"send_failed",message:ae.message};const re=ae.context;if(re&&typeof re.json=="function")try{le=await re.clone().json()}catch{}}if(le)if(le.error==="insufficient_scope")await Z(),ne.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(le.message||le.error||"Failed to send");else if(!(X!=null&&X.success))throw new Error("Failed to send")}else await Z();try{await u.mutateAsync({contactId:n.id,actionTypeId:A$n,notes:`Sent Connect Page invite — Subject: "${b}"`})}catch(X){console.warn("Failed to log activity:",X)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),ne.success("Connect Page invite sent!"),t(!1)}catch(X){console.error("Send error:",X),ne.error(X instanceof Error?X.message:"Failed to send invite")}finally{I(!1)}},U=S.split(/\n\n+/).filter(Boolean);return e.jsx(Os,{open:s,onOpenChange:V=>!E&&t(V),children:e.jsxs(Fs,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(wn,{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(Ct,{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(pa,{value:v,onValueChange:V=>y(V),className:"mt-1.5",children:e.jsxs(ga,{className:"grid w-full grid-cols-2",children:[e.jsxs(Xt,{value:"gmail",disabled:!c,children:[e.jsx(pn,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(Xt,{value:"system",children:[e.jsx(wn,{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:v==="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=>A(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(Ir,{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(Ct,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(vl,{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(nu,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function T$n(){const{user:s}=_s();return st({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 M$n(s){return st({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 P$n(s){return st({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 zQt(){const s=Zt(),{user:t}=_s(),{leadSite:n}=tg();return mt({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 I$n(){const s=Zt();return mt({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 L$n(){const s=Zt();return mt({mutationFn:async t=>{const{error:n}=await q.from("cmas").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function R$n(){const{leadSite:s}=tg();return mt({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 D$n(){const{leadSite:s}=tg();return mt({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 F$n(){const s=Zt();return mt({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 gCt(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 O$n(s){return st({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 z$n(s){return st({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 fit(){const s=Sa(),t=Zt();return mt({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 DK(){const s=Zt();return mt({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 BQt(){const s=Zt();return mt({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 $Qt(){const s=Zt();return mt({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 UQt(){const s=Zt();return mt({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 B$n(s){return st({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 qQt(){const s=Zt();return mt({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 $$n(){const s=Sa();return st({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 U$n(){const s=Sa(),t=Zt();return mt({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 q$n(){const s=Zt();return mt({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 V$n(){const s=Zt();return mt({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 oC(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function H$n({contactId:s}){const t=Zn(),n=Zt(),[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=DK(),v=qQt(),{data:y,isLoading:b}=st({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=(y==null?void 0:y.map(P=>P.id))||[],{data:S}=st({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}),A=P=>{navigator.clipboard.writeText(oC(P)),a(P),ne.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},E=async(P,R)=>{if(!d.trim())return;const D=d.trim(),O=h.trim();await v.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?oC(R):void 0,force:!0}});if(W)throw W;U!=null&&U.emailSent?ne.success("Update posted & client emailed"):ne.success(`Update posted (${(U==null?void 0:U.reason)||"no email sent"})`)}catch(U){console.error("Portal notification failed:",U),ne.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]}),ne.success("Portal settings updated!"))};return b||!y||y.length===0?null:e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(cl,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Le,{className:"space-y-3",children:y.map(P=>{var U,W,V;const R=((U=P.stage_mapping)==null?void 0:U.length)>0?P.stage_mapping:XLe(((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($e,{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:Js(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:()=>A(P.slug),children:[r===P.slug?e.jsx(ma,{className:"h-3 w-3 mr-1"}):e.jsx(Za,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(oC(P.slug),"_blank"),children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(Os,{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(no,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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()||v.isPending,className:"w-full",children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(Os,{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(Nd,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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(jn,{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(jn,{checked:f.show_post_close_tips,onCheckedChange:G=>g({...f,show_post_close_tips:G})})]}),e.jsx(Vc,{}),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(Qa,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),y.length>1&&e.jsx(Vc,{})]},P.id)})})]})}function G$n({contactId:s}){const{data:t}=st({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}=st({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(je,{className:"overflow-hidden",children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{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(Ta,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs($e,{variant:"secondary",className:"text-xs ml-auto",children:[r.length," ",r.length===1?"property":"properties"]})]})}),e.jsx(Le,{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(ca,{className:"h-3 w-3"}),e.jsx("span",{title:Js(new Date(l.viewed_at),"PPp"),children:hu(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(Ir,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}function W$n({contactId:s,contactName:t}){var O,U,W;const{user:n}=_s(),r=Sa(),{hasIdx:a}=tg(),i=Zt(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState(null),[g,x]=j.useState(!1),[v,y]=j.useState(!1),{data:b,isLoading:w}=st({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,A]=j.useState({}),E=()=>{A({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=mt({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),ne.success("Home search saved!")},onError:V=>{ne.error(V.message||"Failed to save home search")}}),P=mt({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),ne.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){ne.error(V.message||"Failed to generate preview"),d(!1)}finally{x(!1)}}},D=async()=>{if(b!=null&&b.id&&await mo(`Send property alert email to ${t} now?`)){y(!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?(ne.success(`Sent ${V.sent_count} ${V.sent_count===1?"listing":"listings"} to ${V.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):ne.info((V==null?void 0:V.message)||"No new matching listings to send right now.")}catch(V){ne.error(V.message||"Failed to send alert")}finally{y(!1)}}};return w?null:b&&!l?e.jsxs(e.Fragment,{children:[e.jsxs(je,{className:"overflow-hidden",children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{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(zy,{className:"h-4 w-4 text-green-600"}):e.jsx(KS,{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($e,{variant:b.is_active?"default":"secondary",className:"text-xs ml-auto",children:[b.is_active?"Active":"Paused"," · ",b.frequency]})]})}),e.jsxs(Le,{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($e,{variant:"outline",className:"gap-1",children:[e.jsx(su,{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($e,{variant:"outline",className:"gap-1",children:[e.jsx(C4,{className:"h-3 w-3"}),b.min_beds,"+ beds"]}):null,b.min_baths?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(C0,{className:"h-3 w-3"}),b.min_baths,"+ baths"]}):null,(O=b.cities)==null?void 0:O.map(V=>e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(ui,{className:"h-3 w-3"}),V]},V)),(U=b.zip_codes)==null?void 0:U.map(V=>e.jsx($e,{variant:"outline",children:V},V)),(W=b.property_types)==null?void 0:W.map(V=>e.jsx($e,{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(br,{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(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ta,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs($,{size:"sm",onClick:D,disabled:v||!b.is_active,title:b.is_active?"Send this alert email now":"Activate alert to send",children:[v?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Zr,{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(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(mr,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx($s,{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(Ct,{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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>d(!1),children:"Close"}),u&&e.jsxs($,{onClick:()=>{d(!1),D()},disabled:v||!b.is_active,children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]}):l?e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[a?e.jsx(zy,{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(Le,{className:"space-y-4",children:[e.jsx(OQt,{value:S,onChange:A,hasIdx:a,idxNote:e.jsx($,{asChild:!0,variant:"link",size:"sm",className:"h-auto p-0 text-xs",children:e.jsx(br,{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(Ct,{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(mr,{className:"h-4 w-4"})})]})]})]}):e.jsx(je,{className:"overflow-hidden",children:e.jsx(Le,{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(zy,{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 K$n({contactId:s,contactName:t}){var Z;const{user:n}=_s(),r=Sa(),{hasLeadSite:a}=tg(),i=Zt(),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState([]),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[v,y]=j.useState(!1),[b,w]=j.useState(""),S=j.useRef(null),A=j.useRef(null),{data:E}=st({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 le=X.theme_config||{},re=Array.isArray(le.searchCities)?le.searchCities:[];return X.mls_market_area&&!re.includes(X.mls_market_area)&&re.unshift(X.mls_market_area),re},enabled:!!r}),{data:I,isLoading:P}=st({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=>{A.current&&!A.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=mt({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),y(!0)},onError:X=>{ne.error(X.message||"Failed to generate preview")}}),W=mt({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:()=>{ne.success(`Market report sent to ${t}!`)},onError:X=>{ne.error(X.message||"Failed to send report")}}),V=mt({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),ne.success(m?"Monthly market report enabled!":"Market report disabled")},onError:X=>{ne.error(X.message||"Failed to save")}}),G=mt({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([]),ne.success("Market report removed")},onError:X=>{ne.error(X.message||"Failed to remove market report")}});return!a||P?null:I!=null&&I.market_report_enabled&&!l?e.jsxs(je,{className:"overflow-hidden",children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{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(Gl,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx($e,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Le,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((Z=I.market_report_cities)==null?void 0:Z.length)>0?I.market_report_cities.map(X=>e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(ui,{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(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ta,{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(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Zr,{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(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(mr,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(Os,{open:v,onOpenChange:y,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(Us,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Gl,{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:()=>{y(!1),W.mutate()},disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(Gl,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Send Monthly Report"}),e.jsx(jn,{checked:m,onCheckedChange:f})]}),m&&e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ui,{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(wl,{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(cn,{className:"h-4 w-4"})})]}),g&&O.length>0&&e.jsx("div",{ref:A,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children: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(ui,{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($e,{variant:"secondary",className:"gap-1",children:[X,e.jsx("button",{onClick:()=>h(u.filter(ae=>ae!==X)),children:e.jsx(mr,{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(Ct,{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(je,{className:"overflow-hidden",children:e.jsx(Le,{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(Gl,{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 Y$n({contactId:s,contactName:t}){const n=Zt(),[r,a]=j.useState(""),{data:i,isLoading:l}=st({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=mt({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"]}),ne.success(d?`${t} will no longer receive newsletters or marketing emails`:`${t} is opted back in to marketing emails`)},onError:d=>ne.error(d.message)}),c=!!(i!=null&&i.email_opt_out);return e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(WI,{className:"h-4 w-4"}),"Email Preferences",c&&e.jsx($e,{variant:"destructive",className:"ml-1",children:"Opted out"})]})}),e.jsx(Le,{className:"space-y-4",children:l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{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(jn,{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 ",Js(new Date(i.email_opt_out_at),"MMM d, yyyy")]})]})]})})]})}function Z$n(s){return st({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 X$n(s){switch(s){case"active":return e.jsx($e,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx($e,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx($e,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx($e,{variant:"outline",children:"Exited"});default:return e.jsx($e,{variant:"outline",children:s})}}function xCt(s){return s==="sent"?e.jsx(Vr,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(Al,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(Cv,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ca,{className:"h-4 w-4 text-muted-foreground"})}function Q$n({contactId:s}){const t=Zn(),{data:n,isLoading:r}=Z$n(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(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(XI,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Le,{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(XI,{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"}),X$n(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: ",hu(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",hu(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",hu(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(Os,{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:xCt(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(no,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(pn,{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"," · ",Js(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(Fs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[xCt(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:Js(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 H9e=1e3,J$n=5e4;async function oue(s){const t=[];for(let n=0;n{const n=t.id,r=await oue(()=>{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 oue(()=>{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 oue(()=>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 y=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&&(y=y.eq("contact_id",s)),y});c.push(...v)}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($e,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Le,{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(pn,{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($e,{variant:"outline",className:`text-xs ${eUn[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Js(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(br,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}const sUn={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"},nUn={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 rUn(s){if(!s)return null;const t=s.trim();if(/^[A-Za-z]{2}$/.test(t))return t.toUpperCase();const n=t.toLowerCase();return sUn[n]||null}function aUn(s){return!s||!s.trim().match(/^\d{5}(-?\d{4})?$/)?null:s.trim().split("-")[0]}function iUn(s){let t=s.toLowerCase();for(const[n,r]of Object.entries(nUn))t=t.replace(new RegExp(`\\b${n}\\b`,"g"),r);return t}function oUn(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 HQt(s,t,n,r){const a=[s,t,n,r].filter(Boolean).join(", ").trim(),i=rUn(n),l=aUn(r);let o=null,c=null;if(s){const g=oUn(s.trim());o=g.street,c=g.unit}const d=(t==null?void 0:t.trim())||null,u=[];o&&u.push(iUn(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 pit(){const{data:{user:s},error:t}=await q.auth.getUser();if(t||!s)throw new Error("Not authenticated");return s.id}async function lUn(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 cUn(s){const t=await pit(),{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 dUn(s,t,n={}){const a={owner_user_id:await pit(),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 uUn(s){const{error:t}=await q.from("contact_properties").delete().eq("id",s);if(t)throw new Error(t.message)}async function yCt(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 nA(s){return s==null||Number.isNaN(s)?"—":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}function rA(s,t=""){return s==null||Number.isNaN(s)?"—":`${new Intl.NumberFormat("en-US").format(s)}${t}`}function vCt(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 LSr(){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:v,error:y},{count:b,error:w},{count:S,error:A},{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,y,w,A,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:v??0,possibleNonOwnerOccupied:b??0,propertiesMissingValuation:S??0}}async function RSr(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 hUn(s){switch(s){case"verified":return"default";case"high":return"default";case"medium":return"secondary";case"low":return"outline";default:return"outline"}}async function DSr(s,t={}){const n=await pit();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:HQt(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 GQt=[{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"}],WQt=[{value:"current",label:"Current"},{value:"former",label:"Former"},{value:"possible",label:"Possible"},{value:"unknown",label:"Unknown"}];function mUn({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=mt({mutationFn:()=>yCt(r.id,{relationship_type:d,ownership_status:h,is_primary_residence:f}),onSuccess:()=>{ne.success("Property relationship updated"),c(!1),t()},onError:A=>ne.error(A instanceof Error?A.message:"Update failed")}),v=mt({mutationFn:()=>uUn(r.id),onSuccess:()=>{ne.success("Property unlinked"),t()},onError:A=>ne.error(A instanceof Error?A.message:"Unlink failed")}),y=a[0],b=n.primary_data_source||(y==null?void 0:y.source_name)||"Manual",w=n.last_enriched_at||(y==null?void 0:y.retrieved_at)||n.updated_at,S=[{id:"overview",title:"Property Overview",icon:zI,rows:[{label:"Property type",value:n.property_type||"—"},{label:"Bedrooms",value:rA(n.bedrooms)},{label:"Bathrooms",value:rA(n.bathrooms,"+")},{label:"Living area",value:rA(n.living_area_square_feet," sq ft")},{label:"Lot size",value:n.lot_size?`${rA(n.lot_size)} ${n.lot_size_units||""}`:"—"},{label:"Year built",value:rA(n.year_built)},{label:"Parcel ID",value:n.parcel_id||"—"},{label:"County",value:n.county||"—"}]},{id:"value",title:"Value & Valuation",icon:su,rows:[{label:"Estimated value",value:nA(n.estimated_value)},{label:"Value range",value:n.estimated_value_low&&n.estimated_value_high?`${nA(n.estimated_value_low)} – ${nA(n.estimated_value_high)}`:"—"},{label:"Rent estimate",value:nA(n.rent_estimate)},{label:"Data confidence",value:n.data_confidence}]},{id:"tax",title:"Tax Information",icon:Tf,rows:[{label:"Tax-assessed value",value:nA(n.tax_assessed_value)},{label:"Assessed year",value:rA(n.tax_assessed_year)},{label:"Annual property tax",value:nA(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:Cw,rows:[{label:"Last sale price",value:nA(n.last_sale_price)},{label:"Last sale date",value:n.last_sale_date||"—"}]},{id:"sources",title:"Data Sources",icon:Sq,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:Ea,rows:a.length?a.slice(0,5).map(A=>({label:new Date(A.created_at).toLocaleDateString(),value:`${A.source_name} — ${vCt(A.status)}`})):[{label:"History",value:"No enrichment events yet"}]}];return e.jsxs(je,{className:"overflow-hidden",children:[e.jsx(St,{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(Et,{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(ui,{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($e,{variant:"default",className:"gap-1",children:[e.jsx(ei,{className:"h-3 w-3"})," Primary"]}),e.jsx($e,{variant:hUn(n.data_confidence),children:n.data_confidence}),e.jsx($e,{variant:"outline",children:vCt(n.enrichment_status)})]})]})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(lue,{label:"Estimated value",value:nA(n.estimated_value)}),e.jsx(lue,{label:"Tax assessed",value:nA(n.tax_assessed_value)}),e.jsx(lue,{label:"Bed / Bath",value:`${rA(n.bedrooms)} / ${rA(n.bathrooms)}`}),e.jsx(lue,{label:"Sq ft",value:rA(n.living_area_square_feet)})]}),e.jsxs(y1,{open:i,onOpenChange:l,children:[e.jsx(v1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between",children:[e.jsx("span",{children:"Property details"}),e.jsx(wl,{className:Pt("h-4 w-4 transition-transform",i&&"rotate-180")})]})}),e.jsx(b1,{className:"space-y-4 pt-2",children:S.map(A=>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(A.icon,{className:"h-4 w-4 text-primary"}),A.title]}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:A.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))})]},A.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Os,{open:o,onOpenChange:c,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",children:[e.jsx(_f,{className:"mr-1 h-3.5 w-3.5"})," Edit relationship"]})}),e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{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:A=>u(A),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:GQt.map(A=>e.jsx(Ge,{value:A.value,children:A.label},A.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Ownership status"}),e.jsxs(ms,{value:h,onValueChange:A=>m(A),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:WQt.map(A=>e.jsx(Ge,{value:A.value,children:A.label},A.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:`primary-${r.id}`,type:"checkbox",checked:f,onChange:A=>g(A.target.checked),className:"h-4 w-4 rounded border-border"}),e.jsx(ee,{htmlFor:`primary-${r.id}`,children:"Primary residence"})]})]}),e.jsxs(Nr,{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:()=>yCt(r.id,{is_primary_residence:!r.is_primary_residence}).then(()=>{ne.success(r.is_primary_residence?"Removed primary residence":"Marked as primary residence"),t()}).catch(A=>ne.error(A.message)),children:[e.jsx(ei,{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:()=>v.mutate(),disabled:v.isPending,children:[e.jsx(wv,{className:"mr-1 h-3.5 w-3.5"})," Unlink property"]})]})]})]})}function lue({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 fUn({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||""),[v,y]=j.useState("owner"),[b,w]=j.useState("current"),[S,A]=j.useState(!1),E=mt({mutationFn:async()=>{const I=[c,u,m,g].filter(Boolean).join(", "),P=HQt(c,u,m,g);if(!P.normalized)throw new Error("Could not normalize address. Please check the fields.");const R=await cUn({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 dUn(s,R.id,{relationship_type:v,ownership_status:b,is_primary_residence:S})},onSuccess:()=>{ne.success("Property added"),o(!1),d(t||""),h(n||""),f(r||""),x(a||""),i()},onError:I=>ne.error(I instanceof Error?I.message:"Failed to add property")});return e.jsxs(Os,{open:l,onOpenChange:o,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(cn,{className:"mr-1 h-4 w-4"})," Add property"]})}),e.jsxs(Fs,{className:"sm:max-w-lg",children:[e.jsx(Us,{children:e.jsx($s,{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:v,onValueChange:I=>y(I),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:GQt.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:WQt.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=>A(I.target.checked),className:"h-4 w-4 rounded border-border"}),e.jsx(ee,{htmlFor:"pi-primary",children:"Primary residence"})]})]}),e.jsxs(Nr,{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 pUn({contactId:s,contactAddress:t,contactCity:n,contactState:r,contactZip:a}){const i=Zt(),{data:l,isLoading:o,error:c}=st({queryKey:["contact-properties",s],queryFn:()=>lUn(s)}),d=()=>{i.invalidateQueries({queryKey:["contact-properties",s]})};if(o)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-10 w-48"}),e.jsx(xn,{className:"h-48 w-full"})]});if(c)return e.jsx(je,{className:"border-destructive/50 bg-destructive/5",children:e.jsxs(Le,{className:"flex items-center gap-3 py-6",children:[e.jsx(Al,{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(fUn,{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(je,{className:"border-dashed",children:e.jsxs(Le,{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(mUn,{detail:h,onMutate:d},h.relationship.id))})]})}function gUn({videoId:s}){var l;const{data:t,isLoading:n,error:r}=u9n(s);if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"w-full aspect-video rounded-lg"}),e.jsx(xn,{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(Al,{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 xUn({contactId:s}){const t=Zn(),[n,r]=j.useState(!1),{data:a,isLoading:i}=st({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}=st({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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(ma,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx($e,{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(cn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Le,{className:"space-y-1",children:i?e.jsx(xn,{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:Js(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(yUn,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function yUn({contactId:s,open:t,onOpenChange:n}){const[r,a]=j.useState(""),[i,l]=j.useState("medium"),[o,c]=j.useState(),{data:d}=st({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?Js(o,"yyyy-MM-dd"):null}]);if(h){console.error("Task create error:",h);return}n(!1)};return e.jsx(Os,{open:t,onOpenChange:n,children:e.jsxs(Fs,{className:"sm:max-w-[400px]",children:[e.jsx(Us,{children:e.jsx($s,{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?Js(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 vUn({contactId:s}){const t=Zn(),{data:n,isLoading:r}=st({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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(wx,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Le,{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($e,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs($e,{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(Qa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function bUn(){var Ks,Cn,Rr,ia;const{contactId:s}=Wi(),{isAdmin:t}=_s(),{hasIdx:n}=tg(),r=Zn(),[a]=Nc(),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(Hs=>Hs.trim()).filter(Boolean)),[c]),{data:h,isLoading:m}=fHs(s||""),{data:f}=Uw(),{data:g}=Jae(),{data:x}=cK(3650),{data:v}=sDe(365),{data:y}=O$n(s),{contactsWithScores:b}=sie(),{data:w}=Aie(),{score:S}=MWs(s||""),A=Kst(),E=wUt(),I=y6e(),P=_Ut(),[R,D]=j.useState(!1),[O,U]=j.useState("overview"),[W,V]=j.useState(!1),G=N$n(),[Z,X]=j.useState({}),[ae,le]=j.useState(!1),[re,te]=j.useState(!1),[J,ce]=j.useState(null),[ve,fe]=j.useState(""),[ue,be]=j.useState(void 0),[Ee,ke]=j.useState(""),[Ie,Fe]=j.useState(null),[Ne,Be]=j.useState(!1),[Se,Ae]=j.useState(null),[Ce,qe]=j.useState(!1),{isGmailConnected:ze,gmailEmail:Ve}=Gy(),{isReady:ht}=FB(),Qe=ht||ze,at=zQt(),[rt,Ke]=j.useState(!1),{data:Je}=st({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:Hs}}=await q.auth.getUser();if(!Hs)return!1;const{data:Br}=await q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",Hs.id);return(Br||[]).some(Ur=>Ur.is_active&&Ur.mls_provider_id&&!Ur.no_mls_mode)}}),ft=async()=>{var Sn,Fn,bn,xs;if(!h)return;const Hs=(Sn=h.address)==null?void 0:Sn.trim(),Br=(Fn=h.city)==null?void 0:Fn.trim(),Ur=(bn=h.state)==null?void 0:bn.trim().toUpperCase(),Wn=((xs=h.zip_code)==null?void 0:xs.trim())||"";if(!Hs||!Br||!Ur){ne.error("Add a full address (street, city, state) before creating a CMA.");return}try{Ke(!0);const Tr=await at.mutateAsync({subject:{address:Hs,city:Br,state:Ur,zip:Wn},contactId:h.id,title:`${h.first_name||""} ${h.last_name||""}`.trim()+" — "+Hs});r(`/mission-control/cma/${Tr.id}`)}catch(Tr){ne.error("Could not create CMA: "+((Tr==null?void 0:Tr.message)||"unknown error"))}finally{Ke(!1)}},{data:gt}=st({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:Hs,error:Br}=await q.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(Br)throw Br;return Hs},enabled:!!s}),es=Hs=>{if(!Hs)return null;const Br=Hs.match(/Video ID:\s*([a-f0-9-]+)/i);return Br?Br[1]:null},Ht=j.useMemo(()=>{if(!b)return[];const Hs=new Map;if(u.size>0&&w)for(const Ur of w)Hs.has(Ur.contact_id)||Hs.set(Ur.contact_id,new Set),Hs.get(Ur.contact_id).add(Ur.tag_id);let Br=b.filter(Ur=>{var bn,xs,Tr;const Wn=i===""||`${Ur.first_name} ${Ur.last_name}`.toLowerCase().includes(i.toLowerCase())||((bn=Ur.email)==null?void 0:bn.toLowerCase().includes(i.toLowerCase()))||((xs=Ur.phone)==null?void 0:xs.includes(i)),Sn=l==="all"||((Tr=Ur.tags)==null?void 0:Tr.some(Lr=>Lr.relationship_type_id===l));let Fn=!0;if(u.size>0){const Lr=Hs.get(Ur.id)||new Set;d==="all"?Fn=Array.from(u).every(la=>Lr.has(la)):Fn=Array.from(u).some(la=>Lr.has(la))}return Wn&&Sn&&Fn});return o==="not-touched-90"?Br=Br.filter(Ur=>{const Wn=Ur.relationshipScore.daysSinceTouch;return Wn===null||Wn>90}):o==="at-risk"?Br=Br.filter(Ur=>Ur.relationshipScore.status==="at-risk"):o==="cooling"?Br=Br.filter(Ur=>Ur.relationshipScore.status==="cooling"):o==="warm"&&(Br=Br.filter(Ur=>Ur.relationshipScore.status==="warm")),Br.map(Ur=>Ur.id)},[b,i,l,o,u,d,w]),as=Ht.indexOf(s||""),bs=as>0?Ht[as-1]:null,Ut=as1&&as!==-1,is=Hs=>{const Br=new URLSearchParams;i&&Br.set("search",i),l!=="all"&&Br.set("type",l),o!=="all"&&Br.set("status",o),u.size>0&&(Br.set("tags",Array.from(u).join(",")),Br.set("tagMode",d));const Ur=Br.toString();return`/mission-control/contacts/${Hs}${Ur?`?${Ur}`:""}`},jt=j.useMemo(()=>{const Hs=((x==null?void 0:x.filter(Ur=>Ur.contact_id===s))||[]).map(Ur=>{var bn,xs,Tr;const Wn=es(Ur.notes);let Sn=((bn=Ur.action_type)==null?void 0:bn.name)||"Touch",Fn=Ur.notes;if(Sn==="Other"&&((xs=Ur.notes)!=null&&xs.startsWith("["))){const Lr=Ur.notes.indexOf("]");Lr>0&&(Sn=Ur.notes.substring(1,Lr),Fn=Ur.notes.substring(Lr+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:Ur.id,type:"touch",completed_at:Ur.completed_at,name:Sn,color:((Tr=Ur.action_type)==null?void 0:Tr.color)||"#3B82F6",notes:Fn,videoId:Wn}}),Br=((v==null?void 0:v.filter(Ur=>Ur.contact_id===s))||[]).map(Ur=>({id:Ur.id,type:"popby",completed_at:Ur.completed_at,name:"Pop-by",color:"#F97316",notes:Ur.notes,videoId:null}));return[...Hs,...Br].sort((Ur,Wn)=>new Date(Wn.completed_at).getTime()-new Date(Ur.completed_at).getTime())},[x,v,s]),zs=Hs=>{var Br;return{first_name:Hs.first_name||"",last_name:Hs.last_name||"",email:Hs.email||"",phone:Hs.phone||"",address:Hs.address||"",city:Hs.city||"",state:Hs.state||"",zip_code:Hs.zip_code||"",address2_label:Hs.address2_label||"",address2:Hs.address2||"",address2_city:Hs.address2_city||"",address2_state:Hs.address2_state||"",address2_zip:Hs.address2_zip||"",mail_to_secondary:!!Hs.mail_to_secondary,birthday:Hs.birthday||"",home_anniversary:Hs.home_anniversary||"",wedding_anniversary:Hs.wedding_anniversary||"",spouse_birthday:Hs.spouse_birthday||"",spouse_name:Hs.spouse_name||"",spouse_email:Hs.spouse_email||"",company_name:Hs.company_name||"",job_title:Hs.job_title||"",lead_source_id:Hs.lead_source_id||"",notes:Hs.notes||"",tagIds:((Br=Hs.tags)==null?void 0:Br.map(Ur=>Ur.relationship_type_id))||[]}};j.useEffect(()=>{D(!1),X({})},[s]);const yt=j.useRef(null);j.useEffect(()=>{h!=null&&h.id&&yt.current!==h.id&&(yt.current=h.id,X(zs(h)))},[h==null?void 0:h.id,h]);const gs=()=>{h&&(X(zs(h)),le(KSt(h)),D(!0))},Ss=async()=>{await A.mutateAsync({id:s,...Z,lead_source_id:Z.lead_source_id||null}),D(!1)},Ds=async()=>{await mo("Are you sure you want to delete this contact?")&&(await E.mutateAsync(s),r("/mission-control/contacts"))},zt=((Ks=g==null?void 0:g.find(Hs=>Hs.id===J))==null?void 0:Ks.name)==="Other",vs=async()=>{if(!J||zt&&!Ee.trim())return;const Hs=ue?new Date(ue.getFullYear(),ue.getMonth(),ue.getDate(),12,0,0).toISOString():void 0,Br=zt?`[${Ee.trim()}]${ve?" — "+ve:""}`:ve;await I.mutateAsync({contactId:s,actionTypeId:J,notes:Br,completedAt:Hs}),te(!1),ce(null),fe(""),be(void 0),ke("")},dn=(Hs,Br)=>{Qe&&h?(Ae({email:Hs,name:Br||`${h.first_name} ${h.last_name||""}`.trim()}),Be(!0)):window.location.href=`mailto:${Hs}`};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(kd,{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:()=>bs&&r(is(bs)),disabled:!bs,children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-1 text-xs text-muted-foreground whitespace-nowrap",children:[as+1," of ",Ht.length]}),e.jsx($,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>Ut&&r(is(Ut)),disabled:!Ut,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(y$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(WI,{className:"h-3 w-3"}),"Emails opted out"]}),(((Cn=h.lead_source_ref)==null?void 0:Cn.name)||h.lead_source)&&e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:((Rr=h.lead_source_ref)==null?void 0:Rr.name)||h.lead_source}),(ia=h.tags)==null?void 0:ia.map(Hs=>{const Br=f==null?void 0:f.find(Ur=>Ur.id===Hs.relationship_type_id);return Br?e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:Br.name},Hs.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:()=>dn(h.email),className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted transition-opacity hover:opacity-100",children:[e.jsx(pn,{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(ui,{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(wn,{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(bp,{className:"h-4 w-4"}),"Edit"]}),e.jsx("button",{onClick:Ds,className:"hub-glass inline-flex h-9 w-9 items-center justify-center rounded-full",title:"Delete contact",children:e.jsx(qn,{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(no,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Text"]}),h.email&&e.jsxs("button",{onClick:()=>dn(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(pn,{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(fa,{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(cn,{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(wn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Connect Page"]})]})]})}),e.jsxs(pa,{value:O,onValueChange:Hs=>{Hs==="details"&&!R&&gs(),U(Hs)},children:[e.jsx("div",{className:"-mx-1 overflow-x-auto px-1",children:e.jsxs(ga,{className:"inline-flex h-10 w-auto",children:[e.jsx(Xt,{value:"overview",children:"Overview"}),e.jsx(Xt,{value:"details",children:"Details"}),e.jsx(Xt,{value:"activity",children:"Activity"}),e.jsx(Xt,{value:"marketing",children:"Marketing"}),t&&e.jsx(Xt,{value:"property-intel",children:"Property Intelligence"})]})}),e.jsx(Qt,{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(LBn,{contact:h,onLogTouch:()=>te(!0)}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ea,{className:"h-4 w-4 text-primary"}),"Key Dates"]})}),e.jsxs(Le,{children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[{icon:dl,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:Hs,label:Br,value:Ur})=>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(Hs,{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:Br}),e.jsx("p",{className:"truncate text-sm font-medium",children:Ur?Js(kh(Ur),kh(Ur).getFullYear()===1900?"MMMM d":"MMMM d, yyyy"):"—"})]})]},Br))}),jt.length>0&&e.jsxs("p",{className:"mt-3 text-xs text-muted-foreground",children:["Last contacted ",Js(new Date(jt[0].completed_at),"MMM d, yyyy")," (",jt[0].name,")",h.created_at&&` · Added ${Js(new Date(h.created_at),"MMM d, yyyy")}`]})]})]}),(h.address||h.city)&&e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(va,{className:"h-4 w-4 text-primary"}),"Home"]})}),e.jsxs(Le,{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ui,{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}`:""]})]})]}),Je&&h.address&&h.city&&h.state&&e.jsxs($,{size:"sm",variant:"outline",onClick:ft,disabled:rt,children:[rt?e.jsx(Ct,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(r2,{className:"mr-1 h-4 w-4"}),"Create CMA"]})]}),KSt(h)&&e.jsx(Le,{className:"pt-0",children:e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-dashed p-3",children:[e.jsx(ui,{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:SYe(h).label}),h.mail_to_secondary&&e.jsx($e,{variant:"secondary",className:"text-[10px]",children:"Mail goes here"})]}),e.jsx("div",{className:"text-muted-foreground",children:xBn(SYe(h))})]})]})})]}),e.jsx(C$n,{contactId:h.id,ownerUserId:h.owner_user_id,legacyNote:h.notes}),e.jsx(xUn,{contactId:s})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-base",children:"Tags"})}),e.jsx(Le,{children:e.jsx(aCt,{contactId:s})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(sl,{className:"h-4 w-4 text-primary"}),"People & Work"]})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsx(AYe,{contactId:s,currentSpouseContactId:(h==null?void 0:h.spouse_contact_id)||null,currentSpouseName:h.spouse_name||null,currentSpouseEmail:h.spouse_email||null,onLink:Hs=>P.mutate({contactId:s,spouseContactId:Hs}),onUnlink:()=>P.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(wi,{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(vUn,{contactId:s}),e.jsx(H$n,{contactId:s})]})]})}),e.jsx(Qt,{value:"details",className:"mt-4",children:e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-base",children:"Edit Contact"})}),e.jsxs(Le,{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:Z.first_name||"",onChange:Hs=>X({...Z,first_name:Hs.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"last_name",children:"Last Name"}),e.jsx(pe,{id:"last_name",value:Z.last_name||"",onChange:Hs=>X({...Z,last_name:Hs.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:Z.email||"",onChange:Hs=>X({...Z,email:Hs.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Phone"}),e.jsx(pe,{id:"phone",value:Z.phone||"",onChange:Hs=>X({...Z,phone:Hs.target.value})})]})]})]}),e.jsx(Vc,{}),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:Z.address||"",onChange:Hs=>X({...Z,address:Hs.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:Z.city||"",onChange:Hs=>X({...Z,city:Hs.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:Z.state||"",onChange:Hs=>X({...Z,state:Hs.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:Z.zip_code||"",onChange:Hs=>X({...Z,zip_code:Hs.target.value}),placeholder:"12345"})]})]})]}),e.jsx(Vc,{}),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:()=>le(!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:Z.address2_label||"",onChange:Hs=>X({...Z,address2_label:Hs.target.value}),placeholder:"Vacation home"}),e.jsx("datalist",{id:"contact-address-labels",children:mQt.map(Hs=>e.jsx("option",{value:Hs},Hs))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2",children:"Street Address"}),e.jsx(pe,{id:"address2",value:Z.address2||"",onChange:Hs=>X({...Z,address2:Hs.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:Z.address2_city||"",onChange:Hs=>X({...Z,address2_city:Hs.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_state",children:"State"}),e.jsx(pe,{id:"address2_state",value:Z.address2_state||"",onChange:Hs=>X({...Z,address2_state:Hs.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:Z.address2_zip||"",onChange:Hs=>X({...Z,address2_zip:Hs.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(jn,{id:"mail_to_secondary",checked:!!Z.mail_to_secondary,onCheckedChange:Hs=>X({...Z,mail_to_secondary:Hs})})]}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>{X({...Z,address2_label:"",address2:"",address2_city:"",address2_state:"",address2_zip:"",mail_to_secondary:!1}),le(!1)},children:"Remove second address"})]})]}),e.jsx(Vc,{}),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:Z.birthday||"",onChange:Hs=>X({...Z,birthday:Hs.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(pe,{id:"home_anniversary",type:"date",value:Z.home_anniversary||"",onChange:Hs=>X({...Z,home_anniversary:Hs.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(pe,{id:"wedding_anniversary",type:"date",value:Z.wedding_anniversary||"",onChange:Hs=>X({...Z,wedding_anniversary:Hs.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(pe,{id:"spouse_birthday",type:"date",value:Z.spouse_birthday||"",onChange:Hs=>X({...Z,spouse_birthday:Hs.target.value})})]})]})]}),e.jsx(Vc,{}),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(AYe,{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:Hs=>P.mutate({contactId:s,spouseContactId:Hs}),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:Z.company_name||"",onChange:Hs=>X({...Z,company_name:Hs.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:Z.job_title||"",onChange:Hs=>X({...Z,job_title:Hs.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(IQt,{value:Z.lead_source_id||"",onChange:Hs=>X({...Z,lead_source_id:Hs})})]}),e.jsx(Vc,{}),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(Hs=>Hs.active).map(Hs=>{var Ur;const Br=!!((Ur=Z.tagIds)!=null&&Ur.includes(Hs.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",Br?"border-primary bg-primary/10 text-primary":"border-border hover:bg-accent"),children:[e.jsx(ai,{checked:Br,onCheckedChange:Wn=>{var Sn;X(Wn?{...Z,tagIds:[...Z.tagIds||[],Hs.id]}:{...Z,tagIds:(Sn=Z.tagIds)==null?void 0:Sn.filter(Fn=>Fn!==Hs.id)})}}),Hs.name]},Hs.id)})}),e.jsxs("div",{children:[e.jsx(ee,{children:"Tags"}),e.jsx("div",{className:"mt-2",children:e.jsx(aCt,{contactId:s})})]})]}),e.jsx(Vc,{}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"notes",children:"Notes"}),e.jsx(Rs,{id:"notes",value:Z.notes||"",onChange:Hs=>X({...Z,notes:Hs.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:A.isPending,children:[A.isPending?e.jsx(Ct,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(ma,{className:"mr-1 h-4 w-4"}),"Save Changes"]})]})]})]})}),e.jsx(Qt,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between gap-2 pb-3",children:[e.jsx(Et,{className:"text-base",children:"Activity Log"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>te(!0),children:[e.jsx(cn,{className:"mr-1 h-3.5 w-3.5"})," Log Action"]})]}),e.jsx(Le,{children:jt.length>0?e.jsx("div",{className:"space-y-4",children:jt.map(Hs=>{var Br;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:Hs.color},children:Hs.type==="popby"?e.jsx(dl,{className:"h-4 w-4"}):(Br=Hs.name)==null?void 0:Br.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:Hs.name}),Hs.videoId&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>Fe(Hs.videoId),children:[e.jsx(Ou,{className:"mr-1 h-3 w-3"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Js(new Date(Hs.completed_at),"MMM d, yyyy h:mm a")}),Hs.notes&&!Hs.videoId&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:Hs.notes})]})]},Hs.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:[y&&y.length>0&&e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(no,{className:"h-4 w-4 text-primary"}),"Video Replies"]})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-4",children:y.map(Hs=>{var Br,Ur;return e.jsxs("div",{className:"flex items-start gap-3 border-b pb-3 last:border-0",children:[(Br=Hs.video)!=null&&Br.thumbnail_url?e.jsx("img",{src:Hs.video.thumbnail_url,alt:Hs.video.title||"Video",className:"h-12 w-16 cursor-pointer rounded object-cover transition-opacity hover:opacity-80",onClick:()=>Fe(Hs.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(Hs.video_id),children:e.jsx(fa,{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: ",((Ur=Hs.video)==null?void 0:Ur.title)||"Untitled Video"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Js(new Date(Hs.created_at),"MMM d, yyyy h:mm a")}),Hs.message&&e.jsxs("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:['"',Hs.message,'"']})]})]},Hs.id)})})})]}),gt&>.length>0&&e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(Zr,{className:"h-4 w-4 text-sky-500"}),"Sent Emails"]})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-3",children:gt.map(Hs=>e.jsxs(Os,{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(pn,{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:Hs.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",Hs.to_email," · ",Js(new Date(Hs.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(Fs,{className:"flex max-h-[85vh] max-w-2xl flex-col",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5 text-sky-500"}),Hs.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",Hs.to_email," · ",Js(new Date(Hs.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:Hs.body,className:"h-[400px] w-full border-0",sandbox:"",title:`Email: ${Hs.subject}`})})]})]},Hs.id))})})]}),e.jsx(tUn,{contactId:s})]})]})}),e.jsx(Qt,{value:"marketing",className:"mt-4",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-2",children:[e.jsx(Y$n,{contactId:s,contactName:h.first_name}),e.jsx(G$n,{contactId:s}),n&&e.jsxs(e.Fragment,{children:[e.jsx(W$n,{contactId:s,contactName:h.first_name}),e.jsx(K$n,{contactId:s,contactName:h.first_name})]}),e.jsx(Q$n,{contactId:s})]})}),t&&e.jsx(Qt,{value:"property-intel",className:"mt-4",children:e.jsx(pUn,{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(no,{className:"mr-1 h-4 w-4"})," Text"]}),e.jsxs($,{className:"flex-1",onClick:()=>te(!0),children:[e.jsx(cn,{className:"mr-1 h-4 w-4"})," Log"]})]}),e.jsx(Os,{open:re,onOpenChange:te,children:e.jsxs(Fs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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(Hs=>Hs.active).map(Hs=>e.jsxs("button",{onClick:()=>ce(Hs.id),className:Pt("rounded-lg border p-3 text-left transition-all",J===Hs.id?"border-primary bg-primary/10":"hover:bg-accent"),children:[e.jsx("div",{className:"font-medium",children:Hs.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Hs.description})]},Hs.id))}),zt&&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:Hs=>ke(Hs.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(Gd,{children:[e.jsx(Wd,{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(Ea,{className:"mr-2 h-4 w-4"}),ue?Js(ue,"PPP"):"Today (default)"]})}),e.jsx(Dd,{className:"w-auto p-0",align:"start",children:e.jsx(A2,{mode:"single",selected:ue,onSelect:be,disabled:Hs=>Hs>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:ve,onChange:Hs=>fe(Hs.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs($,{onClick:vs,disabled:!J||zt&&!Ee.trim()||I.isPending,className:"w-full",children:[e.jsx(ma,{className:"mr-1 h-4 w-4"}),"Complete Action"]})]})]})}),e.jsx(Os,{open:!!Ie,onOpenChange:Hs=>!Hs&&Fe(null),children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx($s,{children:"Video Preview"})}),Ie&&e.jsx(gUn,{videoId:Ie})]})})]})}),G&&h&&e.jsx(w$n,{open:W,onOpenChange:V,contactId:h.id,contactName:`${h.first_name} ${h.last_name||""}`.trim(),hasEmail:!!h.email}),Qe&&h&&Se&&e.jsx(Nk,{open:Ne,onOpenChange:Be,contact:{id:h.id,first_name:h.first_name,last_name:h.last_name,email:Se.email},gmailEmail:Ve}),h&&h.email&&e.jsx(E$n,{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 _Un({rangeDays:s}){const{user:t}=_s(),n=Zt(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!1),{data:d=[],isLoading:u}=st({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 v=new Date(Date.now()-s*864e5).toISOString();f=f.gte("created_at",v)}const{data:g,error:x}=await f;if(x)throw x;return g||[]}}),{data:h}=st({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){ne.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:v,error:y}=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(y)throw y;const b=f.map(S=>({campaign_id:v.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,v=g>0?f.click_count/g*100:0,y=f.sent_at?ck(new Date,new Date(f.sent_at)):0,b=f.status==="sent"&&y>=3&&g>0&&f.open_counta(f.id),children:[e.jsx(Ta,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),b&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>l(f),children:[e.jsx(Wz,{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(cue,{icon:e.jsx(Zr,{className:"h-3.5 w-3.5"}),label:"Sent",value:g,sub:`of ${f.total_recipients}`}),e.jsx(cue,{icon:e.jsx(Ta,{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(cue,{icon:e.jsx(Pm,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:f.click_count,sub:`${v.toFixed(1)}%`,children:e.jsx(Yi,{value:v,className:"h-1 mt-1"})}),e.jsx(cue,{icon:e.jsx(WI,{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(Vy,{open:!!r,onOpenChange:f=>!f&&a(null),children:e.jsxs(uy,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(I0,{children:e.jsx(L0,{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($e,{variant:"default",className:"text-xs",children:Js(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($e,{variant:"default",className:"text-xs bg-purple-600",children:Js(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($e,{variant:"outline",className:"text-xs",children:"sent"}),f.status==="pending"&&e.jsx($e,{variant:"secondary",className:"text-xs",children:"queued"}),f.status==="failed"&&e.jsx($e,{variant:"destructive",className:"text-xs",title:f.error_message||"",children:"failed"}),f.status==="suppressed"&&e.jsx($e,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},f.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(fc,{open:!!i,onOpenChange:f=>!f&&l(null),children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Resend to non-openers?"}),e.jsxs(ic,{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(rc,{children:[e.jsx(oc,{disabled:o,children:"Cancel"}),e.jsx(Yl,{onClick:m,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Wz,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function cue({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 cne(){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 wUn(){const{user:s}=_s(),t=Zn(),n=Zt(),{data:r=[],isLoading:a}=st({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 cne(),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=mt({mutationFn:d=>i("cancel",d),onSuccess:()=>{ne.success("Schedule cancelled — saved as draft"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ne.error(d.message)}),o=mt({mutationFn:d=>i("delete",d),onSuccess:()=>{ne.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ne.error(d.message)}),c=mt({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:()=>{ne.success("Send time updated"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ne.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(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ca,{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(jUn,{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 jUn({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 ne.error("Pick a date");const g=new Date(`${Js(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(g).getTime()gm(g.target.value)})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:f,disabled:i,children:[i&&e.jsx(Ct,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(ju,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Cancel this scheduled send?"}),e.jsxs(ic,{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(rc,{children:[e.jsx(oc,{children:"Keep scheduled"}),e.jsx(Yl,{onClick:n,children:"Cancel send"})]})]})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Delete this scheduled email?"}),e.jsx(ic,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Keep"}),e.jsx(Yl,{onClick:r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}function NUn({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 due({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 kUn({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(NUn,{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(due,{icon:e.jsx(Vr,{className:"h-3.5 w-3.5"}),label:"Delivered",value:s.toLocaleString(),hint:"All sends completed"}),e.jsx(due,{icon:e.jsx(Ta,{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(due,{icon:e.jsx(Pm,{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(due,{icon:e.jsx(ca,{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 bCt=["Gmail","Mass Email","Campaign","Client Portal Invite","Card Studio"],SUn={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 CUn(){const{user:s}=_s(),[t,n]=Nc(),{data:r=[],isLoading:a}=VQt(),[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}=Gy(),{data:v=0}=st({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 y=j.useMemo(()=>Array.from(new Set(r.map(I=>I.contact_id).filter(Boolean))),[r]),{data:b}=st({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,y.length],enabled:y.length>0,queryFn:async()=>{const{data:I}=await q.from("innercircle_contacts").select("id, first_name, last_name").in("id",y),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]),A=d==="all"?"All time":`Last ${d} days`,E=bCt.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(Zr,{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(Zr,{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(ca,{className:"h-3.5 w-3.5"})," Scheduled",v>0&&e.jsx($e,{variant:"secondary",className:"ml-0.5 h-5 min-w-5 px-1.5 text-xs",children:v})]})]}),e.jsxs($,{onClick:()=>m(!0),className:"rounded-full",children:[e.jsx(pn,{className:"h-4 w-4 mr-2"})," Send Email"]})]})]}),e.jsxs(pa,{value:f,onValueChange:I=>g(I),className:"space-y-5",children:[e.jsxs(Qt,{value:"sent",className:"space-y-5 mt-0",children:[e.jsx(kUn,{total:w.length,opened:S.opened,clicked:S.clicked,trackable:S.trackable,scheduled:v,rangeLabel:A,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"}),bCt.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(XS,{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(_Un,{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(je,{className:"rounded-2xl",children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(pn,{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(je,{className:"rounded-2xl overflow-hidden",children:e.jsx(Le,{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(vk,{children:e.jsxs(ry,{children:[e.jsxs(ay,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(XS,{className:"h-3 w-3"})]}),e.jsx(vx,{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:Js(new Date(I.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx($e,{variant:"outline",className:SUn[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(br,{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($e,{variant:"outline",className:"bg-slate-50 text-slate-700 border-slate-200 gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"})," Delivered"]}),I.opened_at&&e.jsxs($e,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"})," Opened"]}),I.clicked_at&&e.jsxs($e,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(Pm,{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(Qt,{value:"scheduled",className:"mt-0",children:e.jsx(wUn,{})})]}),e.jsx(Nk,{open:h,onOpenChange:m,gmailEmail:x})]})})}const _Ct={Crown:Og,FileText:Qr,Users:Yn,Globe:cl,Star:ei,Phone:Da,MessageSquare:no,PenTool:PE,Video:fa,Gift:dl},uue=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function AUn(){var gt,es;const s=Zn(),{user:t}=_s(),{data:n}=Uw(),{data:r}=xHs(),{data:a}=NHs(),{data:i}=bUt(),{data:l}=Jae(),{data:o}=gHs(),c=kHs(),d=yHs(),u=bHs(),h=_Hs(),m=wHs(),f=jHs(),g=vHs(),[x,v]=j.useState(null),[y,b]=j.useState(!1),[w,S]=j.useState(null),[A,E]=j.useState(""),[I,P]=j.useState(""),[R,D]=j.useState([]),[O,U]=j.useState(null),[W,V]=j.useState(null),[G,Z]=j.useState(null),[X,ae]=j.useState(!1),[le,re]=j.useState(""),[te,J]=j.useState(""),[ce,ve]=j.useState(""),[fe,ue]=j.useState(""),be=(Ht,as)=>a==null?void 0:a.some(bs=>bs.plan_id===Ht&&bs.relationship_type_id===as&&bs.active),Ee=Ht=>a==null?void 0:a.find(as=>as.relationship_type_id===Ht&&as.active),ke=async(Ht,as)=>{const bs=be(Ht,as);await c.mutateAsync({planId:Ht,relationshipTypeId:as,active:!bs})},Ie=(r==null?void 0:r.filter(Ht=>Ht.active&&!Ht.owner_user_id))||[],Fe=(r==null?void 0:r.filter(Ht=>Ht.owner_user_id===(t==null?void 0:t.id)))||[],Ne=n==null?void 0:n.find(Ht=>Ht.id===x),Be=x?Ee(x):null,Se=r==null?void 0:r.find(Ht=>Ht.id===(Be==null?void 0:Be.plan_id)),Ae=async()=>{if(!A.trim())return;const Ht=await d.mutateAsync({name:A,description:I});Ht&&R.length>0&&await m.mutateAsync({planId:Ht.id,items:R}),Ve()},Ce=async()=>{!A.trim()||!w||(await u.mutateAsync({id:w,name:A,description:I}),await m.mutateAsync({planId:w,items:R}),Ve())},qe=Ht=>{var as;S(Ht.id),E(Ht.name),P(Ht.description||""),D(((as=Ht.items)==null?void 0:as.map(bs=>({month_number:bs.month_number,action_type_id:bs.action_type_id,default_script_id:bs.default_script_id||void 0,notes:bs.notes||void 0})))||[]),b(!0)},ze=async(Ht,as)=>{if(Ht.owner_user_id===(t==null?void 0:t.id)){qe(Ht);return}try{const bs=await g.mutateAsync({sourcePlanId:Ht.id,newName:`${Ht.name} (My Copy)`});if(!bs)return;await c.mutateAsync({planId:Ht.id,relationshipTypeId:as,active:!1}),await c.mutateAsync({planId:bs.id,relationshipTypeId:as,active:!0}),S(bs.id),E(bs.name),P(bs.description||""),D((Ht.items||[]).map(Ut=>({month_number:Ut.month_number,action_type_id:Ut.action_type_id,default_script_id:Ut.default_script_id||void 0,notes:Ut.notes||void 0}))),b(!0)}catch{}},Ve=()=>{b(!1),S(null),E(""),P(""),D([])},ht=(Ht,as)=>{V(as)},Qe=(Ht,as,bs)=>{D(Ut=>[...Ut.filter(is=>is.month_number!==Ht),{month_number:Ht,action_type_id:as,default_script_id:bs}]),U(null),V(null)},at=Ht=>{D(as=>as.filter(bs=>bs.month_number!==Ht))},rt=async()=>{if(!le.trim()||!te.trim()||!W)return;const Ht=await f.mutateAsync({actionTypeId:W,title:le,scriptBody:te,emailSubject:ce||void 0,tone:fe||void 0});Ht&&O!==null&&Qe(O,W,Ht.id),ae(!1),re(""),J(""),ve(""),ue("")},Ke=W?o==null?void 0:o.filter(Ht=>Ht.action_type_id===W&&Ht.active):[],Je=Ht=>_Ct[Ht||"Phone"]||Da,ft=Ht=>_Ct[Ht||"Users"]||Yn;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(kd,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs($,{onClick:()=>b(!0),className:"w-full sm:w-auto",children:[e.jsx(cn,{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(Ht=>Ht.active).map(Ht=>{const as=ft(Ht.icon),bs=(i==null?void 0:i[Ht.id])||0,Ut=Ee(Ht.id),Ft=r==null?void 0:r.find(jt=>jt.id===(Ut==null?void 0:Ut.plan_id)),is=x===Ht.id;return e.jsxs("button",{onClick:()=>v(Ht.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${is?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(as,{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:Ht.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[bs," contacts"]})]}),Ft?e.jsxs($e,{variant:"secondary",className:"text-xs",children:[e.jsx(Wl,{className:"h-3 w-3 mr-1"}),Ft.name.split(" ")[0]]}):e.jsx($e,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},Ht.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:x&&Ne?e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[(()=>{const Ht=ft(Ne.icon);return e.jsx(Ht,{className:"h-5 w-5"})})(),Ne.name," Touchpoint Plan"]}),e.jsxs(Vn,{children:["Choose a plan for your ",Ne.name," contacts"]})]}),e.jsxs(Le,{className:"space-y-6",children:[Se&&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(Wl,{className:"h-4 w-4 text-green-500"}),"Currently using: ",Se.name]}),Se.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Se.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:g.isPending||c.isPending,onClick:()=>ze(Se,x),children:[e.jsx(SN,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>ke(Se.id,x),children:"Disable"})]})]}),Se.items&&Se.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(Ea,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:uue.map((Ht,as)=>{var is,jt;const bs=((is=Se.items)==null?void 0:is.filter(zs=>zs.month_number===as+1))||[],Ut=(jt=bs[0])==null?void 0:jt.action_type,Ft=Ut?Je(Ut.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${bs.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:Ht}),Ft&&e.jsx(Ft,{className:"h-4 w-4 mx-auto mt-1",style:{color:(Ut==null?void 0:Ut.color)||"#3B82F6"}})]},as)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:Se?"Switch to a Different Plan":"Choose a Plan"}),Ie.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"}),Ie.map(Ht=>{var bs;const as=(Se==null?void 0:Se.id)===Ht.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${as?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ht.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((bs=Ht.items)==null?void 0:bs.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>Z(Ht.id),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:g.isPending,onClick:()=>{const Ut=`${Ht.name} (Copy)`;g.mutate({sourcePlanId:Ht.id,newName:Ut})},children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:as?"outline":"default",disabled:as||c.isPending,onClick:()=>ke(Ht.id,x),children:as?"Active":"Use This"})]})]},Ht.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(Ht=>{var bs;const as=(Se==null?void 0:Se.id)===Ht.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${as?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ht.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((bs=Ht.items)==null?void 0:bs.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>Z(Ht.id),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>qe(Ht),children:e.jsx(SN,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(Ht.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})}),e.jsx($,{size:"sm",variant:as?"outline":"default",disabled:as||c.isPending,onClick:()=>ke(Ht.id,x),children:as?"Active":"Use This"})]})]},Ht.id)})]}),Ie.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(je,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Ea,{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(je,{className:"bg-muted/50",children:e.jsx(Le,{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(Os,{open:y,onOpenChange:Ht=>{Ht?b(!0):Ve()},children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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:A,onChange:Ht=>E(Ht.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:Ht=>P(Ht.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:uue.map((Ht,as)=>{const bs=as+1,Ut=R.find(jt=>jt.month_number===bs),Ft=Ut?l==null?void 0:l.find(jt=>jt.id===Ut.action_type_id):null,is=Ft?Je(Ft.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>U(O===bs?null:bs),className:` w-full p-3 rounded-lg border text-center transition-all ${Ut?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${O===bs?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:Ht}),is?e.jsx(is,{className:"h-5 w-5 mx-auto mt-1",style:{color:(Ft==null?void 0:Ft.color)||"#3B82F6"}}):e.jsx(cn,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),Ut&&e.jsx("button",{type:"button",onClick:jt=>{jt.stopPropagation(),at(bs)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(mr,{className:"h-3 w-3"})})]},as)})}),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 ",uue[O-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(Ht=>Ht.active).map(Ht=>{const as=Je(Ht.icon);return e.jsxs("button",{type:"button",onClick:()=>ht(O,Ht.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(as,{className:"h-4 w-4",style:{color:Ht.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:Ht.name})]},Ht.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(kd,{className:"h-4 w-4 mr-1"})," Back"]})]}),e.jsxs("div",{className:"space-y-2 max-h-[300px] overflow-y-auto pr-1",children:[e.jsx("button",{type:"button",onClick:()=>Qe(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(Ht=>e.jsx("button",{type:"button",onClick:()=>Qe(O,W,Ht.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:Ht.title}),Ht.tone&&e.jsx($e,{variant:"secondary",className:"text-xs mt-1",children:Ht.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[Ht.script_body.substring(0,100),"..."]})]})},Ht.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(cn,{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(Nr,{children:[e.jsx($,{variant:"outline",onClick:Ve,children:"Cancel"}),e.jsxs($,{onClick:w?Ce:Ae,disabled:!A.trim()||d.isPending||u.isPending,children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),w?"Save Changes":"Create Plan"]})]})]})}),e.jsx(Os,{open:X,onOpenChange:ae,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx($s,{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:le,onChange:Ht=>re(Ht.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:fe,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"})]})]})]}),((es=(gt=l==null?void 0:l.find(Ht=>Ht.id===W))==null?void 0:gt.name)==null?void 0:es.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:Ht=>ve(Ht.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:Ht=>J(Ht.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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>ae(!1),children:"Cancel"}),e.jsxs($,{onClick:rt,disabled:!le.trim()||!te.trim()||f.isPending,children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(Os,{open:!!G,onOpenChange:Ht=>{Ht||Z(null)},children:e.jsx(Fs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const Ht=r==null?void 0:r.find(Ut=>Ut.id===G);if(!Ht)return null;const as=Ht.owner_user_id===(t==null?void 0:t.id),bs=[...Ht.items||[]].sort((Ut,Ft)=>Ut.month_number-Ft.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[Ht.name,!as&&e.jsx($e,{variant:"secondary",children:"Template"})]}),Ht.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Ht.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[bs.length," touchpoint",bs.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(Ut,Ft)=>Ft+1).map(Ut=>{const Ft=bs.find(yt=>yt.month_number===Ut),is=Ft?l==null?void 0:l.find(yt=>yt.id===Ft.action_type_id):null,jt=Ft!=null&&Ft.default_script_id?o==null?void 0:o.find(yt=>yt.id===Ft.default_script_id):null,zs=is?Je(is.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:uue[Ut-1]}),Ft&&is?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[zs&&e.jsx(zs,{className:"h-4 w-4",style:{color:is.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:is.name}),jt&&e.jsx($e,{variant:"outline",className:"text-xs",children:jt.title})]}),jt&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:jt.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"})]},Ut)})})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>Z(null),children:"Close"}),as?e.jsxs($,{onClick:()=>{const Ut=r==null?void 0:r.find(Ft=>Ft.id===G);Ut&&(Z(null),qe(Ut))},children:[e.jsx(SN,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs($,{disabled:g.isPending,onClick:()=>{g.mutate({sourcePlanId:Ht.id,newName:`${Ht.name} (Copy)`}),Z(null)},children:[e.jsx(Za,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const G9e="https://cma.relevelup.com";function KQt({open:s,onOpenChange:t,cma:n}){var Z;const{user:r}=_s(),{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,v]=j.useState(""),[y,b]=j.useState(!1),[w,S]=j.useState(null),[A,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(null);j.useEffect(()=>{!s||!r||(async()=>{var ve;const[X,ae,le,re,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(fe=>fe.email&&fe.email.includes("@"));l(J),S(ae.data||null),E(!!((ve=le.data)!=null&&ve.is_active)),P(!!(re.data&&re.data.length>0)),D(te.data||null);const ce=n.contact_id?J.find(fe=>fe.id===n.contact_id):null;ce&&(c(ce),m(ce.email))})()},[s,r,n.contact_id]),j.useEffect(()=>{var re;if(!s)return;const X=((re=n.subject)==null?void 0:re.address)||"your home",ae=((w==null?void 0:w.name)||"").split(" ")[0]||"your agent",le=(o==null?void 0:o.first_name)||"there";g(`Your home value report for ${X}`),v(`Hi ${le}, 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,(Z=n.subject)==null?void 0:Z.address]);const O=j.useMemo(()=>A?"Gmail (your inbox)":I?"Amazon SES":null,[A,I]),U=!!(h.trim()&&f.trim()&&x.trim()&&O&&!y),W=X=>{c(X),m(X.email||""),u(!1)},V=X=>{const ae=`${G9e}/${n.share_token}?e=${X}`,te=x.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(ve=>`

${ve.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:A?"gmail":"ses"}).select("id").single();if(ae)throw ae;const le=V(X.id);if(A){const{data:re,error:te}=await q.functions.invoke("gmail-send",{body:{to:h.trim(),subject:f.trim(),body:le}});if(te)throw te;if(!(re!=null&&re.success))throw new Error((re==null?void 0:re.error)||"Gmail send failed")}else if(I){const re=(R==null?void 0:R.display_name)||(w==null?void 0:w.name)||"ReLevelUp",te=`${re.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:`${re} <${te}>`,subject:f.trim(),body_html:le,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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{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(Gd,{open:d,onOpenChange:u,children:[e.jsx(Wd,{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(kw,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(Dd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(N2,{children:[e.jsx(k2,{placeholder:"Search contacts…"}),e.jsxs(S2,{children:[e.jsx(C2,{children:"No contacts with email found."}),e.jsx(Rw,{children:i.map(X=>e.jsxs(h1,{value:`${X.first_name} ${X.last_name||""} ${X.email}`,onSelect:()=>W(X),children:[e.jsx(ma,{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=>v(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(Ir,{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:`${G9e}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${G9e}/${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(Nr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:G,disabled:!U,children:[y?e.jsx(Ct,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Zr,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function EUn(s){const{user:t}=_s(),n=Zt(),{data:r}=st({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=mt({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]}),ne.success("Request sent — we'll reach out about upgrading your site.")},onError:l=>ne.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 TUn="free_luxury",MUn="free_beta";function YQt(s){const t=s==null?void 0:s.planTier;return t===TUn||t===MUn}const PUn={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 IUn({featureKey:s,siteId:t,bullets:n}){const r=PUn[s],{requestUpgrade:a,hasRequested:i,isSending:l}=EUn(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(jc,{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(wn,{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(ma,{className:"h-4 w-4 mr-2"})," Upgrade requested"]}):"Request this upgrade"})]})]})})}function LUn({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=R$n(),m=zQt(),{toast:f}=Bi(),[g,x]=j.useState([]),v=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"})}},y=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(Os,{open:t,onOpenChange:n,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(cn,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx($s,{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:v,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(Ct,{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 A;return e.jsxs("button",{onClick:()=>y(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 · ",((A=w.sqft)==null?void 0:A.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 RUn(){const{data:s,isLoading:t}=T$n(),n=L$n(),r=Zn(),{toast:a}=Bi(),[i,l]=j.useState(null),{isFreePlan:o,leadSite:c}=tg();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(Qr,{className:"w-7 h-7"})," CMAs"]}),e.jsx(IUn,{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(Qr,{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(LUn,{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(je,{className:"hover:shadow-md transition",children:e.jsxs(Le,{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($e,{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(Ir,{className:"w-4 h-4"})}),e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>l(d),children:[e.jsx(pn,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:async()=>{await mo("Delete this CMA?")&&n.mutate(d.id)},children:e.jsx(qn,{className:"w-4 h-4"})})]})]})},d.id)})}):e.jsx(je,{children:e.jsx(Le,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(KQt,{open:!!i,onOpenChange:d=>!d&&l(null),cma:i})]})})}function DUn(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 wCt(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 FUn({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;_u.accessToken=o;const u=new _u.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new _u.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:wCt(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(wCt(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(v=>v.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 _u.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new _u.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(m);const f=new _u.LngLatBounds;f.extend([d.lng,d.lat]),t.forEach((v,y)=>{const b=Number(v.latitude),w=Number(v.longitude);if(!Number.isFinite(b)||!Number.isFinite(w))return;const S=DUn(v.status),A=document.createElement("div");A.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: ${v.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(y)),A.appendChild(E);const I=v.soldPrice||v.price,P=new _u.Popup({offset:14}).setHTML(`
${v.address??""}
${v.status??""}`+(I?` · $${I.toLocaleString()}`:"")+"
"),R=new _u.Marker({element:A}).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 Q_=null;function ZQt(){if(Q_)return Q_;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return Q_={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},Q_;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 Q_={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},Q_;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(Q_={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},Q_):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(Q_={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},Q_):(Q_={canRunVirtualBg:!0,renderer:r},Q_)}catch{return Q_={canRunVirtualBg:!0},Q_}}const OUn=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function zUn({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(()=>ZQt()),h=!u.canRunVirtualBg,{data:m=[],refetch:f}=st({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:w}}=await q.auth.getUser();if(!w)return[];const{data:S,error:A}=await q.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return A?(console.error("Failed to load backgrounds:",A),[]):(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=[...OUn,...g],v=w=>w.type!==s.type?!1:w.type==="image"?w.imageUrl===s.imageUrl:!0,y=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 A="/video-backgrounds/",E=w.imageUrl.indexOf(A);if(E!==-1){const I=decodeURIComponent(w.imageUrl.slice(E+A.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(),ne.success("Background deleted")}catch(S){console.error("Delete background error:",S),ne.error((S==null?void 0:S.message)||"Failed to delete background")}finally{d(null)}}},b=async w=>{var A;const S=(A=w.target.files)==null?void 0:A[0];if(S){if(!S.type.startsWith("image/")){ne.error("Please select an image file");return}if(S.size>5*1024*1024){ne.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}),ne.success("Background uploaded!")}catch(E){console.error("Upload error:",E),ne.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(Al,{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(Ct,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),x.map((w,S)=>{const A=v(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",A?"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(Pz,{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(),y(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(Ct,{className:"h-3 w-3 animate-spin"}):e.jsx(mr,{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(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(cn,{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(_J,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var cW=typeof self<"u"?self:{};function XQt(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=cW,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 JQt(s){cW.setTimeout(()=>{throw s},0)}var EYe,qUn=XQt(610401301,!1),NCt=XQt(748402147,!0);function kCt(){var s=cW.navigator;return s&&(s=s.userAgent)?s:""}const SCt=cW.navigator;function aDe(s){return aDe[" "](s),s}EYe=SCt&&SCt.userAgentData||null,aDe[" "]=function(){};const eJt={};let vQ=null;function VUn(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 tJt(){if(!vQ){vQ={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));eJt[n]=r;for(let a=0;a0)&&(kCt().indexOf("Trident")!=-1||kCt().indexOf("MSIE")!=-1))&&typeof btoa=="function";const CCt=/[-_.]/g,GUn={"-":"+",_:"/",".":"="};function WUn(s){return GUn[s]||""}function nJt(s){if(!sJt)return VUn(s);s=CCt.test(s)?s.replace(CCt,WUn):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,aJt(s=Error(),"incident"),JQt(s))}}function FK(){return typeof BigInt=="function"}var OK=typeof Symbol=="function"&&typeof Symbol()=="symbol";function p3(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 ZUn=p3("jas",void 0,!0),ACt=p3(void 0,"0di"),nX=p3(void 0,"1oa"),y2=p3(void 0,Symbol()),XUn=p3(void 0,"0ub"),QUn=p3(void 0,"0ubs"),MYe=p3(void 0,"0ubsb"),JUn=p3(void 0,"0actk"),hW=p3("m_m","Pa",!0),ECt=p3();const iJt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},oJt=Object.defineProperties,ul=OK?ZUn:"Ga";var t9;const TCt=[];function Pie(s,t){OK||ul in s||oJt(s,iJt),s[ul]|=t}function R0(s,t){OK||ul in s||oJt(s,iJt),s[ul]=t}function Iie(s){return Pie(s,34),s}function dne(s){return Pie(s,8192),s}R0(TCt,7),t9=Object.freeze(TCt);var mW={};function E2(s,t){return t===void 0?s.h!==iB&&!!(2&(0|s.v[ul])):!!(2&t)&&s.h!==iB}const iB={};function yit(s,t){if(s!=null){if(typeof s=="string")s=s?new $4(s,dW):aB();else if(s.constructor!==$4)if(git(s))s=s.length?new $4(new Uint8Array(s),dW):aB();else{if(!t)throw Error();s=void 0}}return s}let MCt=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 eqn=Object.freeze({});function lJt(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"),PCt=iDe(s=>typeof s=="string"),sqn=iDe(s=>typeof s=="boolean"),oDe=typeof cW.BigInt=="function"&&typeof cW.BigInt(0)=="bigint";function v2(s){var t=s;if(PCt(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(tqn(t)&&!Number.isSafeInteger(t))throw Error(String(t));return oDe?BigInt(s):s=sqn(s)?s?"1":"0":PCt(s)?s.trim()||"0":String(s)}var PYe=iDe(s=>oDe?s>=rqn&&s<=iqn:s[0]==="-"?ICt(s,nqn):ICt(s,aqn));const nqn=Number.MIN_SAFE_INTEGER.toString(),rqn=oDe?BigInt(Number.MIN_SAFE_INTEGER):void 0,aqn=Number.MAX_SAFE_INTEGER.toString(),iqn=oDe?BigInt(Number.MAX_SAFE_INTEGER):void 0;function ICt(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;wg=t,Iy=(s-t)/4294967296>>>0}function fW(s){if(s<0){LCt(-s);const[t,n]=_it(wg,Iy);wg=t>>>0,Iy=n>>>0}else LCt(s)}function vit(s){const t=lqn||(lqn=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),Iy=0,wg=t.getUint32(0,!0)}function dJt(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:une(s,t)}function cqn(s,t){return v2(FK()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):une(s,t))}function uJt(s,t){return FK()?v2(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else FK()?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+RCt(n)+RCt(s));return n}function RCt(s){return s=String(s),"0000000".slice(s.length)+s}function bit(s,t){if(2147483648&t)if(FK())s=""+(BigInt(0|t)<>>0));else{const[n,r]=_it(s,t);s="-"+une(n,r)}else s=une(s,t);return s}function lDe(s){if(s.length<16)fW(Number(s));else if(FK())s=BigInt(s),wg=Number(s&BigInt(4294967295))>>>0,Iy=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");Iy=wg=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));Iy*=1e6,wg=1e6*wg+i,wg>=4294967296&&(Iy+=Math.trunc(wg/4294967296),Iy>>>=0,wg>>>=0)}if(t){const[r,a]=_it(wg,Iy);wg=r,Iy=a}}}function _it(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function lC(s){return Array.prototype.slice.call(s)}const Lie=typeof BigInt=="function"?BigInt.asIntN:void 0,dqn=typeof BigInt=="function"?BigInt.asUintN:void 0,oB=Number.isSafeInteger,cDe=Number.isFinite,pW=Math.trunc,uqn=v2(0);function bQ(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 y4(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function hne(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 hJt(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const hqn=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function Rie(s){switch(typeof s){case"bigint":return!0;case"number":return cDe(s);case"string":return hqn.test(s);default:return!1}}function BK(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return cDe(s)?0|s:void 0}function mJt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return cDe(s)?s>>>0:void 0}function fJt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(lDe(s),bit(wg,Iy))}function wit(s){if(s=pW(s),!oB(s)){fW(s);var t=wg,n=Iy;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=dJt(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function pJt(s){var t=pW(Number(s));return oB(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),fJt(s))}function gJt(s){var t=pW(Number(s));return oB(t)?v2(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),FK()?v2(Lie(64,BigInt(s))):v2(fJt(s)))}function xJt(s){return oB(s)?s=v2(wit(s)):(s=pW(s),oB(s)?s=String(s):(fW(s),s=bit(wg,Iy)),s=v2(s)),s}function XMe(s){const t=typeof s;return s==null?s:t==="bigint"?v2(Lie(64,s)):Rie(s)?t==="string"?gJt(s):xJt(s):void 0}function yJt(s){if(typeof s!="string")throw Error();return s}function Die(s){if(s!=null&&typeof s!="string")throw Error();return s}function _b(s){return s==null||typeof s=="string"?s:void 0}function jit(s,t,n,r){return s!=null&&s[hW]===mW?s:Array.isArray(s)?((r=(n=0|s[ul])|32&r|2&r)!==n&&R0(s,r),new t(s)):(n?2&r?((s=t[ACt])||(Iie((s=new t).v),s=t[ACt]=s),t=s):t=new t:t=void 0,t)}function mqn(s,t,n){if(t)e:{if(!Rie(t=s))throw TYe("int64");switch(typeof t){case"string":t=gJt(t);break e;case"bigint":t=v2(Lie(64,t));break e;default:t=xJt(t)}}else t=XMe(s);return(s=t)==null?n?uqn:void 0:s}const fqn={};let pqn=function(){try{return aDe(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),K9e=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 gqn=pqn?(Object.setPrototypeOf(K9e.prototype,Map.prototype),Object.defineProperties(K9e.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),K9e):class extends Map{constructor(){super()}};function DCt(s){return s}function Y9e(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var gT=class extends gqn{constructor(s,t,n=DCt,r=DCt){super(),this.J=0|s[ul],this.K=t,this.S=n,this.fa=this.K?xqn:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return Y9e(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 xqn(s,t,n,r,a,i){return s=jit(s,r,n,i),a&&(s=kit(s)),s}function yqn(s){return[s,this.get(s)]}let vqn;function FCt(){return vqn||(vqn=new gT(Iie([]),void 0,void 0,void 0,fqn))}function dDe(s){return y2?s[y2]:void 0}function QMe(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}gT.prototype.toJSON=void 0;var IYe=class{};const bqn={Ka:!0};function _qn(s,t){t<100||uW(QUn,1)}function uDe(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=y2;!a&&OK&&l&&(i=s[l])&&QMe(i,_qn),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[v]=lC(y)}),g.da=f.da,g}(s)),l}function wqn(s){return s[0]=mne(s[0]),s[1]=mne(s[1]),s}function mne(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return PYe(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[ul];return s.length===0&&1&t?void 0:uDe(s,t,mne)}if(s!=null&&s[hW]===mW)return vJt(s);if(s instanceof $4){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(sJt){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 gT?s=s.size!==0?s.V(wqn):void 0:void 0}return s}let jqn,Nqn;function vJt(s){return uDe(s=s.v,0|s[ul],mne)}function v7(s,t){return bJt(s,t[0],t[1])}function bJt(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[ul],NCt&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(NCt)throw Error("carr");uW(JUn,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&R0(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 R0(s,64|a|r),s}function kqn(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[ul];return s.length===0&&1&n?void 0:OCt(s,n,t)}if(s!=null&&s[hW]===mW)return zCt(s);if(s instanceof gT){if(2&(t=s.J))return s;if(!s.size)return;if(n=Iie(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 tf(s,t,n,r){qK(s),T0(s=s.v,0|s[ul],t,n,r)}function T0(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[ul]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function x8(){return eqn===void 0?2:4}function y8(s,t,n,r,a){let i=s.v,l=0|i[ul];r=E2(s,l)?1:r,a=!!a||r===3,r===2&&UK(s)&&(i=s.v,l=0|i[ul]);let o=(s=Cit(i,t))===t9?7:0|s[ul],c=Ait(o,l);var d=!(4&c);if(d){4&c&&(s=lC(s),o=0,c=_7(c,l),l=T0(i,l,t,s));let u=0,h=0;for(;u{const o=jit(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!E2(r)&&s9(s,t),r}function $h(s,t,n,r){let a=s.v,i=0|a[ul];if((t=SJt(a,i,t,n,r))==null)return t;if(i=0|a[ul],!E2(s,i)){const l=kit(t);l!==t&&(UK(s)&&(a=s.v,i=0|a[ul]),i=T0(a,i,n,t=l,r),s9(a,i))}return t}function CJt(s,t,n,r,a,i,l,o){var c=E2(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&UK(s)&&(n=0|(t=s.v)[ul]);var d=(s=Cit(t,a))===t9?7:0|s[ul],u=Ait(d,n);if(o=!(4&u)){var h=s,m=n;const f=!!(2&u);f&&(m|=2);let g=!f,x=!0,v=0,y=0;for(;v32)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 Rit(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function ePe(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],w7(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 Sqn(s){return RL(s)}function w7(s,t){if(s.g=t,t>s.l)throw Error()}function EJt(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 TJt(s,t){if(t==0)return aB();var n=EJt(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):oqn?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?aB():new $4(n,dW)}var BCt=[];function MJt(s,t,n,r){if(tPe.length){const a=tPe.pop();return a.o(r),a.g.init(s,t,n,r),a}return new Cqn(s,t,n,r)}function PJt(s){s.g.clear(),s.l=-1,s.h=-1,tPe.length<100&&tPe.push(s)}function IJt(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=Q4(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function N3e(s){switch(s.h){case 0:s.h!=0?N3e(s):Rit(s.g);break;case 1:w7(s=s.g,s.g+8);break;case 2:if(s.h!=2)N3e(s);else{var t=Q4(s.g);w7(s=s.g,s.g+t)}break;case 5:w7(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!IJt(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}N3e(s)}break;default:throw Error()}}function Fie(s,t,n){const r=s.g.l;var a=Q4(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 Dit(s){var t=Q4(s.g),n=EJt(s=s.g,t);if(s=s.h,BUn){var r,a=s;(r=W9e)||(r=W9e=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(hue===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),hue=!0}catch{hue=!1}}throw!hue&&(W9e=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?xR():(o=s[i++],l<194||(192&o)!=128?(i--,xR()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?xR():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,xR()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?xR():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,xR()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):xR(),n.length>=8192&&(c=jCt(c,n),n.length=0)}i=jCt(c,n)}return i}function LJt(s){const t=Q4(s.g);return TJt(s.g,t)}function mDe(s,t,n){var r=Q4(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let Aqn;function UCt(s){return s?/^-?\d+$/.test(s)?(lDe(s),new RYe(wg,Iy)):null:Eqn||(Eqn=new RYe(0,0))}var RYe=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let Eqn;function TV(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 HK(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function fDe(s,t){if(t>=0)HK(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function Fit(s){var t=wg;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 gW(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function Ak(s,t,n){HK(s.g,8*t+n)}function Oit(s,t){return Ak(s,t,2),t=s.g.end(),gW(s,t),t.push(s.h),t}function zit(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 pDe(s,t,n){Ak(s,t,2),HK(s.g,n.length),gW(s,s.g.end()),gW(s,n)}function sPe(s,t,n,r){n!=null&&(t=Oit(s,t),r(n,s),zit(s,t))}function g3(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var Bit=g3(),RJt=g3(),$it=g3(),Uit=g3(),qit=g3(),DJt=g3(),Tqn=g3(),gDe=g3(),FJt=g3(),OJt=g3();function x3(s,t,n){var r=s.v;y2&&y2 in r&&(r=r[y2])&&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 hl=class{constructor(s,t){this.v=bJt(s,t,void 0,2048)}toJSON(){return vJt(this)}j(){var a;var s=uVn,t=this.v,n=s.g,r=y2;if(OK&&r&&((a=t[r])==null?void 0:a[n])!=null&&uW(XUn,3),t=s.g,ECt&&y2&&ECt===void 0&&(r=(n=this.v)[y2])&&(r=r.da))try{r(n,t,bqn)}catch(i){JQt(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[ul];return Sit(this,s,t)?Nit(this,s,!0):new this.constructor($K(s,t,!1))}};hl.prototype[hW]=mW,hl.prototype.toString=function(){return this.v.toString()};var GK=class{constructor(s,t,n){this.g=s,this.h=t,s=Bit,this.l=!!s&&n===s||!1}};function xDe(s,t){return new GK(s,t,Bit)}function zJt(s,t,n,r,a){sPe(s,n,qJt(t,r),a)}const Mqn=xDe(function(s,t,n,r,a){return s.h===2&&(Fie(s,Mit(t,r,n),a),!0)},zJt),Pqn=xDe(function(s,t,n,r,a){return s.h===2&&(Fie(s,Mit(t,r,n),a),!0)},zJt);var yDe=Symbol(),vDe=Symbol(),DYe=Symbol(),qCt=Symbol(),VCt=Symbol();let BJt,$Jt;function n9(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 jqn||(jqn=[0,void 0,!0]);case"number":return h>0?void 0:h===0?Nqn||(Nqn=[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,BJt??(BJt=i),$Jt??($Jt=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 Hit(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=n9(vDe,Vit,Hit,r).T),l||(l=Git(r)),a)}function Git(s){let t=s[DYe];if(t!=null)return t;const n=n9(vDe,Vit,Hit,s);return t=n.ma?(r,a)=>BJt(r,a,n):(r,a)=>{for(;IJt(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=Lqn(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,N3e(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=TJt(o.g,c);l=void 0,o=r,c&&((l=o[y2]??(o[y2]=new IYe))[i]??(l[i]=[])).push(c)}}return(r=dDe(r))&&(r.da=n.qa[VCt]),!0},s[DYe]=t,s[VCt]=Iqn.bind(s),t}function Iqn(s,t,n,r){var a=this[vDe];const i=this[DYe],l=v7(void 0,a.T),o=dDe(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=MJt(f);try{c=!0,i(l,u)}finally{PJt(u)}}else r==null||r(s,h,m)},t==null)QMe(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[ul];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=zK(u),m=(f,g)=>{if(xT(s,f,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}g!=null&&(u=T0(s,u,f,g,h)),delete o[f]};t==null?lJt(l,0|l[ul],(f,g)=>{m(f,g)}):m(t,xT(l,t,h))}}}}function Lqn(s){const t=(s=UJt(s))[0].g;if(s=s[1]){const n=Git(s),r=n9(vDe,Vit,Hit,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function bDe(s,t,n){s[t]=n.h}function _De(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=n9(yDe,bDe,_De,r).T),a||(a=VJt(r)))}function VJt(s){let t=s[qCt];if(!t){const n=n9(yDe,bDe,_De,s);t=(r,a)=>HJt(r,a,n),s[qCt]=t}return t}function HJt(s,t,n){lJt(s,0|s[ul],(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=UJt(c))[0].h;if(c=c[1]){const u=VJt(c),h=n9(yDe,bDe,_De,c).T;c=l.ma?$Jt(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||uW(MYe,3)}}),(s=dDe(s))&&QMe(s,(r,a,i)=>{for(gW(t,t.g.end()),r=0;r{sPe(s,n,v7([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),TV(s.g,n.h,n.g);break;default:n=UCt(t),TV(s.g,n.h,n.g)}}function KJt(s,t,n){(t=BK(t))!=null&&t!=null&&(Ak(s,n,0),fDe(s.g,t))}function YJt(s,t,n){(t=hJt(t))!=null&&(Ak(s,n,0),s.g.g.push(t?1:0))}function ZJt(s,t,n){(t=_b(t))!=null&&pDe(s,n,QQt(t))}function XJt(s,t,n,r,a){sPe(s,n,qJt(t,r),a)}function QJt(s,t,n){(t=t==null||typeof t=="string"||t instanceof $4?t:void 0)!=null&&pDe(s,n,Iit(t,!0).buffer)}function JJt(s,t,n){(t=mJt(t))!=null&&t!=null&&(Ak(s,n,0),HK(s.g,t))}function ees(s,t,n){return(s.h===5||s.h===2)&&(t=VK(t,0|t[ul],n),s.h==2?mDe(s,ePe,t):t.push(ePe(s.g)),!0)}var Oy=T1(function(s,t,n){return s.h===5&&(M1(t,n,ePe(s.g)),!0)},GJt,gDe),Fqn=KK(ees,function(s,t,n){if((t=WK(y4,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"))||(lDe(r),r=une(wg,Iy))),r;if(a==="number")return(r=pW(r))>=0&&oB(r)||(fW(r),r=dJt(wg,Iy)),r}}(t),t!=null&&(typeof t=="string"&&$Ct(t),t!=null))switch(Ak(s,n,0),typeof t){case"number":s=s.g,fW(t),TV(s,wg,Iy);break;case"bigint":n=BigInt.asUintN(64,t),n=new LYe(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),TV(s.g,n.h,n.g);break;default:n=$Ct(t),TV(s.g,n.h,n.g)}},Tqn),k0=T1(function(s,t,n){return s.h===0&&(M1(t,n,RL(s.g)),!0)},KJt,Uit),Oie=KK(function(s,t,n){return(s.h===0||s.h===2)&&(t=VK(t,0|t[ul],n),s.h==2?mDe(s,RL,t):t.push(RL(s.g)),!0)},function(s,t,n){if((t=WK(BK,t))!=null&&t.length){n=Oit(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=MJt(n,void 0,void 0,i);try{const l=new s,o=l.v;Git(t)(o,n);var a=l}finally{PJt(n)}}return a}}function wDe(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}}}};HJt(this.v,t,n9(yDe,bDe,_De,s)),gW(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=WCt.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=Q9e)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function mue(s,...t){if(t.length===0)return KCt(s[0]);let n=s[0];for(let r=0;r({index:UN(r,1)??0??-1,score:Yx(r,2)??0,categoryName:_b(Tg(r,3))??""??"",displayName:_b(Tg(r,4))??""??""})),headIndex:t,headName:n}}function pVn(s){const t={classifications:yT(s,Zqn,1).map(n=>{var r;return tot(((r=$h(n,ces,4))==null?void 0:r.g())??[],UN(n,2)??0,_b(Tg(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(PYe(n)?n=Number(n):(n=Lie(64,n),n=PYe(n)?Number(n):String(n)),n):Rie(n)?typeof n=="number"?wit(n):pJt(n):void 0}(Tg(s,2,void 0,void 0,XMe))!=null&&(t.timestampMs=Des(Tg(s,2,void 0,void 0,XMe)??_Jt)),t}function Fes(s){var l,o;var t=y8(s,3,y4,x8()),n=y8(s,2,BK,x8()),r=y8(s,1,_b,x8()),a=y8(s,9,_b,x8());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function i5t(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 o5t(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 Bes(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 xl(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 l5t(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]=Bes(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 c5t(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 s5(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function kM(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)}}yU.forVisionTasks=function(s,t=!1){return pue("vision",s??mue``,t)},yU.forTextTasks=function(s,t=!1){return pue("text",s??mue``,t)},yU.forGenAiTasks=function(s,t=!1){return pue("genai",s??mue``,t)},yU.forAudioTasks=function(s,t=!1){return pue("audio",s??mue``,t)},yU.isSimdSupported=function(s=!1){return Oes(s)};async function xVn(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await o5t(i),!self.ModuleFactory||l&&(await o5t(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 t$e(s,t){const n=$h(s.baseOptions,nPe,1)||new nPe;typeof t=="string"?(tf(n,2,Die(t)),tf(n,1)):t instanceof Uint8Array&&(tf(n,1,yit(t,!1)),tf(n,2)),ec(s.baseOptions,0,1,n)}function d5t(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 SDe(s,t){s.B=new Hw,T2(s.B,2,"PassThroughCalculator"),Jp(s.B,"free_memory"),fh(s.B,"free_memory_unused_out"),$g(t,"free_memory"),Ek(t,s.B)}function xW(s,t){Jp(s.B,t),fh(s.B,t+"_unused_out")}function CDe(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var $Ye=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=$h(this.baseOptions,nPe,1))!=null&&a.g()||(i=$h(this.baseOptions,nPe,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=$h(d.baseOptions,t5t,3);if(!h){var m=h=new t5t,f=new YCt;Kee(m,4,k3e,f)}"delegate"in u&&(u.delegate==="GPU"?(u=h,m=new qqn,Kee(u,2,k3e,m)):(u=h,m=new YCt,Kee(u,4,k3e,m))),ec(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),t$e(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)t$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=>{t$e(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=Vqn(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,d5t(this)}finishProcessing(){this.g.finishProcessing(),d5t(this)}close(){this.B=void 0,this.g.closeGraph()}};function uL(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}$Ye.prototype.close=$Ye.prototype.close;class yVn{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 u5t(s,t,n){const r=s.g;if(n=uL(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 h5t(s,t){const n=s.g,r=uL(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=uL(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=uL(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 yVn(n,r,a,i)}function sot(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function vVn(s,t,n,r){return sot(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=h5t(s,!0)),n=s.u):(s.A||(s.A=h5t(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function $es(s,t,n){return sot(s,t),s=uL(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 Ues(s,t,n){sot(s,t),s.B||(s.B=uL(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 bVn(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var qes=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=uL(s.createProgram(),"Failed to create WebGL program"),this.X=u5t(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=u5t(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 uE(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 UYe(s){var t=uE(s,1);if(!t){if(t=uE(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=yW(s);var n=not(s);if(Ues(n,r,Ves(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 UYe(this)}N(){return Ves(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=yW(this),a=not(this);r.activeTexture(r.TEXTURE1),n=$es(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=Hes(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),Ues(a,r,n),vVn(a,r,!1,()=>{Ges(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),qYe(this)}),bVn(a),qYe(this)}}s.push(n)}return new J0(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&yW(this).deleteTexture(uE(this,2)),m5t=-1}};J0.prototype.close=J0.prototype.close,J0.prototype.clone=J0.prototype.clone,J0.prototype.getAsWebGLTexture=J0.prototype.N,J0.prototype.getAsFloat32Array=J0.prototype.ia,J0.prototype.getAsUint8Array=J0.prototype.ja,J0.prototype.hasWebGLTexture=J0.prototype.R,J0.prototype.hasFloat32Array=J0.prototype.ka,J0.prototype.hasUint8Array=J0.prototype.Fa;var m5t=250;function kC(...s){return s.map(([t,n])=>({start:t,end:n}))}const _Vn=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((f5t=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:zes()?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?'),xl(this,r||"input_audio",i=>{xl(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){s5(this,"__graph_config__",t=>{s(t)}),xl(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),xl(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){xl(this,t,r=>{const[a,i]=l5t(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){xl(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){xl(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){xl(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){xl(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){xl(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){xl(this,t,r=>{xl(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){xl(this,t,r=>{c5t(this,Object.keys(s),a=>{c5t(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){xl(this,n,a=>{xl(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){xl(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){xl(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){xl(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){xl(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){xl(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){xl(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){xl(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)xl(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){xl(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){xl(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){xl(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){xl(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){xl(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){xl(this,t,n=>{xl(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){xl(this,n,r=>{xl(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){xl(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){xl(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){xl(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){xl(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){xl(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){xl(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)xl(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){s5(this,s,t),xl(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){kM(this,s,t),xl(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){s5(this,s,t),xl(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){kM(this,s,t),xl(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){s5(this,s,t),xl(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){kM(this,s,t),xl(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){s5(this,s,t),xl(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){kM(this,s,t),xl(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){s5(this,s,t),xl(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){kM(this,s,t),xl(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){s5(this,s,t),xl(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){kM(this,s,t),xl(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){s5(this,s,t),xl(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){kM(this,s,t),xl(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?'),s5(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),xl(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 f5t{get ga(){return this.i}pa(s,t,n){xl(this,t,r=>{const[a,i]=l5t(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){s5(this,s,t),xl(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){kM(this,s,t),xl(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var f5t,SC=class extends _Vn{};async function Eh(s,t,n){return async function(r,a,i,l){return xVn(r,a,i,l)}(s,n.canvas??(zes()?void 0:document.createElement("canvas")),t,n)}function Wes(s,t,n,r){if(s.U){const i=new fes;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]=Bes(t);n=Yx(i,3)*o/l,a=Yx(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 CC(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'.");Wes(s,t,n,s.C+1)}function v3(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'.");Wes(s,t,n,r)}function vW(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 J0([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var M2=class extends $Ye{constructor(s,t,n,r){super(s),this.g=s,this.X=t,this.U=n,this.oa=r,this.P=new qes}l(s,t=!0){if("runningMode"in s&&tf(this.baseOptions,2,hne(!!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()}};M2.prototype.close=M2.prototype.close;var nN=class extends M2{constructor(s,t){super(new SC(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},ec(s=this.h=new NDe,0,1,t=new Ax),Cl(this.h,2,.5),Cl(this.h,3,.3)}get baseOptions(){return $h(this.h,Ax,1)}set baseOptions(s){ec(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:[]},CC(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},v3(this,s,n,t),this.j}m(){var s=new z2;$g(s,"image_in"),$g(s,"norm_rect_in"),tm(s,"detections");const t=new O2;x3(t,sVn,this.h);const n=new Hw;T2(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),Jp(n,"IMAGE:image_in"),Jp(n,"NORM_RECT:norm_rect_in"),fh(n,"DETECTIONS:detections"),n.o(t),Ek(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=ues(i),this.j.detections.push(Fes(r));qo(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};nN.prototype.detectForVideo=nN.prototype.G,nN.prototype.detect=nN.prototype.F,nN.prototype.setOptions=nN.prototype.o,nN.createFromModelPath=async function(s,t){return Eh(nN,s,{baseOptions:{modelAssetPath:t}})},nN.createFromModelBuffer=function(s,t){return Eh(nN,s,{baseOptions:{modelAssetBuffer:t}})},nN.createFromOptions=function(s,t){return Eh(nN,s,t)};var rot=kC([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]),aot=kC([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]),iot=kC([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),Kes=kC([474,475],[475,476],[476,477],[477,474]),oot=kC([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]),lot=kC([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),Yes=kC([469,470],[470,471],[471,472],[472,469]),cot=kC([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]),Zes=[...rot,...aot,...iot,...oot,...lot,...cot],Xes=kC([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 p5t(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var ax=class extends M2{constructor(s,t){super(new SC(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,ec(s=this.h=new ves,0,1,t=new Ax),this.A=new yes,ec(this.h,0,3,this.A),this.u=new NDe,ec(this.h,0,2,this.u),vT(this.u,4,1),Cl(this.u,2,.5),Cl(this.A,2,.5),Cl(this.h,4,.5)}get baseOptions(){return $h(this.h,Ax,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){return"numFaces"in s&&vT(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 p5t(this),CC(this,s,t),this.j}G(s,t,n){return p5t(this),v3(this,s,n,t),this.j}m(){var s=new z2;$g(s,"image_in"),$g(s,"norm_rect"),tm(s,"face_landmarks");const t=new O2;x3(t,rVn,this.h);const n=new Hw;T2(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),Jp(n,"IMAGE:image_in"),Jp(n,"NORM_RECT:norm_rect"),fh(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),Ek(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=zie(i),this.j.faceLandmarks.push(kDe(r));qo(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{qo(this,r)}),this.outputFaceBlendshapes&&(tm(s,"blendshapes"),fh(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=jDe(i),this.j.faceBlendshapes.push(tot(r.g()??[]));qo(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{qo(this,r)})),this.outputFacialTransformationMatrixes&&(tm(s,"face_geometry"),fh(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=$h(r=nVn(i),Kqn,2))&&this.j.facialTransformationMatrixes.push({rows:UN(r,1)??0??0,columns:UN(r,2)??0??0,data:y8(r,3,y4,x8()).slice()??[]});qo(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{qo(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};ax.prototype.detectForVideo=ax.prototype.G,ax.prototype.detect=ax.prototype.F,ax.prototype.setOptions=ax.prototype.o,ax.createFromModelPath=function(s,t){return Eh(ax,s,{baseOptions:{modelAssetPath:t}})},ax.createFromModelBuffer=function(s,t){return Eh(ax,s,{baseOptions:{modelAssetBuffer:t}})},ax.createFromOptions=function(s,t){return Eh(ax,s,t)},ax.FACE_LANDMARKS_LIPS=rot,ax.FACE_LANDMARKS_LEFT_EYE=aot,ax.FACE_LANDMARKS_LEFT_EYEBROW=iot,ax.FACE_LANDMARKS_LEFT_IRIS=Kes,ax.FACE_LANDMARKS_RIGHT_EYE=oot,ax.FACE_LANDMARKS_RIGHT_EYEBROW=lot,ax.FACE_LANDMARKS_RIGHT_IRIS=Yes,ax.FACE_LANDMARKS_FACE_OVAL=cot,ax.FACE_LANDMARKS_CONTOURS=Zes,ax.FACE_LANDMARKS_TESSELATION=Xes;var dot=kC([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 g5t(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function x5t(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 y5t(s,t=!0){const n=[];for(const a of s){var r=jDe(a);s=[];for(const i of r.g())r=t&&UN(i,1)!=null?UN(i,1)??0:-1,s.push({score:Yx(i,2)??0,index:r,categoryName:_b(Tg(i,3))??""??"",displayName:_b(Tg(i,4))??""??""});n.push(s)}return n}var mj=class extends M2{constructor(s,t){super(new SC(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],ec(s=this.j=new wes,0,1,t=new Ax),this.u=new Xit,ec(this.j,0,2,this.u),this.D=new Zit,ec(this.u,0,3,this.D),this.A=new _es,ec(this.u,0,2,this.A),this.h=new aVn,ec(this.j,0,3,this.h),Cl(this.A,2,.5),Cl(this.u,4,.5),Cl(this.D,2,.5)}get baseOptions(){return $h(this.j,Ax,1)}set baseOptions(s){ec(this.j,0,1,s)}o(s){var a,i,l,o;if(vT(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 O$,n=t,r=BYe(s.cannedGesturesClassifierOptions,(a=$h(this.h,O$,3))==null?void 0:a.l());ec(n,0,2,r),ec(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=$h(this.h,O$,3))==null||i.g());return s.customGesturesClassifierOptions?(ec(n=t=new O$,0,2,r=BYe(s.customGesturesClassifierOptions,(l=$h(this.h,O$,4))==null?void 0:l.l())),ec(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=$h(this.h,O$,4))==null||o.g()),this.l(s)}Ha(s,t){return g5t(this),CC(this,s,t),x5t(this)}Ia(s,t,n){return g5t(this),v3(this,s,n,t),x5t(this)}m(){var s=new z2;$g(s,"image_in"),$g(s,"norm_rect"),tm(s,"hand_gestures"),tm(s,"hand_landmarks"),tm(s,"world_hand_landmarks"),tm(s,"handedness");const t=new O2;x3(t,iVn,this.j);const n=new Hw;T2(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),Jp(n,"IMAGE:image_in"),Jp(n,"NORM_RECT:norm_rect"),fh(n,"HAND_GESTURES:hand_gestures"),fh(n,"LANDMARKS:hand_landmarks"),fh(n,"WORLD_LANDMARKS:world_hand_landmarks"),fh(n,"HANDEDNESS:handedness"),n.o(t),Ek(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=zie(i);const l=[];for(const o of yT(r,mes,1))l.push({x:Yx(o,1)??0,y:Yx(o,2)??0,z:Yx(o,3)??0,visibility:Yx(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=MV(i);const l=[];for(const o of yT(r,hes,1))l.push({x:Yx(o,1)??0,y:Yx(o,2)??0,z:Yx(o,3)??0,visibility:Yx(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(...y5t(r,!1)),qo(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{qo(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(...y5t(r)),qo(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function v5t(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}mj.prototype.recognizeForVideo=mj.prototype.Ia,mj.prototype.recognize=mj.prototype.Ha,mj.prototype.setOptions=mj.prototype.o,mj.createFromModelPath=function(s,t){return Eh(mj,s,{baseOptions:{modelAssetPath:t}})},mj.createFromModelBuffer=function(s,t){return Eh(mj,s,{baseOptions:{modelAssetBuffer:t}})},mj.createFromOptions=function(s,t){return Eh(mj,s,t)},mj.HAND_CONNECTIONS=dot;var fj=class extends M2{constructor(s,t){super(new SC(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],ec(s=this.h=new Xit,0,1,t=new Ax),this.u=new Zit,ec(this.h,0,3,this.u),this.j=new _es,ec(this.h,0,2,this.j),vT(this.j,3,1),Cl(this.j,2,.5),Cl(this.u,2,.5),Cl(this.h,4,.5)}get baseOptions(){return $h(this.h,Ax,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){return"numHands"in s&&vT(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=[],CC(this,s,t),v5t(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],v3(this,s,n,t),v5t(this)}m(){var s=new z2;$g(s,"image_in"),$g(s,"norm_rect"),tm(s,"hand_landmarks"),tm(s,"world_hand_landmarks"),tm(s,"handedness");const t=new O2;x3(t,oVn,this.h);const n=new Hw;T2(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),Jp(n,"IMAGE:image_in"),Jp(n,"NORM_RECT:norm_rect"),fh(n,"LANDMARKS:hand_landmarks"),fh(n,"WORLD_LANDMARKS:world_hand_landmarks"),fh(n,"HANDEDNESS:handedness"),n.o(t),Ek(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=zie(i),this.landmarks.push(kDe(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=MV(i),this.worldLandmarks.push(Zee(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=jDe(c);const d=[];for(const u of r.g())d.push({score:Yx(u,2)??0,index:UN(u,1)??0??-1,categoryName:_b(Tg(u,3))??""??"",displayName:_b(Tg(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)}};fj.prototype.detectForVideo=fj.prototype.G,fj.prototype.detect=fj.prototype.F,fj.prototype.setOptions=fj.prototype.o,fj.createFromModelPath=function(s,t){return Eh(fj,s,{baseOptions:{modelAssetPath:t}})},fj.createFromModelBuffer=function(s,t){return Eh(fj,s,{baseOptions:{modelAssetBuffer:t}})},fj.createFromOptions=function(s,t){return Eh(fj,s,t)},fj.HAND_CONNECTIONS=dot;var Qes=kC([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 b5t(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function _5t(s){try{if(!s.D)return s.h;s.D(s.h)}finally{CDe(s)}}function xue(s,t){s=zie(s),t.push(kDe(s))}var Lp=class extends M2{constructor(s,t){super(new SC(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,ec(s=this.j=new Ces,0,1,t=new Ax),this.I=new Zit,ec(this.j,0,2,this.I),this.W=new lVn,ec(this.j,0,3,this.W),this.u=new NDe,ec(this.j,0,4,this.u),this.O=new yes,ec(this.j,0,5,this.O),this.A=new kes,ec(this.j,0,6,this.A),this.M=new Ses,ec(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 $h(this.j,Ax,1)}set baseOptions(s){ec(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,b5t(this),CC(this,s,r),_5t(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,b5t(this),v3(this,s,a,t),_5t(this)}m(){var s=new z2;$g(s,"input_frames_image"),tm(s,"pose_landmarks"),tm(s,"pose_world_landmarks"),tm(s,"face_landmarks"),tm(s,"left_hand_landmarks"),tm(s,"left_hand_world_landmarks"),tm(s,"right_hand_landmarks"),tm(s,"right_hand_world_landmarks");const t=new O2,n=new HCt;T2(n,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))tf(a,2,uDe(i,0,mne));else{if(!(typeof i=="string"||i instanceof $4||git(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");pP(a,2,yit(i,!1),aB())}}(n,this.j.g());const r=new Hw;T2(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),Pit(r,8,HCt,n),Jp(r,"IMAGE:input_frames_image"),fh(r,"POSE_LANDMARKS:pose_landmarks"),fh(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),fh(r,"FACE_LANDMARKS:face_landmarks"),fh(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),fh(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),fh(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),fh(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),Ek(s,r),SDe(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{xue(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=MV(a),l.push(Zee(a)),qo(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{qo(this,a)}),this.outputPoseSegmentationMasks&&(fh(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),xW(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[vW(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)=>{xue(a,this.h.faceLandmarks),qo(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{qo(this,a)}),this.outputFaceBlendshapes&&(tm(s,"extra_blendshapes"),fh(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=jDe(a),l.push(tot(a.g()??[]))),qo(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{qo(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{xue(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=MV(a),l.push(Zee(a)),qo(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{qo(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{xue(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=MV(a),l.push(Zee(a)),qo(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{qo(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Lp.prototype.detectForVideo=Lp.prototype.G,Lp.prototype.detect=Lp.prototype.F,Lp.prototype.setOptions=Lp.prototype.o,Lp.createFromModelPath=function(s,t){return Eh(Lp,s,{baseOptions:{modelAssetPath:t}})},Lp.createFromModelBuffer=function(s,t){return Eh(Lp,s,{baseOptions:{modelAssetBuffer:t}})},Lp.createFromOptions=function(s,t){return Eh(Lp,s,t)},Lp.HAND_CONNECTIONS=dot,Lp.POSE_CONNECTIONS=Qes,Lp.FACE_LANDMARKS_LIPS=rot,Lp.FACE_LANDMARKS_LEFT_EYE=aot,Lp.FACE_LANDMARKS_LEFT_EYEBROW=iot,Lp.FACE_LANDMARKS_LEFT_IRIS=Kes,Lp.FACE_LANDMARKS_RIGHT_EYE=oot,Lp.FACE_LANDMARKS_RIGHT_EYEBROW=lot,Lp.FACE_LANDMARKS_RIGHT_IRIS=Yes,Lp.FACE_LANDMARKS_FACE_OVAL=cot,Lp.FACE_LANDMARKS_CONTOURS=Zes,Lp.FACE_LANDMARKS_TESSELATION=Xes;var rN=class extends M2{constructor(s,t){super(new SC(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},ec(s=this.h=new Aes,0,1,t=new Ax)}get baseOptions(){return $h(this.h,Ax,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){return ec(this.h,0,2,BYe(s,$h(this.h,Kit,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},CC(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},v3(this,s,n,t),this.j}m(){var s=new z2;$g(s,"input_image"),$g(s,"norm_rect"),tm(s,"classifications");const t=new O2;x3(t,cVn,this.h);const n=new Hw;T2(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),Jp(n,"IMAGE:input_image"),Jp(n,"NORM_RECT:norm_rect"),fh(n,"CLASSIFICATIONS:classifications"),n.o(t),Ek(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=pVn(Xqn(r)),qo(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};rN.prototype.classifyForVideo=rN.prototype.ta,rN.prototype.classify=rN.prototype.sa,rN.prototype.setOptions=rN.prototype.o,rN.createFromModelPath=function(s,t){return Eh(rN,s,{baseOptions:{modelAssetPath:t}})},rN.createFromModelBuffer=function(s,t){return Eh(rN,s,{baseOptions:{modelAssetBuffer:t}})},rN.createFromOptions=function(s,t){return Eh(rN,s,t)};var pj=class extends M2{constructor(s,t){super(new SC(s,t),"image_in","norm_rect",!0),this.h=new Ees,this.embeddings={embeddings:[]},ec(s=this.h,0,1,t=new Ax)}get baseOptions(){return $h(this.h,Ax,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){var t=this.h,n=$h(this.h,e5t,2);return n=n?n.clone():new e5t,s.l2Normalize!==void 0?tf(n,1,hne(s.l2Normalize)):"l2Normalize"in s&&tf(n,1),s.quantize!==void 0?tf(n,2,hne(s.quantize)):"quantize"in s&&tf(n,2),ec(t,0,2,n),this.l(s)}za(s,t){return CC(this,s,t),this.embeddings}Aa(s,t,n){return v3(this,s,n,t),this.embeddings}m(){var s=new z2;$g(s,"image_in"),$g(s,"norm_rect"),tm(s,"embeddings_out");const t=new O2;x3(t,dVn,this.h);const n=new Hw;T2(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),Jp(n,"IMAGE:image_in"),Jp(n,"NORM_RECT:norm_rect"),fh(n,"EMBEDDINGS:embeddings_out"),n.o(t),Ek(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=eVn(r),this.embeddings=function(i){return{embeddings:yT(i,Jqn,1).map(l=>{var d,u;const o={headIndex:UN(l,3)??0??-1,headName:_b(Tg(l,4))??""??""};var c=l.v;return SJt(c,0|c[ul],JCt,Z9e(l,1))!==void 0?(l=y8(l=$h(l,JCt,Z9e(l,1),void 0),1,y4,x8()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=$h(l,Qqn,Z9e(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:Des(Tg(i,2,void 0,void 0,XMe)??_Jt)}}(r),qo(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};pj.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=i5t(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=i5t(a5t(s.quantizedEmbedding),a5t(t.quantizedEmbedding))}return s},pj.prototype.embedForVideo=pj.prototype.Aa,pj.prototype.embed=pj.prototype.za,pj.prototype.setOptions=pj.prototype.o,pj.createFromModelPath=function(s,t){return Eh(pj,s,{baseOptions:{modelAssetPath:t}})},pj.createFromModelBuffer=function(s,t){return Eh(pj,s,{baseOptions:{modelAssetBuffer:t}})},pj.createFromOptions=function(s,t){return Eh(pj,s,t)};var VYe=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 wVn(s){var n,r;const t=function(a){return yT(a,Hw,1)}(s.ca()).filter(a=>(_b(Tg(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=$h(t[0],O2,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=_b(Tg(a,1))??""})}function w5t(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function j5t(s){try{const t=new VYe(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{CDe(s)}}VYe.prototype.close=VYe.prototype.close;var Q1=class extends M2{constructor(s,t){super(new SC(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new eot,this.A=new Tes,ec(this.h,0,3,this.A),ec(s=this.h,0,1,t=new Ax)}get baseOptions(){return $h(this.h,Ax,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?tf(this.h,2,Die(s.displayNamesLocale)):"displayNamesLocale"in s&&tf(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){wVn(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,w5t(this),CC(this,s,r),j5t(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,w5t(this),v3(this,s,a,t),j5t(this)}Da(){return this.u}m(){var s=new z2;$g(s,"image_in"),$g(s,"norm_rect");const t=new O2;x3(t,Pes,this.h);const n=new Hw;T2(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),Jp(n,"IMAGE:image_in"),Jp(n,"NORM_RECT:norm_rect"),n.o(t),Ek(s,n),SDe(this,s),this.outputConfidenceMasks&&(tm(s,"confidence_masks"),fh(n,"CONFIDENCE_MASKS:confidence_masks"),xW(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>vW(this,i,!0,!this.j)),qo(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],qo(this,r)})),this.outputCategoryMask&&(tm(s,"category_mask"),fh(n,"CATEGORY_MASK:category_mask"),xW(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=vW(this,r,!1,!this.j),qo(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,qo(this,r)})),tm(s,"quality_scores"),fh(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)}};Q1.prototype.getLabels=Q1.prototype.Da,Q1.prototype.segmentForVideo=Q1.prototype.La,Q1.prototype.segment=Q1.prototype.segment,Q1.prototype.setOptions=Q1.prototype.o,Q1.createFromModelPath=function(s,t){return Eh(Q1,s,{baseOptions:{modelAssetPath:t}})},Q1.createFromModelBuffer=function(s,t){return Eh(Q1,s,{baseOptions:{modelAssetBuffer:t}})},Q1.createFromOptions=function(s,t){return Eh(Q1,s,t)};var HYe=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()}};HYe.prototype.close=HYe.prototype.close;var n5=class extends M2{constructor(s,t){super(new SC(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new eot,this.u=new Tes,ec(this.h,0,3,this.u),ec(s=this.h,0,1,t=new Ax)}get baseOptions(){return $h(this.h,Ax,1)}set baseOptions(s){ec(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 Ies,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new e$e;pP(i,3,hne(!0),!1),pP(i,1,bQ(t.keypoint.x),0),pP(i,2,bQ(t.keypoint.y),0),Kee(r,1,zYe,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new hVn;for(i of t.scribble)pP(t=new e$e,3,hne(!0),!1),pP(t,1,bQ(i.x),0),pP(t,2,bQ(i.y),0),Pit(o,1,e$e,t);Kee(r,2,zYe,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),CC(this,s,a);e:{try{const o=new HYe(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{CDe(this)}l=void 0}return l}m(){var s=new z2;$g(s,"image_in"),$g(s,"roi_in"),$g(s,"norm_rect_in");const t=new O2;x3(t,Pes,this.h);const n=new Hw;T2(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),Jp(n,"IMAGE:image_in"),Jp(n,"ROI:roi_in"),Jp(n,"NORM_RECT:norm_rect_in"),n.o(t),Ek(s,n),SDe(this,s),this.outputConfidenceMasks&&(tm(s,"confidence_masks"),fh(n,"CONFIDENCE_MASKS:confidence_masks"),xW(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>vW(this,i,!0,!this.j)),qo(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],qo(this,r)})),this.outputCategoryMask&&(tm(s,"category_mask"),fh(n,"CATEGORY_MASK:category_mask"),xW(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=vW(this,r,!1,!this.j),qo(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,qo(this,r)})),tm(s,"quality_scores"),fh(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)}};n5.prototype.segment=n5.prototype.segment,n5.prototype.setOptions=n5.prototype.o,n5.createFromModelPath=function(s,t){return Eh(n5,s,{baseOptions:{modelAssetPath:t}})},n5.createFromModelBuffer=function(s,t){return Eh(n5,s,{baseOptions:{modelAssetBuffer:t}})},n5.createFromOptions=function(s,t){return Eh(n5,s,t)};var aN=class extends M2{constructor(s,t){super(new SC(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},ec(s=this.h=new Les,0,1,t=new Ax)}get baseOptions(){return $h(this.h,Ax,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?tf(this.h,2,Die(s.displayNamesLocale)):"displayNamesLocale"in s&&tf(this.h,2),s.maxResults!==void 0?vT(this.h,3,s.maxResults):"maxResults"in s&&tf(this.h,3),s.scoreThreshold!==void 0?Cl(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&tf(this.h,4),s.categoryAllowlist!==void 0?JMe(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&tf(this.h,5),s.categoryDenylist!==void 0?JMe(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&tf(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},CC(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},v3(this,s,n,t),this.j}m(){var s=new z2;$g(s,"input_frame_gpu"),$g(s,"norm_rect"),tm(s,"detections");const t=new O2;x3(t,mVn,this.h);const n=new Hw;T2(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),Jp(n,"IMAGE:input_frame_gpu"),Jp(n,"NORM_RECT:norm_rect"),fh(n,"DETECTIONS:detections"),n.o(t),Ek(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=ues(i),this.j.detections.push(Fes(r));qo(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};aN.prototype.detectForVideo=aN.prototype.G,aN.prototype.detect=aN.prototype.F,aN.prototype.setOptions=aN.prototype.o,aN.createFromModelPath=async function(s,t){return Eh(aN,s,{baseOptions:{modelAssetPath:t}})},aN.createFromModelBuffer=function(s,t){return Eh(aN,s,{baseOptions:{modelAssetBuffer:t}})},aN.createFromOptions=function(s,t){return Eh(aN,s,t)};var GYe=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 N5t(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function k5t(s){try{const t=new GYe(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{CDe(s)}}GYe.prototype.close=GYe.prototype.close;var gj=class extends M2{constructor(s,t){super(new SC(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,ec(s=this.h=new Res,0,1,t=new Ax),this.A=new Ses,ec(this.h,0,3,this.A),this.j=new kes,ec(this.h,0,2,this.j),vT(this.j,4,1),Cl(this.j,2,.5),Cl(this.A,2,.5),Cl(this.h,4,.5)}get baseOptions(){return $h(this.h,Ax,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){return"numPoses"in s&&vT(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,N5t(this),CC(this,s,r),k5t(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,N5t(this),v3(this,s,a,t),k5t(this)}m(){var s=new z2;$g(s,"image_in"),$g(s,"norm_rect"),tm(s,"normalized_landmarks"),tm(s,"world_landmarks"),tm(s,"segmentation_masks");const t=new O2;x3(t,fVn,this.h);const n=new Hw;T2(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),Jp(n,"IMAGE:image_in"),Jp(n,"NORM_RECT:norm_rect"),fh(n,"NORM_LANDMARKS:normalized_landmarks"),fh(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),Ek(s,n),SDe(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=zie(i),this.landmarks.push(kDe(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=MV(i),this.worldLandmarks.push(Zee(r));qo(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],qo(this,r)}),this.outputSegmentationMasks&&(fh(n,"SEGMENTATION_MASK:segmentation_masks"),xW(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>vW(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)}};gj.prototype.detectForVideo=gj.prototype.G,gj.prototype.detect=gj.prototype.F,gj.prototype.setOptions=gj.prototype.o,gj.createFromModelPath=function(s,t){return Eh(gj,s,{baseOptions:{modelAssetPath:t}})},gj.createFromModelBuffer=function(s,t){return Eh(gj,s,{baseOptions:{modelAssetBuffer:t}})},gj.createFromOptions=function(s,t){return Eh(gj,s,t)},gj.POSE_CONNECTIONS=Qes;let v8=null,_Q=null;async function jVn(){return v8||_Q||(_Q=(async()=>{const s=await yU.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return v8=await Q1.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}),v8})(),_Q)}function NVn(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 kVn(){v8&&(v8.close(),v8=null,_Q=null)}const SVn=1280,CVn=720;function AVn(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,v=null;const y=async()=>{u(!0),m(null);try{const w=await jVn();if(g)return;u(!1);const S=r.current;if(!S||(await new Promise(as=>{if(S.videoWidth>0)return as();S.onloadedmetadata=()=>as(),setTimeout(as,2e3)}),g))return;const A=S.videoWidth||640,E=S.videoHeight||480,I=Math.max(A,E),P=Math.min(A,E),R=Math.min(1,SVn/I,CVn/P),D=Math.max(2,Math.round(A*R/2)*2),O=Math.max(2,Math.round(E*R/2)*2),W=!ZQt().canRunVirtualBg,G=(W?192:256)/Math.max(D,O),Z=Math.max(2,Math.round(D*G)),X=Math.max(2,Math.round(O*G)),ae=W?90:55,le=W?24:30,re=n.current;if(!re)return;re.width=D,re.height=O;const te=re.getContext("2d",{alpha:!1}),J=document.createElement("canvas");J.width=D,J.height=O;const ce=J.getContext("2d"),ve=document.createElement("canvas");ve.width=Math.max(2,Math.round(D/2)),ve.height=Math.max(2,Math.round(O/2));const fe=ve.getContext("2d",{alpha:!1}),ue=document.createElement("canvas");ue.width=Z,ue.height=X;const be=ue.getContext("2d",{alpha:!1}),Ee=document.createElement("canvas");Ee.width=Z,Ee.height=X;const ke=Ee.getContext("2d"),Ie=ke.createImageData(Z,X),Fe=Ie.data;for(let as=0;asNe.addTrack(as)),g||c(Ne);const Se=new Float32Array(Z*X),Ae=new Float32Array(Z*X),Ce=new Float32Array(Z*X);let qe=!1,ze=!1;const Ve=2,ht=.4;let Qe=0;const at=(as,bs)=>{be.drawImage(as,0,0,Z,X);const Ft=w.segmentForVideo(ue,bs).confidenceMasks;if(!(!Ft||Ft.length===0)){Ae.fill(0);for(let is=1;is1?1:gs}}for(const is of Ft)is.close();if(NVn(Ae,Se,Z,X,Ve),qe)for(let is=0;is=1?255:zs*255|0}ke.putImageData(Ie,0,0),ze=!0}},rt=as=>{const bs=l.current;if(bs.type==="blur"){const Ut=Math.max(2,Math.round((bs.blurRadius??15)/2));fe.filter=`blur(${Ut}px)`,fe.drawImage(as,0,0,ve.width,ve.height),fe.filter="none",te.drawImage(ve,0,0,D,O)}else if(bs.type==="image"&&a.current){const Ut=a.current,Ft=Ut.width/Ut.height,is=D/O;let jt=0,zs=0,yt=Ut.width,gs=Ut.height;Ft>is?(yt=Ut.height*is,jt=(Ut.width-yt)/2):(gs=Ut.width/is,zs=(Ut.height-gs)/2),te.drawImage(Ut,jt,zs,yt,gs,0,0,D,O)}else te.fillStyle="#000",te.fillRect(0,0,D,O)},Ke=()=>{if(g||!r.current)return;const as=r.current;if(as.readyState<2){Ht(as);return}try{const bs=performance.now();bs-Qe>=ae&&(Qe=bs,at(as,bs)),ze?(rt(as),ce.globalCompositeOperation="source-over",ce.clearRect(0,0,D,O),ce.drawImage(as,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(as,0,0,D,O)}catch{try{te.drawImage(as,0,0,D,O)}catch{}}Ht(as)},Je=typeof S.requestVideoFrameCallback=="function",ft="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}}",gt=new Blob([ft],{type:"application/javascript"});v=URL.createObjectURL(gt),x=new Worker(v),x.onmessage=()=>{g||!document.hidden||Ke()};const es=()=>{x&&(document.hidden?x.postMessage({type:"start",fps:le}):(x.postMessage({type:"stop"}),Ht(r.current)))};document.addEventListener("visibilitychange",es);const Ht=as=>{g||document.hidden||(Je?as.requestVideoFrameCallback(()=>Ke()):i.current=requestAnimationFrame(Ke))};Ht(S),b=()=>{document.removeEventListener("visibilitychange",es)}}catch(w){console.error("[useVirtualBackground] init error:",w),g||(u(!1),m(w.message||"Failed to initialize virtual background"))}};let b=null;return y(),()=>{g=!0,i.current&&cancelAnimationFrame(i.current),b==null||b(),x&&(x.postMessage({type:"stop"}),x.terminate(),x=null),v&&URL.revokeObjectURL(v),c(null)}},[f,s]),j.useEffect(()=>()=>{kVn()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:f,error:h}}function DT({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),v=j.useRef(null),y=RK(),[b,w]=j.useState("camera"),S=j.useRef(null),A=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),[Z,X]=j.useState(!1),[ae,le]=j.useState(!1),[re,te]=j.useState(null),[J,ce]=j.useState(null),[ve,fe]=j.useState(0),[ue,be]=j.useState("user"),[Ee,ke]=j.useState(0),[Ie,Fe]=j.useState(!1),[Ne,Be]=j.useState(!0),[Se,Ae]=j.useState(null),[Ce,qe]=j.useState(!1),[ze,Ve]=j.useState(null),ht=j.useRef(null),[Qe,at]=j.useState(()=>{try{const Sn=localStorage.getItem("video-bg-config");if(Sn)return JSON.parse(Sn)}catch{}return{type:"none"}});j.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(Qe))}catch{}},[Qe]);const[rt,Ke]=j.useState([]),[Je,ft]=j.useState([]),[gt,es]=j.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[Ht,as]=j.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});j.useEffect(()=>{try{localStorage.setItem("video-mic-id",gt)}catch{}},[gt]),j.useEffect(()=>{try{localStorage.setItem("video-cam-id",Ht)}catch{}},[Ht]),j.useEffect(()=>{var Fn,bn,xs;if(!((Fn=navigator.mediaDevices)!=null&&Fn.enumerateDevices))return;const Sn=async()=>{try{const Tr=await navigator.mediaDevices.enumerateDevices();Ke(Tr.filter(Lr=>Lr.kind==="audioinput")),ft(Tr.filter(Lr=>Lr.kind==="videoinput"))}catch(Tr){console.warn("[VideoRecorder] enumerateDevices failed",Tr)}};return Sn(),(xs=(bn=navigator.mediaDevices).addEventListener)==null||xs.call(bn,"devicechange",Sn),()=>{var Tr,Lr;return(Lr=(Tr=navigator.mediaDevices).removeEventListener)==null?void 0:Lr.call(Tr,"devicechange",Sn)}},[V]);const{canvasRef:bs,compositedStream:Ut,isLoading:Ft,isActive:is}=AVn(u,Qe),jt=j.useRef(n);jt.current=n;const zs=j.useCallback(Sn=>{O(Sn)},[]),yt=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(Sn=>Sn.stop()),S.current=null),P.current&&(P.current.getTracks().forEach(Sn=>Sn.stop()),P.current=null),R.current&&(R.current.srcObject=null,R.current=null)},[]),Ss=j.useCallback(async()=>{var Sn;try{const Fn=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});S.current=Fn;let bn=null;try{bn=await navigator.mediaDevices.getUserMedia({video:Ht?{deviceId:{exact:Ht},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,...gt?{deviceId:{exact:gt}}:{}}}),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 Tr=Fn.getVideoTracks()[0],Lr=Tr.getSettings(),la=Lr.width||1920,Xn=Lr.height||1080,wr=document.createElement("canvas");wr.width=la,wr.height=Xn,A.current=wr;const Bn=wr.getContext("2d");let cr=null;bn&&(cr=document.createElement("video"),cr.srcObject=bn,cr.muted=!0,cr.playsInline=!0,cr.autoplay=!0,await cr.play(),R.current=cr);const Pa=document.createElement("video");Pa.srcObject=Fn,Pa.muted=!0,Pa.playsInline=!0,Pa.autoplay=!0,await Pa.play();const ii=()=>{if(Bn.drawImage(Pa,0,0,la,Xn),cr&&cr.readyState>=2){const Nl=Math.round(la*.2),Ho=Math.round(Nl*(cr.videoHeight/cr.videoWidth||.75)),ti=la-Nl-20,Yr=Xn-Ho-20,Eo=12;Bn.save(),Bn.beginPath(),Bn.moveTo(ti+Eo,Yr),Bn.lineTo(ti+Nl-Eo,Yr),Bn.quadraticCurveTo(ti+Nl,Yr,ti+Nl,Yr+Eo),Bn.lineTo(ti+Nl,Yr+Ho-Eo),Bn.quadraticCurveTo(ti+Nl,Yr+Ho,ti+Nl-Eo,Yr+Ho),Bn.lineTo(ti+Eo,Yr+Ho),Bn.quadraticCurveTo(ti,Yr+Ho,ti,Yr+Ho-Eo),Bn.lineTo(ti,Yr+Eo),Bn.quadraticCurveTo(ti,Yr,ti+Eo,Yr),Bn.closePath(),Bn.clip(),Bn.translate(ti+Nl,Yr),Bn.scale(-1,1),Bn.drawImage(cr,0,0,Nl,Ho),Bn.restore(),Bn.strokeStyle="rgba(255,255,255,0.6)",Bn.lineWidth=2,Bn.beginPath(),Bn.moveTo(ti+Eo,Yr),Bn.lineTo(ti+Nl-Eo,Yr),Bn.quadraticCurveTo(ti+Nl,Yr,ti+Nl,Yr+Eo),Bn.lineTo(ti+Nl,Yr+Ho-Eo),Bn.quadraticCurveTo(ti+Nl,Yr+Ho,ti+Nl-Eo,Yr+Ho),Bn.lineTo(ti+Eo,Yr+Ho),Bn.quadraticCurveTo(ti,Yr+Ho,ti,Yr+Ho-Eo),Bn.lineTo(ti,Yr+Eo),Bn.quadraticCurveTo(ti,Yr,ti+Eo,Yr),Bn.closePath(),Bn.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}}",Ln=new Blob([$i],{type:"application/javascript"}),xa=new Worker(URL.createObjectURL(Ln));I.current=xa,xa.onmessage=()=>ii(),xa.postMessage({type:"start",fps:30}),ii();const Ka=wr.captureStream(30),uo=[],Tc=Fn.getAudioTracks();Tc.length&&uo.push(...Tc),xs&&uo.push(...xs.getAudioTracks());const Fd=new MediaStream([...Ka.getVideoTracks(),...uo]);return P.current=Fd,Tr.onended=()=>{c.current&&c.current.state!=="inactive"&&c.current.stop(),gs()},Fd}catch(Fn){return console.error("[VideoRecorder] Screen capture error:",Fn),Fn.name!=="NotAllowedError"&&((Sn=jt.current)==null||Sn.call(jt,"Failed to start screen capture: "+(Fn.message||"Unknown error"))),null}},[gs]),Ds=j.useCallback(async()=>{var Fn,bn;W(!0),Ae(null);const Sn=y&&D;console.log("[VideoRecorder] initCamera start",{isMobile:y,usePortraitMode:D,shouldBePortrait:Sn,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(Bn=>Bn.stop()));const xs=y&&Sn?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},Tr=Ht?{...xs,deviceId:{exact:Ht}}:{...xs,facingMode:{ideal:ue}},Lr={echoCancellation:!0,noiseSuppression:!0,...gt?{deviceId:{exact:gt}}:{}};console.log("[VideoRecorder] requesting getUserMedia",Tr);const la=await navigator.mediaDevices.getUserMedia({video:Tr,audio:Lr});if(console.log("[VideoRecorder] getUserMedia success"),la.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");d.current=la,h(la),G(!0);const wr=la.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",wr.width,"x",wr.height),o.current){const Bn=o.current;Bn.srcObject=la,Bn.muted=!0,Bn.playsInline=!0,Bn.autoplay=!0,Bn.setAttribute("muted",""),Bn.setAttribute("playsinline",""),Bn.setAttribute("autoplay","");try{(Fn=Bn.load)==null||Fn.call(Bn)}catch(Pa){console.warn("[VideoRecorder] videoEl.load failed",Pa)}const cr=async()=>{try{return await Bn.play(),console.log("[VideoRecorder] preview play ok"),qe(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:Bn.readyState,videoWidth:Bn.videoWidth,videoHeight:Bn.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())},Ln=()=>{cr().finally($i)};Bn.onloadedmetadata=Ln,Bn.onloadeddata=Ln,setTimeout($i,1500)})}try{g.current=new AudioContext;const Bn=g.current.createMediaStreamSource(la);x.current=g.current.createAnalyser(),x.current.fftSize=256,Bn.connect(x.current);const cr=()=>{if(x.current){const Pa=new Uint8Array(x.current.frequencyBinCount);x.current.getByteFrequencyData(Pa);const ii=Pa.reduce(($i,Ln)=>$i+Ln)/Pa.length;ke(Math.min(100,ii/128*100))}v.current=requestAnimationFrame(cr)};cr()}catch(Bn){console.warn("Audio context not available:",Bn)}}catch(xs){console.error("Camera initialization error:",xs),G(!1);let Tr="Failed to access camera or microphone.";xs.name==="NotAllowedError"?Tr="Camera permission denied. Please allow camera access in your browser settings.":xs.name==="NotFoundError"?Tr="No camera found. Please connect a camera and try again.":xs.name==="NotReadableError"?Tr="Camera is in use by another application. Please close other apps using the camera.":xs.message&&(Tr=xs.message),Ae(Tr),(bn=jt.current)==null||bn.call(jt,Tr)}finally{W(!1)}},[ue,y,D,gt,Ht]);j.useEffect(()=>{yt.current!==D&&V&&!Z&&!J&&(yt.current=D,Ds())},[D,V,Z,J,Ds]),j.useEffect(()=>(Ds(),()=>{d.current&&d.current.getTracks().forEach(Sn=>Sn.stop()),f.current&&clearInterval(f.current),v.current&&cancelAnimationFrame(v.current),g.current&&g.current.close(),ht.current&&clearInterval(ht.current),J&&URL.revokeObjectURL(J),gs()}),[Ds,J]),j.useEffect(()=>{if(U||V!==!0||J)return;const Sn=d.current,Fn=o.current;!Sn||!Fn||is||(Fn.srcObject!==Sn&&(Fn.srcObject=Sn,Fn.muted=!0,Fn.playsInline=!0,Fn.autoplay=!0,Fn.setAttribute("muted",""),Fn.setAttribute("playsinline",""),Fn.setAttribute("autoplay","")),Fn.play().then(()=>qe(!1)).catch(bn=>{qe(!0),console.warn("Live preview play blocked on mount:",bn)}))},[V,U,J,is]),j.useEffect(()=>{r==null||r(Z)},[Z,r]);const Bt=j.useCallback(async()=>{if(J)return;const Sn=o.current;if(Sn)try{await Sn.play(),qe(!1)}catch(Fn){qe(!0),console.warn("Live preview still blocked (needs user gesture):",Fn)}},[J]),zt=j.useCallback(()=>{c.current&&c.current.state!=="inactive"&&c.current.stop(),f.current&&(clearInterval(f.current),f.current=null),gs(),X(!1),le(!1)},[gs]),vs=j.useCallback(async()=>{let Sn=null;if(b==="screen"){if(Sn=await Ss(),!Sn)return}else Sn=is&&Ut?Ut:d.current;if(!Sn)return;Bt(),m.current=[],fe(0);const bn=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(Tr=>MediaRecorder.isTypeSupported(Tr)),xs=new MediaRecorder(Sn,bn?{mimeType:bn,videoBitsPerSecond:b==="screen"?4e6:25e5,audioBitsPerSecond:128e3}:{videoBitsPerSecond:b==="screen"?4e6:25e5,audioBitsPerSecond:128e3});xs.ondataavailable=Tr=>{Tr.data.size>0&&m.current.push(Tr.data)},xs.onstop=()=>{var Xn;const Tr=xs.mimeType||bn||((Xn=m.current[0])==null?void 0:Xn.type)||"video/webm",Lr=new Blob(m.current,{type:Tr});te(Lr);const la=URL.createObjectURL(Lr);ce(la)},c.current=xs,xs.start(1e3),X(!0),f.current=setInterval(()=>{fe(Tr=>Tr>=s-1?(zt(),s):Tr+1)},1e3)},[Bt,s,zt,is,Ut,b,Ss]),dn=j.useCallback(()=>{ht.current&&(clearInterval(ht.current),ht.current=null),Ve(3);let Sn=3;ht.current=setInterval(()=>{Sn-=1,Sn<=0?(ht.current&&clearInterval(ht.current),ht.current=null,Ve(null),vs()):Ve(Sn)},1e3)},[vs]),Ks=j.useCallback(()=>{c.current&&c.current.state==="recording"&&(c.current.pause(),le(!0),f.current&&clearInterval(f.current))},[]),Cn=j.useCallback(()=>{c.current&&c.current.state==="paused"&&(c.current.resume(),le(!1),f.current=setInterval(()=>{fe(Sn=>Sn>=s-1?(zt(),s):Sn+1)},1e3))},[s,zt]),Rr=j.useCallback(()=>{J&&URL.revokeObjectURL(J),te(null),ce(null),fe(0),Fe(!1),Be(!0),o.current&&d.current&&!is&&(o.current.srcObject=d.current,o.current.muted=!0,Bt())},[Bt,J,is]),ia=j.useCallback(()=>{be(Sn=>Sn==="user"?"environment":"user")},[]),Hs=j.useCallback(()=>{re&&t(re,ve)},[re,ve,t]),Br=j.useCallback(()=>{o.current&&J&&(Ie?o.current.pause():(Be(!1),o.current.muted=!1,o.current.play()),Fe(!Ie))},[J,Ie]);j.useEffect(()=>{if(!J)return;const Sn=o.current;if(!Sn)return;Be(!1),Sn.pause(),Sn.removeAttribute("src"),Sn.srcObject=null,Sn.load(),Sn.src=J,Sn.currentTime=0,Sn.playsInline=!0,Sn.muted=!1,Sn.onended=()=>Fe(!1);const Fn=()=>{var Tr;const bn=Sn.error,xs=bn?`Recorded video failed to play (code ${bn.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",bn),(Tr=jt.current)==null||Tr.call(jt,xs)};return Sn.addEventListener("error",Fn),Sn.load(),()=>{Sn.removeEventListener("error",Fn)}},[J]);const Ur=Sn=>{const Fn=Math.floor(Sn/60),bn=Sn%60;return`${Fn}:${bn.toString().padStart(2,"0")}`},Wn=b==="screen"?"aspect-video":y&&D?"aspect-[9/16]":"aspect-video";return U?e.jsx("div",{className:Pt("flex items-center justify-center bg-black rounded-lg",Wn,i),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(Ct,{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",Wn,i),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(vl,{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:Se||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs($,{onClick:()=>Ds(),variant:"secondary",className:"w-full",children:[e.jsx(co,{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:[!Z&&!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(jx,{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(Gz,{className:"h-4 w-4"}),"Screen"]})]}),a&&b==="camera"&&!Z&&!J&&e.jsx(zUn,{value:Qe,onChange:at,isLoading:Ft,disabled:Z}),!Z&&!J&&(rt.length>0||Je.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[rt.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Hz,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ms,{value:gt||"default",onValueChange:Sn=>es(Sn==="default"?"":Sn),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"}),rt.map(Sn=>e.jsx(Ge,{value:Sn.deviceId,children:Sn.label||`Microphone ${Sn.deviceId.slice(0,6)}`},Sn.deviceId))]})]})]}),Je.length>1&&b==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(jx,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ms,{value:Ht||"default",onValueChange:Sn=>as(Sn==="default"?"":Sn),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"}),Je.map(Sn=>e.jsx(Ge,{value:Sn.deviceId,children:Sn.label||`Camera ${Sn.deviceId.slice(0,6)}`},Sn.deviceId))]})]})]})]}),b==="camera"&&y&&!Z&&!J&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(ZN,{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(jn,{id:"orientation-toggle",checked:D,onCheckedChange:zs}),e.jsx(ee,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(g1,{className:Pt("h-4 w-4",D?"text-primary":"text-muted-foreground")})]}),b==="screen"&&!Z&&!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(Gz,{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:()=>{Bt()},children:[e.jsx("video",{ref:o,src:J??void 0,className:Pt("w-full bg-black",D&&!J?"object-contain":"object-cover",Wn,!J&&ue==="user"!==(Qe.mirror??!1)&&"scale-x-[-1]",is&&!J&&"hidden"),playsInline:!0,controls:!!J,muted:J?Ne:!0,autoPlay:!J},J??"live"),is&&!J&&e.jsx("canvas",{ref:bs,className:Pt("w-full bg-black",D?"object-contain":"object-cover",Wn,ue==="user"!==(Qe.mirror??!1)&&"scale-x-[-1]")}),is&&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(Ct,{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 Bt(),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…"})]})}),Z&&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:[Ur(ve)," / ",Ur(s)]})]}),Z&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(Yi,{value:ve/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(Hz,{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:Rr,children:[e.jsx(co,{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:Br,children:Ie?e.jsx(Cv,{className:"h-5 w-5"}):e.jsx(Ou,{className:"h-5 w-5"})}),e.jsxs($,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:Hs,children:[e.jsx(ma,{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:ia,disabled:Z||ze!==null,children:e.jsx(Sx,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!Z&&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"?vs:dn,children:b==="screen"?e.jsx(Gz,{className:"h-6 w-6"}):e.jsx(fa,{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?Cn:Ks,children:ae?e.jsx(Ou,{className:"h-5 w-5"}):e.jsx(Cv,{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:zt,children:e.jsx(w_,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function EVn({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=_s(),{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(Os,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx($s,{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(Ct,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx(DT,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function TVn({value:s,onChange:t}){const{user:n}=_s(),[r,a]=j.useState(!1);return e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(fa,{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(Le,{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(mr,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(Ou,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(e9,{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(fa,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(EVn,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function RS(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function MVn({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:RS(i.bedrooms),bathrooms:RS(i.bathrooms),sqft:RS(i.sqft),yearBuilt:RS(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx($s,{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(Ct,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(tl,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function PVn({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=RS(a.price),c=RS(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:RS(a.bedrooms),bathrooms:RS(a.bathrooms),sqft:c,yearBuilt:RS(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx($s,{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()||!RS(a.price)||!RS(a.sqft),children:[e.jsx(cn,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function IVn(){var ue,be,Ee,ke,Ie,Fe,Ne;const{id:s}=Wi(),t=Zn(),{toast:n}=Bi(),{data:r,isLoading:a}=M$n(s),{data:i}=P$n(s),l=I$n(),o=D$n(),c=F$n(),{leadSite:d,isLoading:u}=tg(),[h,m]=j.useState([]),[f,g]=j.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[x,v]=j.useState(null),[y,b]=j.useState(!1),[w,S]=j.useState({low:"",likely:"",high:"",note:""}),[A,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(!1),[O,U]=j.useState(null),W=async Be=>{var Ve,ht;if(!r||!(Be!=null&&Be.address)||!(Be!=null&&Be.city)||!(Be!=null&&Be.state))return Be;let Se={...Be};const Ae=async Qe=>{const{data:at,error:rt}=await q.functions.invoke("cma-subject-lookup",{body:{address:Qe.address,city:Qe.city,state:Qe.state,zip:Qe.zip,latitude:Qe.latitude,longitude:Qe.longitude,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id}});if(rt)throw rt;return(at==null?void 0:at.matches)||[]},Ce=Qe=>{const rt=Qe.find(gt=>Number.isFinite(Number(gt.latitude))&&Number.isFinite(Number(gt.longitude)))||Qe[0];if(!rt)return;const Ke=typeof rt.match_type=="string"&&rt.match_type.startsWith("nearby-"),Je=Ke&&Number.isFinite(Number(Se.latitude))&&Number.isFinite(Number(Se.longitude)),ft=gt=>rt[gt]!==void 0&&rt[gt]!==null&&rt[gt]!==""&&rt[gt]!==0?rt[gt]:Se[gt];Se={...Se,bedrooms:ft("bedrooms"),bathrooms:ft("bathrooms"),sqft:ft("sqft"),yearBuilt:ft("yearBuilt"),lotSize:ft("lotSize"),propertyType:ft("propertyType"),propertySubType:ft("propertySubType"),source_provider:rt.source_provider??Se.source_provider,match_type:rt.match_type??Se.match_type,matched_mls_address:Ke?rt.address:Se.matched_mls_address,latitude:Je?Se.latitude:rt.latitude??Se.latitude,longitude:Je?Se.longitude:rt.longitude??Se.longitude,mlsNumber:Ke?Se.mlsNumber:rt.mlsNumber??Se.mlsNumber,photos:!Ke&&Array.isArray(rt.photos)&&rt.photos.length?rt.photos:Se.photos}};Ce(await Ae(Se));const qe=()=>Number.isFinite(Number(Se.latitude))&&Number.isFinite(Number(Se.longitude));if(!qe()){const{data:Qe}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),at=Qe==null?void 0:Qe.value;if(at){const rt=encodeURIComponent(`${Se.address}, ${Se.city}, ${Se.state} ${Se.zip||""}`.trim()),Je=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${rt}.json?access_token=${at}&limit=1&country=us`)).json(),ft=(ht=(Ve=Je==null?void 0:Je.features)==null?void 0:Ve[0])==null?void 0:ht.center;Array.isArray(ft)&&ft.length===2&&(Se.longitude=ft[0],Se.latitude=ft[1])}}if((!Se.bedrooms||!Se.bathrooms||!Se.sqft||!Se.yearBuilt)&&qe())try{Ce(await Ae(Se))}catch(Qe){console.warn("second-pass subject lookup failed",Qe)}return JSON.stringify(Se)!==JSON.stringify(Be)&&await l.mutateAsync({id:r.id,patch:{subject:Se}}),Se};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 Be=(Ae=r==null?void 0:r.settings)==null?void 0:Ae.priceOverride;Be!=null&&Be.enabled&&(b(!0),S({low:Be.low!=null?String(Be.low):"",likely:Be.likely!=null?String(Be.likely):"",high:Be.high!=null?String(Be.high):"",note:Be.note??""}));const Se=(Ce=r==null?void 0:r.settings)==null?void 0:Ce.personalVideo;Se!=null&&Se.url&&U({url:Se.url,thumb:Se.thumb,label:Se.label})},[r==null?void 0:r.id]);const V=j.useRef(!1);j.useEffect(()=>{V.current||i!=null&&i.length&&(m(i.map(Be=>({...Be.snapshot,selected:Be.selected,manual:Be.manual,score:Be.score}))),V.current=!0)},[i]);const G=j.useRef(null);j.useEffect(()=>{if(!r||u)return;const Be=r.subject||{},Se=Number.isFinite(Number(Be.latitude))&&Number.isFinite(Number(Be.longitude)),Ae=!!(Number(Be.bedrooms)||Number(Be.bathrooms)||Number(Be.sqft)||Number(Be.yearBuilt));if(Se&&Ae)return;const Ce=`${r.id}:${(d==null?void 0:d.id)??r.lead_site_id??"no-site"}`;G.current!==Ce&&(!Be.address||!Be.city||!Be.state||(G.current=Ce,(async()=>{try{await W(Be)}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 Z=j.useMemo(()=>r?gCt(r.subject,h):null,[r,h]),X=async()=>{if(r)try{const Be=await W(r.subject),Se=await o.mutateAsync({subject:Be,filters:f,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});m(Se.comps.map(Ae=>({...Ae,selected:!0})).slice(0,12)),n({title:`Found ${Se.comps.length} comps`,description:`Top ${Math.min(12,Se.comps.length)} auto-selected.`})}catch(Be){n({title:"Search failed",description:Be.message,variant:"destructive"})}},ae=Be=>{m(Se=>Se.map((Ae,Ce)=>Ce===Be?{...Ae,selected:!Ae.selected}:Ae))},le=Be=>{m(Se=>Se.filter((Ae,Ce)=>Ce!==Be))},re=async Be=>{if(!r)return;const Se=Object.fromEntries(Object.entries(Be).filter(([,Ce])=>Ce!=null&&Ce!=="")),Ae={...r.subject,...Se,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=Be=>{m(Se=>[{...Be,selected:!0,manual:!0},...Se]),n({title:"Manual comp added"})},J=async(Be=!1)=>{if(!r)return;const Se=gCt(r.subject,h),Ae=ht=>{const Qe=Number(String(ht).replace(/[^0-9.]/g,""));return Number.isFinite(Qe)&&Qe>0?Math.round(Qe):null},Ce=y?Ae(w.likely):null,qe=y?Ae(w.low):null,ze=y?Ae(w.high):null,Ve=y&&Ce;await l.mutateAsync({id:r.id,patch:{settings:{...f,priceOverride:{enabled:y,low:qe,likely:Ce,high:ze,note:w.note||null},personalVideo:O},price_low:Ve?qe??Ce:Se.low??null,price_likely:Ve?Ce:Se.likely??null,price_high:Ve?ze??Ce:Se.high??null,status:Be?"shared":r.status}}),await c.mutateAsync({cmaId:r.id,comps:h}),n({title:Be?"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(Ct,{className:"w-6 h-6 animate-spin"})})});const ve=h.filter(Be=>Be.selected).length,fe=!((ue=r.subject)!=null&&ue.bedrooms)||!((be=r.subject)!=null&&be.bathrooms)||!((Ee=r.subject)!=null&&Ee.sqft)||!((ke=r.subject)!=null&&ke.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(Va,{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(Hd,{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(Ir,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs($,{onClick:()=>E(!0),children:[e.jsx(pn,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Subject Property"})}),e.jsxs(Le,{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:"})," ",((Ie=r.subject.sqft)==null?void 0:Ie.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),fe&&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(pi,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!fe&&e.jsxs($,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>P(!0),children:[e.jsx(pi,{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 Be=>{const Se=Number(Be.target.value);Se>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:Se}}})}})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(r2,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(Le,{className:"space-y-3",children:[Z!=null&&Z.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(y&&Number(w.likely)>0?Number(w.likely):Z.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(Fe=Z.low)==null?void 0:Fe.toLocaleString()," – $",(Ne=Z.high)==null?void 0:Ne.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Z.ppsf,"/sqft median · ",ve," 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(jn,{id:"override-toggle",checked:y,onCheckedChange:b})]}),y&&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:Be=>S(Se=>({...Se,likely:Be.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:Be=>S(Se=>({...Se,low:Be.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:Be=>S(Se=>({...Se,high:Be.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:Be=>S(Se=>({...Se,note:Be.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(TVn,{value:O,onChange:U}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Filters"})}),e.jsxs(Le,{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(bx,{value:[f.sqftPct*100],min:5,max:50,step:5,onValueChange:([Be])=>g(Se=>({...Se,sqftPct:Be/100}))})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["Search radius: ",f.maxMiles," mi"]}),e.jsx(bx,{value:[f.maxMiles],min:1,max:25,step:1,onValueChange:([Be])=>g(Se=>({...Se,maxMiles:Be}))})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["Sold within: ",f.monthsBack," months"]}),e.jsx(bx,{value:[f.monthsBack],min:1,max:24,step:1,onValueChange:([Be])=>g(Se=>({...Se,monthsBack:Be}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Be=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ai,{checked:f.statuses.includes(Be),onCheckedChange:Se=>g(Ae=>({...Ae,statuses:Se?[...Ae.statuses,Be]:Ae.statuses.filter(Ce=>Ce!==Be)}))})," ",Be]},Be))]}),e.jsxs($,{className:"w-full",onClick:X,disabled:o.isPending,children:[o.isPending?e.jsx(Ct,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(wn,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>D(!0),children:[e.jsx(cn,{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(FUn,{subject:r.subject,comps:h,radiusMiles:f.maxMiles,onMarkerClick:Be=>v(Be)}),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:[ve," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Be,Se)=>{var Ae;return e.jsx(je,{className:Be.selected?"":"opacity-50",children:e.jsxs(Le,{className:"p-3 flex gap-3 items-center",children:[e.jsx(ai,{checked:Be.selected,onCheckedChange:()=>ae(Se)}),e.jsxs("button",{type:"button",onClick:()=>v(Se),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(BEe,{photos:Be.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:Be.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Be.city,", ",Be.state," · ",Be.bedrooms??"?","bd/",Be.bathrooms??"?","ba · ",((Ae=Be.sqft)==null?void 0:Ae.toLocaleString())??"?"," sqft",Be.yearBuilt?` · ${Be.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx($e,{variant:"outline",className:"mr-1",children:Be.status}),Be.score!=null&&e.jsxs("span",{className:"text-muted-foreground",children:["Score ",Be.score]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"font-semibold",children:["$",(Be.soldPrice||Be.price||0).toLocaleString()]}),Be.sqft&&(Be.soldPrice||Be.price)?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Math.round((Be.soldPrice||Be.price)/Be.sqft),"/sqft"]}):null]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>v(Se),title:"View details",children:e.jsx(Ta,{className:"w-4 h-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>le(Se),title:"Remove",children:e.jsx(qn,{className:"w-4 h-4"})})]})},Se)})}):e.jsx(je,{children:e.jsx(Le,{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:[fe&&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(X9t,{comp:x!=null?h[x]:null,open:x!=null,onClose:()=>v(null)}),e.jsx(MVn,{open:I,onOpenChange:P,subject:r.subject,onSave:re,isSaving:l.isPending}),e.jsx(PVn,{open:R,onOpenChange:D,subject:r.subject,onAdd:te}),e.jsx(KQt,{open:A,onOpenChange:E,cma:r})]})})}const FL="listing-presentations";function Jes(){const{user:s}=_s(),t=Zt(),n=st({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=mt({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(),ne.success("Template saved")},onError:o=>ne.error(o.message||"Could not save the template")}),i=mt({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(),ne.success("Template updated")},onError:o=>ne.error(o.message||"Could not update the template")}),l=mt({mutationFn:async o=>{const{error:c}=await q.from("listing_presentation_saved_templates").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ne.success("Template deleted")},onError:o=>ne.error(o.message||"Could not delete the template")});return{savedTemplates:n.data??[],isLoading:n.isLoading,save:a,update:i,remove:l}}function LVn(){return st({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 ets(){const{user:s}=_s(),t=Zt(),n=st({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=mt({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=>ne.error(c.message||"Could not create presentation")}),i=mt({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=>ne.error(c.message||"Could not save presentation")}),l=mt({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(FL).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(),ne.success("Presentation duplicated")},onError:c=>ne.error(c.message||"Could not duplicate")}),o=mt({mutationFn:async c=>{const d=[c.property_photo_path,c.pdf_path,c.thumbnail_path].filter(Boolean);d.length&&await q.storage.from(FL).remove(d);const{error:u}=await q.from("listing_presentations").delete().eq("id",c.id);if(u)throw u},onSuccess:()=>{r(),ne.success("Presentation deleted")},onError:c=>ne.error(c.message||"Could not delete")});return{presentations:n.data??[],isLoading:n.isLoading,create:a,update:i,duplicate:l,remove:o}}function RVn(s){return st({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 DVn(s,t=3600){if(!s)return null;const{data:n,error:r}=await q.storage.from(FL).createSignedUrl(s,t);return r?null:(n==null?void 0:n.signedUrl)??null}const WYe={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."}},FVn={cover:"Cover",welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function tts(s,t){var i;const n=((i=s==null?void 0:s.copy)==null?void 0:i[t])||{},r=WYe[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 sts={enabled:!1,name:"",title:null,headshotUrl:null,phone:null,email:null,brokerageName:null,licenseNumber:null,bio:null};function nts(s){return{...sts,...s||{}}}const s$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."}],rts=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`cp_${Math.random().toString(36).slice(2)}`;function uot(s,t=0){const n={id:rts(),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 ats(s){return Array.isArray(s)?s.filter(t=>t&&typeof t=="object").map((t,n)=>({...uot(t.layout||"story",n),...t,id:t.id||rts(),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 KYe={hidden:["overview"]},YYe={x:.5,y:.5},Jd=(s,t,n=!0)=>({key:s,label:t,enabled:n}),rPe=[{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:[Jd("hdr","Full HDR interior and exterior photo set"),Jd("drone","Aerial drone photography of the home and lot"),Jd("twilight","Twilight exterior session for the hero image"),Jd("staging","Virtual staging for vacant or transitional rooms",!1),Jd("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:[Jd("walkthrough","Cinematic full-property walkthrough video"),Jd("reels","Vertical short-form cuts for Reels, Shorts, and TikTok"),Jd("oncamera","On-camera agent introduction to the home"),Jd("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:[Jd("data","Complete, accurate MLS data so your home shows in every filter"),Jd("copy","Copywriting that leads with the features buyers pay for"),Jd("pricing","Pricing built on live comparable and absorption data"),Jd("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:[Jd("zillow","Zillow — the highest-traffic buyer search portal"),Jd("realtor","Realtor.com — direct MLS-sourced listing feed"),Jd("homes","Homes.com — agent-attributed listing exposure"),Jd("others","Redfin, Trulia, Movoto, and hundreds of partner sites"),Jd("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:[Jd("gallery","Full-screen gallery, video, and floor plan in one place"),Jd("mobile","Mobile-first design with a one-tap inquiry form"),Jd("link","Shareable link used across ads, email, and QR signage"),Jd("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:[Jd("organic","Just-listed launch across feed, stories, and reels"),Jd("ads","Geo-targeted paid campaigns aimed at active buyers"),Jd("retarget","Retargeting so interested viewers keep seeing your home"),Jd("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:[Jd("database","Direct email to my buyer and past-client database"),Jd("agents","Broadcast to area agents with matching buyers"),Jd("referral","Referral partner network notified at launch"),Jd("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:[Jd("public","Strategically timed public open houses"),Jd("broker","Broker open house for agents with active buyers"),Jd("signin","Digital sign-in that captures every visitor"),Jd("neighbors","Neighbor invitations and just-listed mailers"),Jd("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:[Jd("weekly","Weekly seller report on the schedule you prefer"),Jd("feedback","Showing feedback delivered as it comes in"),Jd("analytics","Online traffic and engagement analytics"),Jd("access","Direct access to me by call, text, or email")]}],OVn=Object.fromEntries(rPe.map(s=>[s.key,(s.options||[]).map(t=>t.label)]));function ZYe(s){return s!=null&&s.length?rPe.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}}):rPe.map(t=>{var n;return{...t,options:(n=t.options)==null?void 0:n.map(r=>({...r}))}})}const zVn={welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function Tm(s){"@babel/helpers - typeof";return Tm=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},Tm(s)}var xC=Uint8Array,Qj=Uint16Array,hot=Int32Array,mot=new xC([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]),fot=new xC([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]),S5t=new xC([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),its=function(s,t){for(var n=new Qj(31),r=0;r<31;++r)n[r]=t+=1<>1|(jp&21845)<<1;SM=(SM&52428)>>2|(SM&13107)<<2,SM=(SM&61680)>>4|(SM&3855)<<4,QYe[jp]=((SM&65280)>>8|(SM&255)<<8)>>1}var Xee=function(s,t,n){for(var r=s.length,a=0,i=new Qj(t);a>c]=d}else for(o=new Qj(r),a=0;a>15-s[a]);return o},lB=new xC(288);for(var jp=0;jp<144;++jp)lB[jp]=8;for(var jp=144;jp<256;++jp)lB[jp]=9;for(var jp=256;jp<280;++jp)lB[jp]=7;for(var jp=280;jp<288;++jp)lB[jp]=8;var aPe=new xC(32);for(var jp=0;jp<32;++jp)aPe[jp]=5;var UVn=Xee(lB,9,0),qVn=Xee(aPe,5,0),lts=function(s){return(s+7)/8|0},VVn=function(s,t,n){return(n==null||n>s.length)&&(n=s.length),new xC(s.subarray(t,n))},aA=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8},rX=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},n$e=function(s,t){for(var n=[],r=0;rm&&(m=i[r].s);var f=new Qj(m+1),g=JYe(n[u-1],f,0);if(g>t){var r=0,x=0,v=g-t,y=1<t)x+=y-(1<>=v;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 xC(f),l:g}},JYe=function(s,t,n){return s.s==-1?Math.max(JYe(s.l,t,n+1),JYe(s.r,t,n+1)):t[s.s]=n},A5t=function(s){for(var t=s.length;t&&!s[--t];);for(var n=new Qj(++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}},aX=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[S5t[U-1]];--U);var W=d+5<<3,V=aX(a,lB)+aX(i,aPe)+l,G=aX(a,m)+aX(i,x)+l+14+3*U+aX(I,D)+2*I[16]+3*I[17]+7*I[18];if(c>=0&&W<=V&&W<=G)return cts(t,u,s.subarray(c,c+d));var Z,X,ae,le;if(aA(t,u,1+(G15&&(aA(t,u,ce[P]>>5&127),u+=ce[P]>>12)}}else Z=UVn,X=lB,ae=qVn,le=aPe;for(var P=0;P255){var ve=fe>>18&31;rX(t,u,Z[ve+257]),u+=X[ve+257],ve>7&&(aA(t,u,fe>>23&31),u+=mot[ve]);var ue=fe&31;rX(t,u,ae[ue]),u+=le[ue],ue>3&&(rX(t,u,fe>>5&8191),u+=fot[ue])}else rX(t,u,Z[fe]),u+=X[fe]}return rX(t,u,Z[256]),u+X[256]},HVn=new hot([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),dts=new xC(0),GVn=function(s,t,n,r,a,i){var l=i.z||s.length,o=new xC(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=HVn[t-1],m=h>>13,f=h&8191,g=(1<7e3||D>24576)&&(Z>423||!d)){u=E5t(s,c,0,S,A,E,P,D,U,R-U,u),D=I=P=0,U=R;for(var X=0;X<286;++X)A[X]=0;for(var X=0;X<30;++X)E[X]=0}var ae=2,le=0,re=f,te=V-G&32767;if(Z>2&&W==w(R-te))for(var J=Math.min(m,Z)-1,ce=Math.min(32767,R),ve=Math.min(258,Z);te<=ce&&--re&&V!=G;){if(s[R+ae]==s[R+ae-te]){for(var fe=0;feae){if(ae=fe,le=te,fe>J)break;for(var ue=Math.min(te,fe-2),be=0,X=0;Xbe&&(be=Ie,G=Ee)}}}V=G,G=x[V],te+=V-G&32767}if(le){S[D++]=268435456|XYe[ae]<<18|C5t[le];var Fe=XYe[ae]&31,Ne=C5t[le]&31;P+=mot[Fe]+fot[Ne],++A[257+Fe],++E[Ne],O=R+ae,++I}else S[D++]=s[R],++A[s[R]]}}for(R=Math.max(R,O);R=l&&(c[u/8|0]=d,Be=l),u=cts(c,u+1,s.subarray(R,Be))}i.i=l}return VVn(o,0,r+lts(u)+a)},uts=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}}},WVn=function(s,t,n,r,a){if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new xC(i.length+s.length);l.set(i),l.set(s,i.length),s=l,a.w=i.length}return GVn(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)},hts=function(s,t,n){for(;n;++t)s[t]=n,n>>>=8},KVn=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=uts();a.p(t.dictionary),hts(s,2,a.d())}};function eZe(s,t){t||(t={});var n=uts();n.p(s);var r=WVn(s,t,t.dictionary?6:2,4);return KVn(r,t),hts(r,r.length-4,n.d()),r}var YVn=typeof TextDecoder<"u"&&new TextDecoder,ZVn=0;try{YVn.decode(dts,{stream:!0}),ZVn=1}catch{}function XVn(s){if(Array.isArray(s))return s}function QVn(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 T5t(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])})(),r$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 pot{constructor(t=nHn,n={}){_r(this,"buffer");_r(this,"byteLength");_r(this,"byteOffset");_r(this,"length");_r(this,"offset");_r(this,"lastWrittenByte");_r(this,"littleEndian");_r(this,"_data");_r(this,"_mark");_r(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 pot)&&(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=r$e[n].BYTES_PER_ELEMENT*t,a=this.byteOffset+this.offset,i=this.buffer.slice(a,a+r);if(this.littleEndian===rHn&&n!=="uint8"&&n!=="int8"){const o=new Uint8Array(this.buffer.slice(a,a+r));o.reverse();const c=new r$e[n](o.buffer);return this.offset+=r,c.reverse(),c}const l=new r$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 YK(s){let t=s.length;for(;--t>=0;)s[t]=0}const aHn=3,iHn=258,mts=29,oHn=256,lHn=oHn+1+mts,fts=30,cHn=512,dHn=new Array((lHn+2)*2);YK(dHn);const uHn=new Array(fts*2);YK(uHn);const hHn=new Array(cHn);YK(hHn);const mHn=new Array(iHn-aHn+1);YK(mHn);const fHn=new Array(mts);YK(fHn);const pHn=new Array(fts);YK(pHn);const gHn=(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 tZe=gHn;const xHn=()=>{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},yHn=new Uint32Array(xHn()),vHn=(s,t,n,r)=>{const a=yHn,i=r+n;s^=-1;for(let l=r;l>>8^a[(s^t[l])&255];return s^-1};var r5=vHn,sZe={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"},pts={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 bHn=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var _Hn=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)bHn(n,r)&&(s[r]=n[r])}}return s},wHn=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;fne[254]=fne[255]=1;var jHn=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 NHn=(s,t)=>{if(t<65534&&s.subarray&&xts)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 NHn(i,a)},SHn=(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+fne[s[n]]>t?n:t},nZe={string2buf:jHn,buf2string:kHn,utf8border:SHn};function CHn(){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 AHn=CHn;const yue=16209,EHn=16191;var THn=function(t,n){let r,a,i,l,o,c,d,u,h,m,f,g,x,v,y,b,w,S,A,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,v=O.distcode,y=(1<>>24,f>>>=S,g-=S,S=w>>>16&255,S===0)D[i++]=w&65535;else if(S&16){A=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=yue;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=yue;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++],A-=3;A&&(D[i++]=P[I++],A>1&&(D[i++]=P[I++]))}else{I=i-E;do D[i++]=D[I++],D[i++]=D[I++],D[i++]=D[I++],A-=3;while(A>2);A&&(D[i++]=D[I++],A>1&&(D[i++]=D[I++]))}}else if(S&64){t.msg="invalid distance code",O.mode=yue;break e}else{w=v[(w&65535)+(f&(1<>3,r-=A,g-=A<<3,f&=(1<{const c=o.bits;let d=0,u=0,h=0,m=0,f=0,g=0,x=0,v=0,y=0,b=0,w,S,A,E,I,P=null,R;const D=new Uint16Array(z$+1),O=new Uint16Array(z$+1);let U=null,W,V,G;for(d=0;d<=z$;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===R5t||m!==1))return-1;for(O[1]=0,d=1;dI5t||s===D5t&&y>L5t)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)!==A){for(x===0&&(x=f),I+=h,g=d-x,v=1<I5t||s===D5t&&y>L5t)return 1;A=b&E,a[A]=f<<24|g<<16|I-i|0}}return b!==0&&(a[I+b]=d-x<<24|64<<16|0),o.bits=f,0};var Qee=RHn;const DHn=0,yts=1,vts=2,{Z_FINISH:F5t,Z_BLOCK:FHn,Z_TREES:vue,Z_OK:cB,Z_STREAM_END:OHn,Z_NEED_DICT:zHn,Z_STREAM_ERROR:mk,Z_DATA_ERROR:bts,Z_MEM_ERROR:_ts,Z_BUF_ERROR:BHn,Z_DEFLATED:O5t}=pts,ADe=16180,z5t=16181,B5t=16182,$5t=16183,U5t=16184,q5t=16185,V5t=16186,H5t=16187,G5t=16188,W5t=16189,iPe=16190,iA=16191,i$e=16192,K5t=16193,o$e=16194,Y5t=16195,Z5t=16196,X5t=16197,Q5t=16198,bue=16199,_ue=16200,J5t=16201,e4t=16202,t4t=16203,s4t=16204,n4t=16205,l$e=16206,r4t=16207,a4t=16208,Rp=16209,wts=16210,jts=16211,$Hn=852,UHn=592,qHn=15,VHn=qHn,i4t=s=>(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24);function HHn(){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 r9=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.modejts?1:0},Nts=s=>{if(r9(s))return mk;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=ADe,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($Hn),t.distcode=t.distdyn=new Int32Array(UHn),t.sane=1,t.back=-1,cB},kts=s=>{if(r9(s))return mk;const t=s.state;return t.wsize=0,t.whave=0,t.wnext=0,Nts(s)},Sts=(s,t)=>{let n;if(r9(s))return mk;const r=s.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?mk:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,kts(s))},Cts=(s,t)=>{if(!s)return mk;const n=new HHn;s.state=n,n.strm=s,n.window=null,n.mode=ADe;const r=Sts(s,t);return r!==cB&&(s.state=null),r},GHn=s=>Cts(s,VHn);let o4t=!0,c$e,d$e;const WHn=s=>{if(o4t){c$e=new Int32Array(512),d$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(Qee(yts,s.lens,0,288,c$e,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;Qee(vts,s.lens,0,32,d$e,0,s.work,{bits:5}),o4t=!1}s.lencode=c$e,s.lenbits=9,s.distcode=d$e,s.distbits=5},Ats=(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,v=0,y,b,w,S,A,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(r9(s)||!s.output||!s.input&&s.avail_in!==0)return mk;n=s.state,n.mode===iA&&(n.mode=i$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=cB;e:for(;;)switch(n.mode){case ADe:if(n.wrap===0){n.mode=i$e;break}for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=r5(n.check,R,2,0),d=0,u=0,n.mode=z5t;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Rp;break}if((d&15)!==O5t){s.msg="unknown compression method",n.mode=Rp;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=Rp;break}n.dmax=1<>8&1),n.flags&512&&n.wrap&4&&(R[0]=d&255,R[1]=d>>>8&255,n.check=r5(n.check,R,2,0)),d=0,u=0,n.mode=B5t;case B5t: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=r5(n.check,R,4,0)),d=0,u=0,n.mode=$5t;case $5t: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=r5(n.check,R,2,0)),d=0,u=0,n.mode=U5t;case U5t:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=r5(n.check,R,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=q5t;case q5t: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=r5(n.check,r,f,i)),o-=f,i+=f,n.length-=f),n.length))break e;n.length=0,n.mode=V5t;case V5t: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=iA;break;case W5t:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=l$e;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=K5t;break;case 1:if(WHn(n),n.mode=bue,t===vue){d>>>=2,u-=2;break e}break;case 2:n.mode=Z5t;break;case 3:s.msg="invalid block type",n.mode=Rp}d>>>=2,u-=2;break;case K5t: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=Rp;break}if(n.length=d&65535,d=0,u=0,n.mode=o$e,t===vue)break e;case o$e:n.mode=Y5t;case Y5t: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=iA;break;case Z5t: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=Rp;break}n.have=0,n.mode=X5t;case X5t: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=Qee(DHn,n.lens,0,19,n.lencode,0,n.work,D),n.lenbits=D.bits,P){s.msg="invalid code lengths set",n.mode=Rp;break}n.have=0,n.mode=Q5t;case Q5t:for(;n.have>>24,b=v>>>16&255,w=v&65535,!(y<=u);){if(o===0)break e;o--,d+=r[i++]<>>=y,u-=y,n.lens[n.have++]=w;else{if(w===16){for(O=y+2;u>>=y,u-=y,n.have===0){s.msg="invalid bit length repeat",n.mode=Rp;break}I=n.lens[n.have-1],f=3+(d&3),d>>>=2,u-=2}else if(w===17){for(O=y+3;u>>=y,u-=y,I=0,f=3+(d&7),d>>>=3,u-=3}else{for(O=y+7;u>>=y,u-=y,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=Rp;break}for(;f--;)n.lens[n.have++]=I}}if(n.mode===Rp)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Rp;break}if(n.lenbits=9,D={bits:n.lenbits},P=Qee(yts,n.lens,0,n.nlen,n.lencode,0,n.work,D),n.lenbits=D.bits,P){s.msg="invalid literal/lengths set",n.mode=Rp;break}if(n.distbits=6,n.distcode=n.distdyn,D={bits:n.distbits},P=Qee(vts,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,D),n.distbits=D.bits,P){s.msg="invalid distances set",n.mode=Rp;break}if(n.mode=bue,t===vue)break e;case bue:n.mode=_ue;case _ue: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,THn(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===iA&&(n.back=-1);break}for(n.back=0;v=n.lencode[d&(1<>>24,b=v>>>16&255,w=v&65535,!(y<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],y=v>>>24,b=v>>>16&255,w=v&65535,!(S+y<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=y,u-=y,n.back+=y,n.length=w,b===0){n.mode=n4t;break}if(b&32){n.back=-1,n.mode=iA;break}if(b&64){s.msg="invalid literal/length code",n.mode=Rp;break}n.extra=b&15,n.mode=J5t;case J5t:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=e4t;case e4t:for(;v=n.distcode[d&(1<>>24,b=v>>>16&255,w=v&65535,!(y<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],y=v>>>24,b=v>>>16&255,w=v&65535,!(S+y<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=y,u-=y,n.back+=y,b&64){s.msg="invalid distance code",n.mode=Rp;break}n.offset=w,n.extra=b&15,n.mode=t4t;case t4t: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=Rp;break}n.mode=s4t;case s4t: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=Rp;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=_ue);break;case n4t:if(c===0)break e;a[l++]=n.length,c--,n.mode=_ue;break;case l$e:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<{if(r9(s))return mk;let t=s.state;return t.window&&(t.window=null),s.state=null,cB},ZHn=(s,t)=>{if(r9(s))return mk;const n=s.state;return n.wrap&2?(n.head=t,t.done=!1,cB):mk},XHn=(s,t)=>{const n=t.length;let r,a,i;return r9(s)||(r=s.state,r.wrap!==0&&r.mode!==iPe)?mk:r.mode===iPe&&(a=1,a=tZe(a,t,n,0),a!==r.check)?bts:(i=Ats(s,t,n,n),i?(r.mode=wts,_ts):(r.havedict=1,cB))};var QHn=kts,JHn=Sts,eGn=Nts,tGn=GHn,sGn=Cts,nGn=KHn,rGn=YHn,aGn=ZHn,iGn=XHn,oGn="pako inflate (from Nodeca project)",E5={inflateReset:QHn,inflateReset2:JHn,inflateResetKeep:eGn,inflateInit:tGn,inflateInit2:sGn,inflate:nGn,inflateEnd:rGn,inflateGetHeader:aGn,inflateSetDictionary:iGn,inflateInfo:oGn};function lGn(){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 cGn=lGn;const Ets=Object.prototype.toString,{Z_NO_FLUSH:dGn,Z_FINISH:l4t,Z_OK:PV,Z_STREAM_END:u$e,Z_NEED_DICT:h$e,Z_STREAM_ERROR:uGn,Z_DATA_ERROR:c4t,Z_MEM_ERROR:hGn,Z_BUF_ERROR:d4t}=pts,mGn={chunkSize:1024*64,windowBits:15,to:""};function Bie(s){this.options=gts.assign({},mGn,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 AHn,this.strm.avail_out=0;let n=E5.inflateInit2(this.strm,t.windowBits);if(n!==PV)throw new Error(sZe[n]);if(this.header=new cGn,E5.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=nZe.string2buf(t.dictionary):Ets.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=E5.inflateSetDictionary(this.strm,t.dictionary),n!==PV)))throw new Error(sZe[n])}Bie.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?l4t:dGn,Ets.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=E5.inflate(n,l),i===h$e&&a&&(i=E5.inflateSetDictionary(n,a),i===PV?i=E5.inflate(n,l):i===c4t&&(i=h$e));n.avail_in>0&&i===u$e&&n.state.wrap&2&&n.state.flags!==0&&n.input[n.next_in]!==0;)E5.inflateReset(n),i=E5.inflate(n,l);switch(i){case uGn:case c4t:case h$e:case hGn:return this.onEnd(i),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(n.avail_out===0||i===u$e||l>0))if(this.options.to==="string"){let c=nZe.utf8border(n.output,n.next_out),d=n.next_out-c,u=nZe.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===PV||i===d4t)&&o===0)){if(i===u$e)return i=E5.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,!0;if(n.avail_in===0){if(l===l4t)return i=E5.inflateEnd(this.strm),this.onEnd(i===PV?d4t:i),this.ended=!0,!1;break}}}return!0};Bie.prototype.onData=function(s){this.chunks.push(s)};Bie.prototype.onEnd=function(s){s===PV&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=gts.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function fGn(s,t){const n=new Bie(t);if(n.push(s,!0),n.err)throw n.msg||sZe[n.err];return n.result}var pGn=Bie,gGn=fGn,xGn={Inflate:pGn,inflate:gGn};const{Inflate:yGn,inflate:vGn}=xGn;var u4t=yGn,bGn=vGn;const Tts=[];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;Tts[s]=t}const h4t=4294967295;function _Gn(s,t,n){let r=s;for(let a=0;a>>8;return r}function wGn(s,t){return(_Gn(h4t,s,t)^h4t)>>>0}function m4t(s,t,n){const r=s.readUint32(),a=wGn(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 Mts(s,t,n){for(let r=0;r>1)&255}else{for(;i>1)&255;for(;i>1)&255}}function Rts(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 TGn=new Uint16Array([255]),MGn=new Uint8Array(TGn.buffer),PGn=MGn[0]===255,IGn=new Uint8Array(0);function f4t(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=IGn,u=0,h,m;for(let f=0;f>8&255}const S3e=Uint8Array.of(137,80,78,71,13,10,26,10);function p4t(s){if(!RGn(s.readBytes(S3e.length)))throw new Error("wrong PNG signature")}function RGn(s){if(s.length79)throw new Error("keyword length must be between 1 and 79")}const zGn=/^[\u0000-\u00FF]*$/;function BGn(s){if(!zGn.test(s))throw new Error("invalid latin1 text")}function $Gn(s,t,n){const r=Fts(t);s[r]=UGn(t,n-r.length-1)}function Fts(s){for(s.mark();s.readByte()!==FGn;);const t=s.offset;s.reset();const n=Dts.decode(s.readBytes(t-s.offset-1));return s.skip(1),OGn(n),n}function UGn(s,t){return Dts.decode(s.readBytes(t))}const xj={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},m$e={UNKNOWN:-1,DEFLATE:0},g4t={UNKNOWN:-1,ADAPTIVE:0},f$e={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},wue={NONE:0,BACKGROUND:1,PREVIOUS:2},p$e={SOURCE:0,OVER:1};class qGn extends pot{constructor(n,r={}){super(n);_r(this,"_checkCrc");_r(this,"_inflator");_r(this,"_png");_r(this,"_apng");_r(this,"_end");_r(this,"_hasPalette");_r(this,"_palette");_r(this,"_hasTransparency");_r(this,"_transparency");_r(this,"_compressionMethod");_r(this,"_filterMethod");_r(this,"_interlaceMethod");_r(this,"_colorType");_r(this,"_isAnimated");_r(this,"_numberOfFrames");_r(this,"_numberOfPlays");_r(this,"_frames");_r(this,"_writingDataChunks");const{checkCrc:a=!1}=r;this._checkCrc=a,this._inflator=new u4t,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=m$e.UNKNOWN,this._filterMethod=g4t.UNKNOWN,this._interlaceMethod=f$e.UNKNOWN,this._colorType=xj.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(p4t(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeChunk(n,r)}return this.decodeImage(),this._png}decodeApng(){for(p4t(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 DGn:$Gn(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?m4t(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?m4t(this,n+4,r):this.skip(4)}decodeIHDR(){const n=this._png;n.width=this.readUint32(),n.height=this.readUint32(),n.depth=VGn(this.readUint8());const r=this.readUint8();this._colorType=r;let a;switch(r){case xj.GREYSCALE:a=1;break;case xj.TRUECOLOUR:a=3;break;case xj.INDEXED_COLOUR:a=1;break;case xj.GREYSCALE_ALPHA:a=2;break;case xj.TRUECOLOUR_ALPHA:a=4;break;case xj.UNKNOWN:default:throw new Error(`Unknown color type: ${r}`)}if(this._png.channels=a,this._compressionMethod=this.readUint8(),this._compressionMethod!==m$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 p$e.SOURCE:for(let l=0;l=200&&t.status<=299}function jue(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 DO=Dc.saveAs||((typeof window>"u"?"undefined":Tm(window))!=="object"||window!==Dc?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(s,t,n){var r=Dc.URL||Dc.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?y4t(a.href)?x$e(s,t,n):jue(a,a.target="_blank"):jue(a)):(a.href=r.createObjectURL(s),setTimeout(function(){r.revokeObjectURL(a.href)},4e4),setTimeout(function(){jue(a)},0))}:"msSaveOrOpenBlob"in navigator?function(s,t,n){if(t=t||s.name||"download",typeof s=="string")if(y4t(s))x$e(s,t,n);else{var r=document.createElement("a");r.href=s,r.target="_blank",setTimeout(function(){jue(r)})}else navigator.msSaveOrOpenBlob(function(a,i){return i===void 0?i={autoBom:!1}:Tm(i)!=="object"&&(yf.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 x$e(s,t,n);var a=s.type==="application/octet-stream",i=/constructor/i.test(Dc.HTMLElement)||Dc.safari,l=/CriOS\/[\d]+/.test(navigator.userAgent);if((l||a&&i)&&(typeof FileReader>"u"?"undefined":Tm(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=Dc.URL||Dc.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 Ots(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 C3e=Dc.atob.bind(Dc),v4t=Dc.btoa.bind(Dc);/** * @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 y$e(s,t){var n=s[0],r=s[1],a=s[2],i=s[3];n=Kb(n,r,a,i,t[0],7,-680876936),i=Kb(i,n,r,a,t[1],12,-389564586),a=Kb(a,i,n,r,t[2],17,606105819),r=Kb(r,a,i,n,t[3],22,-1044525330),n=Kb(n,r,a,i,t[4],7,-176418897),i=Kb(i,n,r,a,t[5],12,1200080426),a=Kb(a,i,n,r,t[6],17,-1473231341),r=Kb(r,a,i,n,t[7],22,-45705983),n=Kb(n,r,a,i,t[8],7,1770035416),i=Kb(i,n,r,a,t[9],12,-1958414417),a=Kb(a,i,n,r,t[10],17,-42063),r=Kb(r,a,i,n,t[11],22,-1990404162),n=Kb(n,r,a,i,t[12],7,1804603682),i=Kb(i,n,r,a,t[13],12,-40341101),a=Kb(a,i,n,r,t[14],17,-1502002290),n=Yb(n,r=Kb(r,a,i,n,t[15],22,1236535329),a,i,t[1],5,-165796510),i=Yb(i,n,r,a,t[6],9,-1069501632),a=Yb(a,i,n,r,t[11],14,643717713),r=Yb(r,a,i,n,t[0],20,-373897302),n=Yb(n,r,a,i,t[5],5,-701558691),i=Yb(i,n,r,a,t[10],9,38016083),a=Yb(a,i,n,r,t[15],14,-660478335),r=Yb(r,a,i,n,t[4],20,-405537848),n=Yb(n,r,a,i,t[9],5,568446438),i=Yb(i,n,r,a,t[14],9,-1019803690),a=Yb(a,i,n,r,t[3],14,-187363961),r=Yb(r,a,i,n,t[8],20,1163531501),n=Yb(n,r,a,i,t[13],5,-1444681467),i=Yb(i,n,r,a,t[2],9,-51403784),a=Yb(a,i,n,r,t[7],14,1735328473),n=Zb(n,r=Yb(r,a,i,n,t[12],20,-1926607734),a,i,t[5],4,-378558),i=Zb(i,n,r,a,t[8],11,-2022574463),a=Zb(a,i,n,r,t[11],16,1839030562),r=Zb(r,a,i,n,t[14],23,-35309556),n=Zb(n,r,a,i,t[1],4,-1530992060),i=Zb(i,n,r,a,t[4],11,1272893353),a=Zb(a,i,n,r,t[7],16,-155497632),r=Zb(r,a,i,n,t[10],23,-1094730640),n=Zb(n,r,a,i,t[13],4,681279174),i=Zb(i,n,r,a,t[0],11,-358537222),a=Zb(a,i,n,r,t[3],16,-722521979),r=Zb(r,a,i,n,t[6],23,76029189),n=Zb(n,r,a,i,t[9],4,-640364487),i=Zb(i,n,r,a,t[12],11,-421815835),a=Zb(a,i,n,r,t[15],16,530742520),n=Xb(n,r=Zb(r,a,i,n,t[2],23,-995338651),a,i,t[0],6,-198630844),i=Xb(i,n,r,a,t[7],10,1126891415),a=Xb(a,i,n,r,t[14],15,-1416354905),r=Xb(r,a,i,n,t[5],21,-57434055),n=Xb(n,r,a,i,t[12],6,1700485571),i=Xb(i,n,r,a,t[3],10,-1894986606),a=Xb(a,i,n,r,t[10],15,-1051523),r=Xb(r,a,i,n,t[1],21,-2054922799),n=Xb(n,r,a,i,t[8],6,1873313359),i=Xb(i,n,r,a,t[15],10,-30611744),a=Xb(a,i,n,r,t[6],15,-1560198380),r=Xb(r,a,i,n,t[13],21,1309151649),n=Xb(n,r,a,i,t[4],6,-145523070),i=Xb(i,n,r,a,t[11],10,-1120210379),a=Xb(a,i,n,r,t[2],15,718787259),r=Xb(r,a,i,n,t[9],21,-343485551),s[0]=_I(n,s[0]),s[1]=_I(r,s[1]),s[2]=_I(a,s[2]),s[3]=_I(i,s[3])}function EDe(s,t,n,r,a,i){return t=_I(_I(t,s),_I(r,i)),_I(t<>>32-a,n)}function Kb(s,t,n,r,a,i,l){return EDe(t&n|~t&r,s,t,a,i,l)}function Yb(s,t,n,r,a,i,l){return EDe(t&r|n&~r,s,t,a,i,l)}function Zb(s,t,n,r,a,i,l){return EDe(t^n^r,s,t,a,i,l)}function Xb(s,t,n,r,a,i,l){return EDe(n^(t|~r),s,t,a,i,l)}function zts(s){var t,n=s.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=s.length;t+=64)y$e(r,GGn(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(y$e(r,a),t=0;t<16;t++)a[t]=0;return a[14]=8*n,y$e(r,a),r}function GGn(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 b4t="0123456789abcdef".split("");function WGn(s){for(var t="",n=0;n<4;n++)t+=b4t[s>>8*n+4&15]+b4t[s>>8*n&15];return t}function KGn(s){return String.fromCharCode(255&s,(65280&s)>>8,(16711680&s)>>16,(4278190080&s)>>24)}function rZe(s){return zts(s).map(KGn).join("")}var YGn=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 aZe(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=rZe(i+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(r)).substr(0,5),this.U=aZe(this.encryptionKey,this.padding)}function bU(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 w4t(s){if(Tm(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){Dc.console&&yf.error("jsPDF PubSub Error",o.message,o)}l[1]&&a.push(i)}a.length&&a.forEach(this.unsubscribe)}},this.getTopics=function(){return t}}function oPe(s){if(!(this instanceof oPe))return new oPe(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 Bts(s,t){this.gState=s,this.matrix=t,this.id="",this.objectNumber=-1}function KO(s,t,n,r,a){if(!(this instanceof KO))return new KO(s,t,n,r,a);this.type=s==="axial"?2:3,this.coords=t,this.colors=n,Bts.call(this,r,a)}function lq(s,t,n,r,a){if(!(this instanceof lq))return new lq(s,t,n,r,a);this.boundingBox=s,this.xStep=t,this.yStep=n,this.stream="",this.cloneIndex=0,Bts.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;Tm(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=w4t;var g="1.3",x=f.__private__.getPdfVersion=function(){return g};f.__private__.setPdfVersion=function(et){g=et};var v={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 v};var y=f.__private__.getPageFormat=function(et){return v[et]};a=a||"a4";var b="compat",w="advanced",S=b;function A(){this.saveGraphicsState(),Ae(new Hs(as,0,0,-as,0,gr()*as).toString()+" cm"),this.setFontSize(this.getFontSize()/as),d="n",S=w}function E(){this.restoreGraphicsState(),d="S",S=b}var I=f.__private__.combineFontStyleAndFontWeight=function(et,Gt){if(et=="bold"&&Gt=="normal"||et=="bold"&&Gt==400||et=="normal"&&Gt=="italic"||et=="bold"&&Gt=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return Gt&&(et=Gt==400||Gt==="normal"?et==="italic"?"italic":"normal":Gt!=700&&Gt!=="bold"||et!=="normal"?(Gt==700?"bold":Gt)+""+et:"bold"),et};f.advancedAPI=function(et){var Gt=S===b;return Gt&&A.call(this),typeof et!="function"||(et(this),Gt&&E.call(this)),this},f.compatAPI=function(et){var Gt=S===w;return Gt&&E.call(this),typeof et!="function"||(et(this),Gt&&A.call(this)),this},f.isAdvancedAPI=function(){return S===w};var P,R=function(et){if(S!==w)throw new Error(et+" is only available in 'advanced' API mode. You need to call advancedAPI() first.")},D=f.roundToPrecision=f.__private__.roundToPrecision=function(et,Gt){var Es=t||Gt;if(isNaN(et)||isNaN(Es))throw new Error("Invalid argument passed to jsPDF.roundToPrecision");return et.toFixed(Es).replace(/0+$/,"")};P=f.hpf=f.__private__.hpf=typeof c=="number"?function(et){if(isNaN(et))throw new Error("Invalid argument passed to jsPDF.hpf");return D(et,c)}:c==="smart"?function(et){if(isNaN(et))throw new Error("Invalid argument passed to jsPDF.hpf");return D(et,et>-1&&et<1?16:5)}:function(et){if(isNaN(et))throw new Error("Invalid argument passed to jsPDF.hpf");return D(et,16)};var O=f.f2=f.__private__.f2=function(et){if(isNaN(et))throw new Error("Invalid argument passed to jsPDF.f2");return D(et,2)},U=f.__private__.f3=function(et){if(isNaN(et))throw new Error("Invalid argument passed to jsPDF.f3");return D(et,3)},W=f.scale=f.__private__.scale=function(et){if(isNaN(et))throw new Error("Invalid argument passed to jsPDF.scale");return S===b?et*as:S===w?et:void 0},V=function(et){return W(function(Gt){return S===b?gr()-Gt:S===w?Gt:void 0}(et))};f.__private__.setPrecision=f.setPrecision=function(et){typeof parseInt(et,10)=="number"&&(t=parseInt(et,10))};var G,Z="00000000000000000000000000000000",X=f.__private__.getFileId=function(){return Z},ae=f.__private__.setFileId=function(et){return Z=et!==void 0&&/^[a-fA-F0-9]{32}$/.test(et)?et.toUpperCase():Z.split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""),u!==null&&(gc=new vU(u.userPermissions,u.userPassword,u.ownerPassword,Z)),Z};f.setFileId=function(et){return ae(et),this},f.getFileId=function(){return X()};var le=f.__private__.convertDateToPDFDate=function(et){var Gt=et.getTimezoneOffset(),Es=Gt<0?"+":"-",on=Math.floor(Math.abs(Gt/60)),en=Math.abs(Gt%60),tr=[Es,ve(on),"'",ve(en),"'"].join("");return["D:",et.getFullYear(),ve(et.getMonth()+1),ve(et.getDate()),ve(et.getHours()),ve(et.getMinutes()),ve(et.getSeconds()),tr].join("")},re=f.__private__.convertPDFDateToDate=function(et){var Gt=parseInt(et.substr(2,4),10),Es=parseInt(et.substr(6,2),10)-1,on=parseInt(et.substr(8,2),10),en=parseInt(et.substr(10,2),10),tr=parseInt(et.substr(12,2),10),sr=parseInt(et.substr(14,2),10);return new Date(Gt,Es,on,en,tr,sr,0)},te=f.__private__.setCreationDate=function(et){var Gt;if(et===void 0&&(et=new Date),et instanceof Date)Gt=le(et);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(et))throw new Error("Invalid argument passed to jsPDF.setCreationDate");Gt=et}return G=Gt},J=f.__private__.getCreationDate=function(et){var Gt=G;return et==="jsDate"&&(Gt=re(G)),Gt};f.setCreationDate=function(et){return te(et),this},f.getCreationDate=function(et){return J(et)};var ce,ve=f.__private__.padd2=function(et){return("0"+parseInt(et)).slice(-2)},fe=f.__private__.padd2Hex=function(et){return("00"+(et=et.toString())).substr(et.length)},ue=0,be=[],Ee=[],ke=0,Ie=[],Fe=[],Ne=!1,Be=Ee;f.__private__.setCustomOutputDestination=function(et){Ne=!0,Be=et};var Se=function(et){Ne||(Be=et)};f.__private__.resetCustomOutputDestination=function(){Ne=!1,Be=Ee};var Ae=f.__private__.out=function(et){return et=et.toString(),ke+=et.length+1,Be.push(et),Be},Ce=f.__private__.write=function(et){return Ae(arguments.length===1?et.toString():Array.prototype.join.call(arguments," "))},qe=f.__private__.getArrayBuffer=function(et){for(var Gt=et.length,Es=new ArrayBuffer(Gt),on=new Uint8Array(Es);Gt--;)on[Gt]=et.charCodeAt(Gt);return Es},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 Ve=s.fontSize||16;f.__private__.setFontSize=f.setFontSize=function(et){return Ve=S===w?et/as:et,this};var ht,Qe=f.__private__.getFontSize=f.getFontSize=function(){return S===b?Ve:Ve*as},at=s.R2L||!1;f.__private__.setR2L=f.setR2L=function(et){return at=et,this},f.__private__.getR2L=f.getR2L=function(){return at};var rt,Ke=f.__private__.setZoomMode=function(et){if(/^(?:\d+\.\d*|\d*\.\d+|\d+)%$/.test(et))ht=et;else if(isNaN(et)){if([void 0,null,"fullwidth","fullheight","fullpage","original"].indexOf(et)===-1)throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "'+et+'" is not recognized.');ht=et}else ht=parseInt(et,10)};f.__private__.getZoomMode=function(){return ht};var Je,ft=f.__private__.setPageMode=function(et){if([void 0,null,"UseNone","UseOutlines","UseThumbs","FullScreen"].indexOf(et)==-1)throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "'+et+'" is not recognized.');rt=et};f.__private__.getPageMode=function(){return rt};var gt=f.__private__.setLayoutMode=function(et){if([void 0,null,"continuous","single","twoleft","tworight","two"].indexOf(et)==-1)throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "'+et+'" is not recognized.');Je=et};f.__private__.getLayoutMode=function(){return Je},f.__private__.setDisplayMode=f.setDisplayMode=function(et,Gt,Es){return Ke(et),gt(Gt),ft(Es),this};var es={title:"",subject:"",author:"",keywords:"",creator:""};f.__private__.getDocumentProperty=function(et){if(Object.keys(es).indexOf(et)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return es[et]},f.__private__.getDocumentProperties=function(){return es},f.__private__.setDocumentProperties=f.setProperties=f.setDocumentProperties=function(et){for(var Gt in es)es.hasOwnProperty(Gt)&&et[Gt]&&(es[Gt]=et[Gt]);return this},f.__private__.setDocumentProperty=function(et,Gt){if(Object.keys(es).indexOf(et)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return es[et]=Gt};var Ht,as,bs,Ut,Ft,is={},jt={},zs=[],yt={},gs={},Ss={},Ds={},Bt=null,zt=0,vs=[],dn=new w4t(f),Ks=s.hotfixes||[],Cn={},Rr={},ia=[],Hs=function et(Gt,Es,on,en,tr,sr){if(!(this instanceof et))return new et(Gt,Es,on,en,tr,sr);isNaN(Gt)&&(Gt=1),isNaN(Es)&&(Es=0),isNaN(on)&&(on=0),isNaN(en)&&(en=1),isNaN(tr)&&(tr=0),isNaN(sr)&&(sr=0),this._matrix=[Gt,Es,on,en,tr,sr]};Object.defineProperty(Hs.prototype,"sx",{get:function(){return this._matrix[0]},set:function(et){this._matrix[0]=et}}),Object.defineProperty(Hs.prototype,"shy",{get:function(){return this._matrix[1]},set:function(et){this._matrix[1]=et}}),Object.defineProperty(Hs.prototype,"shx",{get:function(){return this._matrix[2]},set:function(et){this._matrix[2]=et}}),Object.defineProperty(Hs.prototype,"sy",{get:function(){return this._matrix[3]},set:function(et){this._matrix[3]=et}}),Object.defineProperty(Hs.prototype,"tx",{get:function(){return this._matrix[4]},set:function(et){this._matrix[4]=et}}),Object.defineProperty(Hs.prototype,"ty",{get:function(){return this._matrix[5]},set:function(et){this._matrix[5]=et}}),Object.defineProperty(Hs.prototype,"a",{get:function(){return this._matrix[0]},set:function(et){this._matrix[0]=et}}),Object.defineProperty(Hs.prototype,"b",{get:function(){return this._matrix[1]},set:function(et){this._matrix[1]=et}}),Object.defineProperty(Hs.prototype,"c",{get:function(){return this._matrix[2]},set:function(et){this._matrix[2]=et}}),Object.defineProperty(Hs.prototype,"d",{get:function(){return this._matrix[3]},set:function(et){this._matrix[3]=et}}),Object.defineProperty(Hs.prototype,"e",{get:function(){return this._matrix[4]},set:function(et){this._matrix[4]=et}}),Object.defineProperty(Hs.prototype,"f",{get:function(){return this._matrix[5]},set:function(et){this._matrix[5]=et}}),Object.defineProperty(Hs.prototype,"rotation",{get:function(){return Math.atan2(this.shx,this.sx)}}),Object.defineProperty(Hs.prototype,"scaleX",{get:function(){return this.decompose().scale.sx}}),Object.defineProperty(Hs.prototype,"scaleY",{get:function(){return this.decompose().scale.sy}}),Object.defineProperty(Hs.prototype,"isIdentity",{get:function(){return this.sx===1&&this.shy===0&&this.shx===0&&this.sy===1&&this.tx===0&&this.ty===0}}),Hs.prototype.join=function(et){return[this.sx,this.shy,this.shx,this.sy,this.tx,this.ty].map(P).join(et)},Hs.prototype.multiply=function(et){var Gt=et.sx*this.sx+et.shy*this.shx,Es=et.sx*this.shy+et.shy*this.sy,on=et.shx*this.sx+et.sy*this.shx,en=et.shx*this.shy+et.sy*this.sy,tr=et.tx*this.sx+et.ty*this.shx+this.tx,sr=et.tx*this.shy+et.ty*this.sy+this.ty;return new Hs(Gt,Es,on,en,tr,sr)},Hs.prototype.decompose=function(){var et=this.sx,Gt=this.shy,Es=this.shx,on=this.sy,en=this.tx,tr=this.ty,sr=Math.sqrt(et*et+Gt*Gt),Xr=(et/=sr)*Es+(Gt/=sr)*on;Es-=et*Xr,on-=Gt*Xr;var sa=Math.sqrt(Es*Es+on*on);return Xr/=sa,et*(on/=sa)>16&255,on=sa>>8&255,en=255&sa}if(on===void 0||tr===void 0&&Es===on&&on===en)Gt=typeof Es=="string"?Es+" "+sr[0]:et.precision===2?O(Es/255)+" "+sr[0]:U(Es/255)+" "+sr[0];else if(tr===void 0||Tm(tr)==="object"){if(tr&&!isNaN(tr.a)&&tr.a===0)return["1.","1.","1.",sr[1]].join(" ");Gt=typeof Es=="string"?[Es,on,en,sr[1]].join(" "):et.precision===2?[O(Es/255),O(on/255),O(en/255),sr[1]].join(" "):[U(Es/255),U(on/255),U(en/255),sr[1]].join(" ")}else Gt=typeof Es=="string"?[Es,on,en,tr,sr[2]].join(" "):et.precision===2?[O(Es),O(on),O(en),O(tr),sr[2]].join(" "):[U(Es),U(on),U(en),U(tr),sr[2]].join(" ");return Gt},Bn=f.__private__.getFilters=function(){return l},cr=f.__private__.putStream=function(et){var Gt=(et=et||{}).data||"",Es=et.filters||Bn(),on=et.alreadyAppliedFilters||[],en=et.addLength1||!1,tr=Gt.length,sr=et.objectId,Xr=function(Lo){return Lo};if(u!==null&&sr===void 0)throw new Error("ObjectId must be passed to putStream for file encryption");u!==null&&(Xr=gc.encryptor(sr,0));var sa={};Es===!0&&(Es=["FlateEncode"]);var $a=et.additionalKeyValues||[],Na=(sa=Go.API.processDataByFilters!==void 0?Go.API.processDataByFilters(Gt,Es):{data:Gt,reverseChain:[]}).reverseChain+(Array.isArray(on)?on.join(" "):on.toString());if(sa.data.length!==0&&($a.push({key:"Length",value:sa.data.length}),en===!0&&$a.push({key:"Length1",value:tr})),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 eo=[],xo=0;xo>"),sa.data.length!==0&&(Ae("stream"),Ae(Xr(sa.data)),Ae("endstream"))},Pa=f.__private__.putPage=function(et){var Gt=et.number,Es=et.data,on=et.objId,en=et.contentsObjId;xs(on,!0),Ae("<>"),Ae("endobj");var tr=Es.join(` `);return S===w&&(tr+=` Q`),xs(en,!0),cr({data:tr,filters:Bn(),objectId:en}),Ae("endobj"),on},ii=f.__private__.putPages=function(){var et,Gt,Es=[];for(et=1;et<=zt;et++)vs[et].objId=bn(),vs[et].contentsObjId=bn();for(et=1;et<=zt;et++)Es.push(Pa({number:et,data:Fe[et],objId:vs[et].objId,contentsObjId:vs[et].contentsObjId,mediaBox:vs[et].mediaBox,cropBox:vs[et].cropBox,bleedBox:vs[et].bleedBox,trimBox:vs[et].trimBox,artBox:vs[et].artBox,userUnit:vs[et].userUnit,rootDictionaryObjId:Lr,resourceDictionaryObjId:la}));xs(Lr,!0),Ae("<>"),Ae("endobj"),dn.publish("postPutPages")},$i=function(et){dn.publish("putFont",{font:et,out:Ae,newObject:Fn,putStream:cr}),et.isAlreadyPutted!==!0&&(et.objectNumber=Fn(),Ae("<<"),Ae("/Type /Font"),Ae("/BaseFont /"+bU(et.postScriptName)),Ae("/Subtype /Type1"),typeof et.encoding=="string"&&Ae("/Encoding /"+et.encoding),Ae("/FirstChar 32"),Ae("/LastChar 255"),Ae(">>"),Ae("endobj"))},Ln=function(et){et.objectNumber=Fn();var Gt=[];Gt.push({key:"Type",value:"/XObject"}),Gt.push({key:"Subtype",value:"/Form"}),Gt.push({key:"BBox",value:"["+[P(et.x),P(et.y),P(et.x+et.width),P(et.y+et.height)].join(" ")+"]"}),Gt.push({key:"Matrix",value:"["+et.matrix.toString()+"]"});var Es=et.pages[1].join(` `);cr({data:Es,additionalKeyValues:Gt,objectId:et.objectNumber}),Ae("endobj")},xa=function(et,Gt){Gt||(Gt=21);var Es=Fn(),on=function(sr,Xr){var sa,$a=[],Na=1/(Xr-1);for(sa=0;sa<1;sa+=Na)$a.push(sa);if($a.push(1),sr[0].offset!=0){var La={offset:0,color:sr[0].color};sr.unshift(La)}if(sr[sr.length-1].offset!=1){var eo={offset:1,color:sr[sr.length-1].color};sr.push(eo)}for(var xo="",io=0,Lo=0;Lo<$a.length;Lo++){for(sa=$a[Lo];sa>sr[io+1].offset;)io++;var Ul=sr[io].offset,fo=(sa-Ul)/(sr[io+1].offset-Ul),nl=sr[io].color,Pl=sr[io+1].color;xo+=fe(Math.round((1-fo)*nl[0]+fo*Pl[0]).toString(16))+fe(Math.round((1-fo)*nl[1]+fo*Pl[1]).toString(16))+fe(Math.round((1-fo)*nl[2]+fo*Pl[2]).toString(16))}return xo.trim()}(et.colors,Gt),en=[];en.push({key:"FunctionType",value:"0"}),en.push({key:"Domain",value:"[0.0 1.0]"}),en.push({key:"Size",value:"["+Gt+"]"}),en.push({key:"BitsPerSample",value:"8"}),en.push({key:"Range",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),en.push({key:"Decode",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),cr({data:on,additionalKeyValues:en,alreadyAppliedFilters:["/ASCIIHexDecode"],objectId:Es}),Ae("endobj"),et.objectNumber=Fn(),Ae("<< /ShadingType "+et.type),Ae("/ColorSpace /DeviceRGB");var tr="/Coords ["+P(parseFloat(et.coords[0]))+" "+P(parseFloat(et.coords[1]))+" ";et.type===2?tr+=P(parseFloat(et.coords[2]))+" "+P(parseFloat(et.coords[3])):tr+=P(parseFloat(et.coords[2]))+" "+P(parseFloat(et.coords[3]))+" "+P(parseFloat(et.coords[4]))+" "+P(parseFloat(et.coords[5])),Ae(tr+="]"),et.matrix&&Ae("/Matrix ["+et.matrix.toString()+"]"),Ae("/Function "+Es+" 0 R"),Ae("/Extend [true true]"),Ae(">>"),Ae("endobj")},Ka=function(et,Gt){var Es=bn(),on=Fn();Gt.push({resourcesOid:Es,objectOid:on}),et.objectNumber=on;var en=[];en.push({key:"Type",value:"/Pattern"}),en.push({key:"PatternType",value:"1"}),en.push({key:"PaintType",value:"1"}),en.push({key:"TilingType",value:"1"}),en.push({key:"BBox",value:"["+et.boundingBox.map(P).join(" ")+"]"}),en.push({key:"XStep",value:P(et.xStep)}),en.push({key:"YStep",value:P(et.yStep)}),en.push({key:"Resources",value:Es+" 0 R"}),et.matrix&&en.push({key:"Matrix",value:"["+et.matrix.toString()+"]"}),cr({data:et.stream,additionalKeyValues:en,objectId:et.objectNumber}),Ae("endobj")},uo=function(et){for(var Gt in et.objectNumber=Fn(),Ae("<<"),et)switch(Gt){case"opacity":Ae("/ca "+O(et[Gt]));break;case"stroke-opacity":Ae("/CA "+O(et[Gt]))}Ae(">>"),Ae("endobj")},Tc=function(et){xs(et.resourcesOid,!0),Ae("<<"),Ae("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),function(){for(var Gt in Ae("/Font <<"),is)is.hasOwnProperty(Gt)&&(h===!1||h===!0&&m.hasOwnProperty(Gt))&&Ae("/"+Gt+" "+is[Gt].objectNumber+" 0 R");Ae(">>")}(),function(){if(Object.keys(yt).length>0){for(var Gt in Ae("/Shading <<"),yt)yt.hasOwnProperty(Gt)&&yt[Gt]instanceof KO&&yt[Gt].objectNumber>=0&&Ae("/"+Gt+" "+yt[Gt].objectNumber+" 0 R");dn.publish("putShadingPatternDict"),Ae(">>")}}(),function(Gt){if(Object.keys(yt).length>0){for(var Es in Ae("/Pattern <<"),yt)yt.hasOwnProperty(Es)&&yt[Es]instanceof f.TilingPattern&&yt[Es].objectNumber>=0&&yt[Es].objectNumber>")}}(et.objectOid),function(){if(Object.keys(Ss).length>0){var Gt;for(Gt in Ae("/ExtGState <<"),Ss)Ss.hasOwnProperty(Gt)&&Ss[Gt].objectNumber>=0&&Ae("/"+Gt+" "+Ss[Gt].objectNumber+" 0 R");dn.publish("putGStateDict"),Ae(">>")}}(),function(){for(var Gt in Ae("/XObject <<"),Cn)Cn.hasOwnProperty(Gt)&&Cn[Gt].objectNumber>=0&&Ae("/"+Gt+" "+Cn[Gt].objectNumber+" 0 R");dn.publish("putXobjectDict"),Ae(">>")}(),Ae(">>"),Ae("endobj")},Fd=function(et){jt[et.fontName]=jt[et.fontName]||{},jt[et.fontName][et.fontStyle]=et.id},Nl=function(et,Gt,Es,on,en){var tr={id:"F"+(Object.keys(is).length+1).toString(10),postScriptName:et,fontName:Gt,fontStyle:Es,encoding:on,isStandardFont:en||!1,metadata:{}};return dn.publish("addFont",{font:tr,instance:this}),is[tr.id]=tr,Fd(tr),tr.id},Ho=f.__private__.pdfEscape=f.pdfEscape=function(et,Gt){return function(Es,on){var en,tr,sr,Xr,sa,$a,Na,La,eo;if(sr=(on=on||{}).sourceEncoding||"Unicode",sa=on.outputEncoding,(on.autoencode||sa)&&is[Ht].metadata&&is[Ht].metadata[sr]&&is[Ht].metadata[sr].encoding&&(Xr=is[Ht].metadata[sr].encoding,!sa&&is[Ht].encoding&&(sa=is[Ht].encoding),!sa&&Xr.codePages&&(sa=Xr.codePages[0]),typeof sa=="string"&&(sa=Xr[sa]),sa)){for(Na=!1,$a=[],en=0,tr=Es.length;en>8&&(Na=!0);Es=$a.join("")}for(en=Es.length;Na===void 0&&en!==0;)Es.charCodeAt(en-1)>>8&&(Na=!0),en--;if(!Na)return Es;for($a=on.noBOM?[]:[254,255],en=0,tr=Es.length;en>8)>>8)throw new Error("Character at position "+en+" of string '"+Es+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");$a.push(eo),$a.push(La-(eo<<8))}return String.fromCharCode.apply(void 0,$a)}(et,Gt).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},ti=f.__private__.beginPage=function(et){Fe[++zt]=[],vs[zt]={objId:0,contentsObjId:0,userUnit:Number(o),artBox:null,bleedBox:null,cropBox:null,trimBox:null,mediaBox:{bottomLeftX:0,bottomLeftY:0,topRightX:Number(et[0]),topRightY:Number(et[1])}},Th(zt),Se(Fe[ce])},Yr=function(et,Gt){var Es,on,en;switch(n=Gt||n,typeof et=="string"&&(Es=y(et.toLowerCase()),Array.isArray(Es)&&(on=Es[0],en=Es[1])),Array.isArray(et)&&(on=et[0]*as,en=et[1]*as),isNaN(on)&&(on=a[0],en=a[1]),(on>14400||en>14400)&&(yf.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"),on=Math.min(14400,on),en=Math.min(14400,en)),a=[on,en],n.substr(0,1)){case"l":en>on&&(a=[en,on]);break;case"p":on>en&&(a=[en,on])}ti(a),Fl(vo),Ae(gh),$t!==0&&Ae($t+" J"),Wt!==0&&Ae(Wt+" j"),dn.publish("addPage",{pageNumber:zt})},Eo=function(et){et>0&&et<=zt&&(Fe.splice(et,1),vs.splice(et,1),zt--,ce>zt&&(ce=zt),this.setPage(ce))},Th=function(et){et>0&&et<=zt&&(ce=et)},rh=f.__private__.getNumberOfPages=f.getNumberOfPages=function(){return Fe.length-1},ro=function(et,Gt,Es){var on,en=void 0;return Es=Es||{},et=et!==void 0?et:is[Ht].fontName,Gt=Gt!==void 0?Gt:is[Ht].fontStyle,on=et.toLowerCase(),jt[on]!==void 0&&jt[on][Gt]!==void 0?en=jt[on][Gt]:jt[et]!==void 0&&jt[et][Gt]!==void 0?en=jt[et][Gt]:Es.disableWarning===!1&&yf.warn("Unable to look up font label for font '"+et+"', '"+Gt+"'. Refer to getFontList() for available fonts."),en||Es.noFallback||(en=jt.times[Gt])==null&&(en=jt.times.normal),en},ea=f.__private__.putInfo=function(){var et=Fn(),Gt=function(on){return on};for(var Es in u!==null&&(Gt=gc.encryptor(et,0)),Ae("<<"),Ae("/Producer ("+Ho(Gt("jsPDF "+Go.version))+")"),es)es.hasOwnProperty(Es)&&es[Es]&&Ae("/"+Es.substr(0,1).toUpperCase()+Es.substr(1)+" ("+Ho(Gt(es[Es]))+")");Ae("/CreationDate ("+Ho(Gt(G))+")"),Ae(">>"),Ae("endobj")},pc=f.__private__.putCatalog=function(et){var Gt=(et=et||{}).rootDictionaryObjId||Lr;switch(Fn(),Ae("<<"),Ae("/Type /Catalog"),Ae("/Pages "+Gt+" 0 R"),ht||(ht="fullwidth"),ht){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 Es=""+ht;Es.substr(Es.length-1)==="%"&&(ht=parseInt(ht)/100),typeof ht=="number"&&Ae("/OpenAction [3 0 R /XYZ null null "+O(ht)+"]")}switch(Je||(Je="continuous"),Je){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")}rt&&Ae("/PageMode /"+rt),dn.publish("putCatalog"),Ae(">>"),Ae("endobj")},ml=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 "+gc.oid+" 0 R"),Ae("/ID [ <"+Z+"> <"+Z+"> ]"),Ae(">>")},Co=f.__private__.putHeader=function(){Ae("%PDF-"+g),Ae("%ºß¬à")},mu=f.__private__.putXRef=function(){var et="0000000000";Ae("xref"),Ae("0 "+(ue+1)),Ae("0000000000 65535 f ");for(var Gt=1;Gt<=ue;Gt++)typeof be[Gt]=="function"?Ae((et+be[Gt]()).slice(-10)+" 00000 n "):be[Gt]!==void 0?Ae((et+be[Gt]).slice(-10)+" 00000 n "):Ae("0000000000 00000 n ")},cc=f.__private__.buildDocument=function(){var et;ue=0,ke=0,Ee=[],be=[],Ie=[],Lr=bn(),la=bn(),Se(Ee),dn.publish("buildDocument"),Co(),ii(),function(){dn.publish("putAdditionalObjects");for(var Es=0;Es"),Ae("/O <"+gc.toHexString(gc.O)+">"),Ae("/P "+gc.P),Ae(">>"),Ae("endobj")),ea(),pc();var Gt=ke;return mu(),ml(),Ae("startxref"),Ae(""+Gt),Ae("%%EOF"),Se(Fe[ce]),Ee.join(` `)},nd=f.__private__.getBlob=function(et){return new Blob([qe(et)],{type:"application/pdf"})},Dr=function(et){for(;et.firstChild;)et.removeChild(et.firstChild)},Hi=function(et){var Gt,Es=et.document,on=Es.documentElement,en=Es.head,tr=Es.body;return en||(en=Es.createElement("head"),on.appendChild(en)),tr||(tr=Es.createElement("body"),on.appendChild(tr)),Dr(en),Dr(tr),(Gt=Es.createElement("style")).appendChild(Es.createTextNode("html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}")),en.appendChild(Gt),{document:Es,body:tr}},zc=f.output=f.__private__.output=(Sn=function(et,Gt){switch(typeof(Gt=Gt||{})=="string"?Gt={filename:Gt}:Gt.filename=Gt.filename||"generated.pdf",et){case void 0:return cc();case"save":f.save(Gt.filename);break;case"arraybuffer":return qe(cc());case"blob":return nd(cc());case"bloburi":case"bloburl":if(Dc.URL!==void 0&&typeof Dc.URL.createObjectURL=="function")return Dc.URL&&Dc.URL.createObjectURL(nd(cc()))||void 0;yf.warn("bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.");break;case"datauristring":case"dataurlstring":var Es="",on=cc();try{Es=v4t(on)}catch{Es=v4t(unescape(encodeURIComponent(on)))}return"data:application/pdf;filename="+encodeURIComponent(Gt.filename)+";base64,"+Es;case"pdfobjectnewwindow":if(Object.prototype.toString.call(Dc)==="[object Window]"){var en="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js",tr=!Gt.pdfObjectUrl;tr||(en=Gt.pdfObjectUrl);var sr=Dc.open();if(sr!==null){var Xr=Hi(sr),sa=Xr.document.createElement("script"),$a=this;sa.src=en,tr&&(sa.integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==",sa.crossOrigin="anonymous"),sa.onload=function(){sr.PDFObject.embed($a.output("dataurlstring"),Gt)},Xr.body.appendChild(sa)}return sr}throw new Error("The option pdfobjectnewwindow just works in a browser-environment.");case"pdfjsnewwindow":if(Object.prototype.toString.call(Dc)==="[object Window]"){var Na=Gt.pdfJsUrl||"examples/PDF.js/web/viewer.html",La=Dc.open();if(La!==null){var eo=Hi(La),xo=eo.document.createElement("iframe"),io=Na.indexOf("?")===-1?"?":"&";$a=this,xo.id="pdfViewer",xo.width="500px",xo.height="400px",xo.src=Na+io+"file=&downloadName="+encodeURIComponent(Gt.filename),xo.onload=function(){La.document.title=Gt.filename,xo.contentWindow.PDFViewerApplication.open($a.output("bloburl"))},eo.body.appendChild(xo)}return La}throw new Error("The option pdfjsnewwindow just works in a browser-environment.");case"dataurlnewwindow":if(Object.prototype.toString.call(Dc)!=="[object Window]")throw new Error("The option dataurlnewwindow just works in a browser-environment.");var Lo=Dc.open();if(Lo!==null){var Ul=Hi(Lo),fo=Ul.document.createElement("iframe");fo.src=this.output("datauristring",Gt),Ul.body.appendChild(fo),Lo.document.title=Gt.filename}if(Lo||typeof safari>"u")return Lo;break;case"datauri":case"dataurl":return Dc.document.location.href=this.output("datauristring",Gt);default:return null}},Sn.foo=function(){try{return Sn.apply(this,arguments)}catch(Es){var et=Es.stack||"";~et.indexOf(" at ")&&(et=et.split(" at ")[1]);var Gt="Error in function "+et.split(` `)[0].split("<")[0]+": "+Es.message;if(!Dc.console)throw new Error(Gt);Dc.console.error(Gt,Es),Dc.alert&&alert(Gt)}},Sn.foo.bar=Sn,Sn.foo),Bc=function(et){return Array.isArray(Ks)===!0&&Ks.indexOf(et)>-1};switch(r){case"pt":as=1;break;case"mm":as=72/25.4;break;case"cm":as=72/2.54;break;case"in":as=72;break;case"px":as=Bc("px_scaling")==1?.75:96/72;break;case"pc":case"em":as=12;break;case"ex":as=6;break;default:if(typeof r!="number")throw new Error("Invalid unit: "+r);as=r}var gc=null;te(),ae();var $l=f.__private__.getPageInfo=f.getPageInfo=function(et){if(isNaN(et)||et%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfo");return{objId:vs[et].objId,pageNumber:et,pageContext:vs[et]}},sg=f.__private__.getPageInfoByObjId=function(et){if(isNaN(et)||et%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");for(var Gt in vs)if(vs[Gt].objId===et)break;return $l(Gt)},Mx=f.__private__.getCurrentPageInfo=f.getCurrentPageInfo=function(){return{objId:vs[ce].objId,pageNumber:ce,pageContext:vs[ce]}};f.addPage=function(){return Yr.apply(this,arguments),this},f.setPage=function(){return Th.apply(this,arguments),Se.call(this,Fe[ce]),this},f.insertPage=function(et){return this.addPage(),this.movePage(ce,et),this},f.movePage=function(et,Gt){var Es,on;if(et>Gt){Es=Fe[et],on=vs[et];for(var en=et;en>Gt;en--)Fe[en]=Fe[en-1],vs[en]=vs[en-1];Fe[Gt]=Es,vs[Gt]=on,this.setPage(Gt)}else if(et0&&(typeof et=="string"?et=io.splitTextToSize(et,Na):Object.prototype.toString.call(et)==="[object Array]"&&(et=et.reduce(function(Ro,kl){return Ro.concat(io.splitTextToSize(kl,Na))},[]))),tr={text:et,x:Gt,y:Es,options:on,mutex:{pdfEscape:Ho,activeFontKey:Ht,fonts:is,activeFontSize:Ve}},dn.publish("preProcessText",tr),et=tr.text,Xr=(on=tr.options).angle,xo instanceof Hs==0&&Xr&&typeof Xr=="number"){Xr*=Math.PI/180,on.rotationDirection===0&&(Xr=-Xr),S===w&&(Xr=-Xr);var el=Math.cos(Xr),zo=Math.sin(Xr);xo=new Hs(el,zo,-zo,el,0,0)}else Xr&&Xr instanceof Hs&&(xo=Xr);S!==w||xo||(xo=Ur),($a=on.charSpace||Nt)!==void 0&&(fo+=P(W($a))+` Tc `,this.setCharSpace(this.getCharSpace()||0)),(eo=on.horizontalScale)!==void 0&&(fo+=P(100*eo)+` Tz `),on.lang;var Pc=-1,Eu=on.renderingMode!==void 0?on.renderingMode:on.stroke,iu=io.internal.getCurrentPageInfo().pageContext;switch(Eu){case 0:case!1:case"fill":Pc=0;break;case 1:case!0:case"stroke":Pc=1;break;case 2:case"fillThenStroke":Pc=2;break;case 3:case"invisible":Pc=3;break;case 4:case"fillAndAddForClipping":Pc=4;break;case 5:case"strokeAndAddPathForClipping":Pc=5;break;case 6:case"fillThenStrokeAndAddToPathForClipping":Pc=6;break;case 7:case"addToPathForClipping":Pc=7}var dm=iu.usedRenderingMode!==void 0?iu.usedRenderingMode:-1;Pc!==-1?fo+=Pc+` Tr `:dm!==-1&&(fo+=`0 Tr `),Pc!==-1&&(iu.usedRenderingMode=Pc),sa=on.align||"left";var Ad,fu=Ve*nl,Zc=io.internal.pageSize.getWidth(),rd=is[Ht];$a=on.charSpace||Nt,Na=on.maxWidth||0,La=Object.assign({autoencode:!0,noBOM:!0},on.flags);var ih=[],Pf=function(Ro){return io.getStringUnitWidth(Ro,{font:rd,charSpace:$a,fontSize:Ve,doKerning:!1})*Ve/Pl};if(Object.prototype.toString.call(et)==="[object Array]"){var Od;sr=au(et),sa!=="left"&&(Ad=sr.map(Pf));var ad,Ph=0;if(sa==="right"){Gt-=Ad[0],et=[],Ca=sr.length;for(var Hu=0;Hu0?(Na-Ad[Xi])/Ap:0;Xi":")"),ya=parseFloat(sr[Gu][1]),Ky=parseFloat(sr[Gu][2]);break;case 0:Ci=(Ul?"<":"(")+sr[Gu]+(Ul?">":")"),ya=Vh(Gt),Ky=cf(Es)}ih!==void 0&&ih[Gu]!==void 0&&(Om=ih[Gu]+` Tw `),Gu===0?et.push(Om+Ix(ya,Ky,xo)+Ci):Wg===0?et.push(Om+Ci):Wg===1&&et.push(Om+Ix(ya,Ky,xo)+Ci)}et=Wg===0?et.join(` Tj T* `):et.join(` Tj `),et+=` Tj `;var kc=`BT /`;return kc+=Ht+" "+Ve+` Tf `,kc+=P(Ve*nl)+` TL `,kc+=We+` `,kc+=fo,kc+=et,Ae(kc+="ET"),m[Ht]=!0,io};var Yo=f.__private__.clip=f.clip=function(et){return Ae(et==="evenodd"?"W*":"W"),this};f.clipEvenOdd=function(){return Yo("evenodd")},f.__private__.discardPath=f.discardPath=function(){return Ae("n"),this};var Mc=f.__private__.isValidStyle=function(et){var Gt=!1;return[void 0,null,"S","D","F","DF","FD","f","f*","B","B*","n"].indexOf(et)!==-1&&(Gt=!0),Gt};f.__private__.setDefaultPathOperation=f.setDefaultPathOperation=function(et){return Mc(et)&&(d=et),this};var Mh=f.__private__.getStyle=f.getStyle=function(et){var Gt=d;switch(et){case"D":case"S":Gt="S";break;case"F":Gt="f";break;case"FD":case"DF":Gt="B";break;case"f":case"f*":case"B":case"B*":Gt=et}return Gt},lm=f.close=function(){return Ae("h"),this};f.stroke=function(){return Ae("S"),this},f.fill=function(et){return Yc("f",et),this},f.fillEvenOdd=function(et){return Yc("f*",et),this},f.fillStroke=function(et){return Yc("B",et),this},f.fillStrokeEvenOdd=function(et){return Yc("B*",et),this};var Yc=function(et,Gt){Tm(Gt)==="object"?No(Gt,et):Ae(et)},ws=function(et){et===null||S===w&&et===void 0||(et=Mh(et),Ae(et))};function Xa(et,Gt,Es,on,en){var tr=new lq(Gt||this.boundingBox,Es||this.xStep,on||this.yStep,this.gState,en||this.matrix);tr.stream=this.stream;var sr=et+"$$"+this.cloneIndex+++"$$";return Wn(sr,tr),tr}var No=function(et,Gt){var Es=gs[et.key],on=yt[Es];if(on instanceof KO)Ae("q"),Ae(Ba(Gt)),on.gState&&f.setGState(on.gState),Ae(et.matrix.toString()+" cm"),Ae("/"+Es+" sh"),Ae("Q");else if(on instanceof lq){var en=new Hs(1,0,0,-1,0,gr());et.matrix&&(en=en.multiply(et.matrix||Ur),Es=Xa.call(on,et.key,et.boundingBox,et.xStep,et.yStep,en).id),Ae("q"),Ae("/Pattern cs"),Ae("/"+Es+" scn"),on.gState&&f.setGState(on.gState),Ae(Gt),Ae("Q")}},Ba=function(et){switch(et){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"}},ao=f.moveTo=function(et,Gt){return Ae(P(W(et))+" "+P(V(Gt))+" m"),this},ko=f.lineTo=function(et,Gt){return Ae(P(W(et))+" "+P(V(Gt))+" l"),this},qi=f.curveTo=function(et,Gt,Es,on,en,tr){return Ae([P(W(et)),P(V(Gt)),P(W(Es)),P(V(on)),P(W(en)),P(V(tr)),"c"].join(" ")),this};f.__private__.line=f.line=function(et,Gt,Es,on,en){if(isNaN(et)||isNaN(Gt)||isNaN(Es)||isNaN(on)||!Mc(en))throw new Error("Invalid arguments passed to jsPDF.line");return S===b?this.lines([[Es-et,on-Gt]],et,Gt,[1,1],en||"S"):this.lines([[Es-et,on-Gt]],et,Gt,[1,1]).stroke()},f.__private__.lines=f.lines=function(et,Gt,Es,on,en,tr){var sr,Xr,sa,$a,Na,La,eo,xo,io,Lo,Ul,fo;if(typeof et=="number"&&(fo=Es,Es=Gt,Gt=et,et=fo),on=on||[1,1],tr=tr||!1,isNaN(Gt)||isNaN(Es)||!Array.isArray(et)||!Array.isArray(on)||!Mc(en)||typeof tr!="boolean")throw new Error("Invalid arguments passed to jsPDF.lines");for(ao(Gt,Es),sr=on[0],Xr=on[1],$a=et.length,Lo=Gt,Ul=Es,sa=0;sa<$a;sa++)(Na=et[sa]).length===2?(Lo=Na[0]*sr+Lo,Ul=Na[1]*Xr+Ul,ko(Lo,Ul)):(La=Na[0]*sr+Lo,eo=Na[1]*Xr+Ul,xo=Na[2]*sr+Lo,io=Na[3]*Xr+Ul,Lo=Na[4]*sr+Lo,Ul=Na[5]*Xr+Ul,qi(La,eo,xo,io,Lo,Ul));return tr&&lm(),ws(en),this},f.path=function(et){for(var Gt=0;Gt>8&255,s>>16&255,s>>24&255)},vU.prototype.toHexString=function(s){return s.split("").map(function(t){return("0"+(255&t.charCodeAt(0)).toString(16)).slice(-2)}).join("")},vU.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 aZe(n,r)}},oPe.prototype.equals=function(s){var t,n="id,objectNumber,equals";if(!s||Tm(s)!==Tm(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 cx=Go.API,got=1,a9=function(s){return s.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},B$=function(s){return s.replace(/\\\\/g,"\\").replace(/\\\(/g,"(").replace(/\\\)/g,")")},dB=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)})},od=function(s){return s.toFixed(2)},CM=function(s){return s.toFixed(5)};cx.__acroform__={};var Gw=function(s,t){s.prototype=Object.create(t.prototype),s.prototype.constructor=s},j4t=function(s){return s*got},x5=function(s){var t=new Uts,n=$o.internal.getHeight(s)||0,r=$o.internal.getWidth(s)||0;return t.BBox=[0,0,Number(od(r)),Number(od(n))],t},ZGn=cx.__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=Nue("3",s,i).height,m=s.multiline?l-i:(l-h)/2,f=m+=2,g=0,x=0,v=0;if(i<=0){t=`(...) Tj `,t+="% Width of Text: "+Nue(t,s,i=12).width+", FieldWidth:"+o+` `;break}for(var y="",b=0,w=0;wl)continue e;y+=a[w][v],S=!0,x=w,w--}else{y=(y+=a[w][v]+" ").substr(y.length-1)==" "?y.substr(0,y.length-1):y;var A=parseInt(w),E=c(A,y,i),I=w>=a.length-1;if(E&&!I){y+=" ",v=0;continue}if(E||I){if(I)x=A;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=A}}for(var P="",R=g;R<=x;R++){var D=a[R];if(s.multiline){if(R===x){P+=D[v]+" ",v=(v+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=Nue(P,s,i).width,s.textAlign){case"right":d=o-u-2;break;case"center":d=(o-u)/2;break;default:d=2}t+=od(d)+" "+od(f)+` Td `,t+="("+a9(P)+`) Tj `,t+=-od(d)+` 0 Td `,f=-(i+2),u=0,g=S?x:x+1,b++,y=""}break}return r.text=t,r.fontSize=i,r},Nue=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}},tWn={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null,isInitialized:!1},sWn=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)},nWn=function(s,t){if(t.scope=s,s.internal!==void 0&&(s.internal.acroformPlugin===void 0||s.internal.acroformPlugin.isInitialized===!1)){if(AC.FieldNum=0,s.internal.acroformPlugin=JSON.parse(JSON.stringify(tWn)),s.internal.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");got=s.internal.scaleFactor,s.internal.acroformPlugin.acroFormDictionaryRoot=new qts,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&&sWn(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=JGn(o.Rect,a)),a.internal.newObjectDeferredBegin(o.objId,!0),o.DA=$o.createDefaultAppearanceStream(o),Tm(o)==="object"&&typeof o.getKeyValueListForStream=="function"&&(c=o.getKeyValueListForStream()),o.Rect=d,o.hasAppearanceStream&&!o.appearanceStreamContent){var u=eWn(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,v){for(var y in x)if(x.hasOwnProperty(y)){var b=y,w=x[y];v.internal.newObjectDeferredBegin(w.objId,!0),Tm(w)==="object"&&typeof w.putStream=="function"&&w.putStream(),delete x[b]}}(a.internal.acroformPlugin.xForms,a)})(n,s)}),s.internal.acroformPlugin.isInitialized=!0}},$ts=cx.__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)),"("+a9(n(s))+")"}},set:function(n){s=n}})};Gw(qts,v4);var AC=function s(){v4.call(this);var t=4;Object.defineProperty(this,"F",{enumerable:!1,configurable:!1,get:function(){return t},set:function(y){if(isNaN(y))throw new Error('Invalid value "'+y+'" for attribute F supplied.');t=y}}),Object.defineProperty(this,"showWhenPrinted",{enumerable:!0,configurable:!0,get:function(){return!!Jx(t,3)},set:function(y){y?this.F=ey(t,3):this.F=ty(t,3)}});var n=0;Object.defineProperty(this,"Ff",{enumerable:!1,configurable:!1,get:function(){return n},set:function(y){if(isNaN(y))throw new Error('Invalid value "'+y+'" for attribute Ff supplied.');n=y}});var r=[];Object.defineProperty(this,"Rect",{enumerable:!1,configurable:!1,get:function(){if(r.length!==0)return r},set:function(y){r=y!==void 0?y:[]}}),Object.defineProperty(this,"x",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[0])?0:r[0]},set:function(y){r[0]=y}}),Object.defineProperty(this,"y",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[1])?0:r[1]},set:function(y){r[1]=y}}),Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[2])?0:r[2]},set:function(y){r[2]=y}}),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[3])?0:r[3]},set:function(y){r[3]=y}});var a="";Object.defineProperty(this,"FT",{enumerable:!0,configurable:!1,get:function(){return a},set:function(y){switch(y){case"/Btn":case"/Tx":case"/Ch":case"/Sig":a=y;break;default:throw new Error('Invalid value "'+y+'" 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 lPe)return;i="FieldObject"+s.FieldNum++}var y=function(b){return b};return this.scope&&(y=this.scope.internal.getEncryptor(this.objId)),"("+a9(y(i))+")"},set:function(y){i=y.toString()}}),Object.defineProperty(this,"fieldName",{configurable:!0,enumerable:!0,get:function(){return i},set:function(y){i=y}});var l="helvetica";Object.defineProperty(this,"fontName",{enumerable:!0,configurable:!0,get:function(){return l},set:function(y){l=y}});var o="normal";Object.defineProperty(this,"fontStyle",{enumerable:!0,configurable:!0,get:function(){return o},set:function(y){o=y}});var c=0;Object.defineProperty(this,"fontSize",{enumerable:!0,configurable:!0,get:function(){return c},set:function(y){c=y}});var d=void 0;Object.defineProperty(this,"maxFontSize",{enumerable:!0,configurable:!0,get:function(){return d===void 0?50/got:d},set:function(y){d=y}});var u="black";Object.defineProperty(this,"color",{enumerable:!0,configurable:!0,get:function(){return u},set:function(y){u=y}});var h="/F1 0 Tf 0 g";Object.defineProperty(this,"DA",{enumerable:!0,configurable:!1,get:function(){if(!(!h||this instanceof lPe||this instanceof N7))return v$e(h,this.objId,this.scope)},set:function(y){y=y.toString(),h=y}});var m=null;Object.defineProperty(this,"DV",{enumerable:!1,configurable:!1,get:function(){if(m)return this instanceof hv==0?v$e(m,this.objId,this.scope):m},set:function(y){y=y.toString(),m=this instanceof hv==0?y.substr(0,1)==="("?B$(y.substr(1,y.length-2)):B$(y):y}}),Object.defineProperty(this,"defaultValue",{enumerable:!0,configurable:!0,get:function(){return this instanceof hv==1?B$(m.substr(1,m.length-1)):m},set:function(y){y=y.toString(),m=this instanceof hv==1?"/"+dB(y):y}});var f=null;Object.defineProperty(this,"_V",{enumerable:!1,configurable:!1,get:function(){if(f)return f},set:function(y){this.V=y}}),Object.defineProperty(this,"V",{enumerable:!1,configurable:!1,get:function(){if(f)return this instanceof hv==0?v$e(f,this.objId,this.scope):f},set:function(y){y=y.toString(),f=this instanceof hv==0?y.substr(0,1)==="("?B$(y.substr(1,y.length-2)):B$(y):y}}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,get:function(){return this instanceof hv==1?B$(f.substr(1,f.length-1)):f},set:function(y){y=y.toString(),f=this instanceof hv==1?"/"+dB(y):y}}),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(y){y=!!y,x=y}}),Object.defineProperty(this,"page",{enumerable:!0,configurable:!0,get:function(){if(g)return g},set:function(y){g=y}}),Object.defineProperty(this,"readOnly",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,1)},set:function(y){y?this.Ff=ey(this.Ff,1):this.Ff=ty(this.Ff,1)}}),Object.defineProperty(this,"required",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,2)},set:function(y){y?this.Ff=ey(this.Ff,2):this.Ff=ty(this.Ff,2)}}),Object.defineProperty(this,"noExport",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,3)},set:function(y){y?this.Ff=ey(this.Ff,3):this.Ff=ty(this.Ff,3)}});var v=null;Object.defineProperty(this,"Q",{enumerable:!0,configurable:!1,get:function(){if(v!==null)return v},set:function(y){if([0,1,2].indexOf(y)===-1)throw new Error('Invalid value "'+y+'" for attribute Q supplied.');v=y}}),Object.defineProperty(this,"textAlign",{get:function(){var y;switch(v){case 0:default:y="left";break;case 1:y="center";break;case 2:y="right"}return y},configurable:!0,enumerable:!0,set:function(y){switch(y){case"right":case 2:v=2;break;case"center":case 1:v=1;break;default:v=0}}})};Gw(AC,v4);var IV=function(){AC.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 $ts(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!!Jx(this.Ff,18)},set:function(n){n?this.Ff=ey(this.Ff,18):this.Ff=ty(this.Ff,18)}}),Object.defineProperty(this,"edit",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,19)},set:function(n){this.combo===!0&&(n?this.Ff=ey(this.Ff,19):this.Ff=ty(this.Ff,19))}}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,20)},set:function(n){n?(this.Ff=ey(this.Ff,20),t.sort()):this.Ff=ty(this.Ff,20)}}),Object.defineProperty(this,"multiSelect",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,22)},set:function(n){n?this.Ff=ey(this.Ff,22):this.Ff=ty(this.Ff,22)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,23)},set:function(n){n?this.Ff=ey(this.Ff,23):this.Ff=ty(this.Ff,23)}}),Object.defineProperty(this,"commitOnSelChange",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,27)},set:function(n){n?this.Ff=ey(this.Ff,27):this.Ff=ty(this.Ff,27)}}),this.hasAppearanceStream=!1};Gw(IV,AC);var LV=function(){IV.call(this),this.fontName="helvetica",this.combo=!1};Gw(LV,IV);var RV=function(){LV.call(this),this.combo=!0};Gw(RV,LV);var A3e=function(){RV.call(this),this.edit=!0};Gw(A3e,RV);var hv=function(){AC.call(this),this.FT="/Btn",Object.defineProperty(this,"noToggleToOff",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,15)},set:function(n){n?this.Ff=ey(this.Ff,15):this.Ff=ty(this.Ff,15)}}),Object.defineProperty(this,"radio",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,16)},set:function(n){n?this.Ff=ey(this.Ff,16):this.Ff=ty(this.Ff,16)}}),Object.defineProperty(this,"pushButton",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,17)},set:function(n){n?this.Ff=ey(this.Ff,17):this.Ff=ty(this.Ff,17)}}),Object.defineProperty(this,"radioIsUnison",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,26)},set:function(n){n?this.Ff=ey(this.Ff,26):this.Ff=ty(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+" ("+a9(n(t[r]))+")");return a.push(">>"),a.join(` `)}},set:function(n){Tm(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="/"+dB(r)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return s.substr(1,s.length-1)},set:function(n){s="/"+dB(n)}})};Gw(hv,AC);var E3e=function(){hv.call(this),this.pushButton=!0};Gw(E3e,hv);var DV=function(){hv.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:[]}})};Gw(DV,hv);var lPe=function(){var s,t;AC.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+" ("+a9(a(r[i]))+")");return l.push(">>"),l.join(` `)},set:function(a){Tm(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="/"+dB(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="/"+dB(i)}}),this.caption="l",this.appearanceState="Off",this._AppearanceType=$o.RadioButton.Circle,this.appearanceStreamContent=this._AppearanceType.createAppearanceStream(this.optionName)};Gw(lPe,AC),DV.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()}},DV.prototype.createOption=function(s){var t=new lPe;return t.Parent=this,t.optionName=s,this.Kids.push(t),rWn.call(this.scope,t),t};var T3e=function(){hv.call(this),this.fontName="zapfdingbats",this.caption="3",this.appearanceState="On",this.value="On",this.textAlign="center",this.appearanceStreamContent=$o.CheckBox.createAppearanceStream()};Gw(T3e,hv);var N7=function(){AC.call(this),this.FT="/Tx",Object.defineProperty(this,"multiline",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,13)},set:function(t){t?this.Ff=ey(this.Ff,13):this.Ff=ty(this.Ff,13)}}),Object.defineProperty(this,"fileSelect",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,21)},set:function(t){t?this.Ff=ey(this.Ff,21):this.Ff=ty(this.Ff,21)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,23)},set:function(t){t?this.Ff=ey(this.Ff,23):this.Ff=ty(this.Ff,23)}}),Object.defineProperty(this,"doNotScroll",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,24)},set:function(t){t?this.Ff=ey(this.Ff,24):this.Ff=ty(this.Ff,24)}}),Object.defineProperty(this,"comb",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,25)},set:function(t){t?this.Ff=ey(this.Ff,25):this.Ff=ty(this.Ff,25)}}),Object.defineProperty(this,"richText",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,26)},set:function(t){t?this.Ff=ey(this.Ff,26):this.Ff=ty(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}})};Gw(N7,AC);var M3e=function(){N7.call(this),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,get:function(){return!!Jx(this.Ff,14)},set:function(s){s?this.Ff=ey(this.Ff,14):this.Ff=ty(this.Ff,14)}}),this.password=!0};Gw(M3e,N7);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=x5(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=iZe(s,s.caption);return n.push("0.749023 g"),n.push("0 0 "+od($o.internal.getWidth(s))+" "+od($o.internal.getHeight(s))+" re"),n.push("f"),n.push("BMC"),n.push("q"),n.push("0 0 1 rg"),n.push("/"+r+" "+od(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=x5(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=iZe(s,s.caption);return a.push("1 g"),a.push("0 0 "+od(l)+" "+od(i)+" re"),a.push("f"),a.push("q"),a.push("0 0 1 rg"),a.push("0 0 "+od(l-1)+" "+od(i-1)+" re"),a.push("W"),a.push("n"),a.push("0 g"),a.push("BT"),a.push("/"+n+" "+od(o.fontSize)+" Tf "+r),a.push(o.text),a.push("ET"),a.push("Q"),t.stream=a.join(` `),t},OffPushDown:function(s){var t=x5(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+od($o.internal.getWidth(s))+" "+od($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=x5(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 "+CM($o.internal.getWidth(s)/2)+" "+CM($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=x5(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 "+CM($o.internal.getWidth(s)/2)+" "+CM($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 "+CM($o.internal.getWidth(s)/2)+" "+CM($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=x5(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 "+CM($o.internal.getWidth(s)/2)+" "+CM($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=x5(s);t.scope=s.scope;var n=[],r=$o.internal.calculateCross(s);return n.push("q"),n.push("1 1 "+od($o.internal.getWidth(s)-2)+" "+od($o.internal.getHeight(s)-2)+" re"),n.push("W"),n.push("n"),n.push(od(r.x1.x)+" "+od(r.x1.y)+" m"),n.push(od(r.x2.x)+" "+od(r.x2.y)+" l"),n.push(od(r.x4.x)+" "+od(r.x4.y)+" m"),n.push(od(r.x3.x)+" "+od(r.x3.y)+" l"),n.push("s"),n.push("Q"),t.stream=n.join(` `),t},YesPushDown:function(s){var t=x5(s);t.scope=s.scope;var n=$o.internal.calculateCross(s),r=[];return r.push("0.749023 g"),r.push("0 0 "+od($o.internal.getWidth(s))+" "+od($o.internal.getHeight(s))+" re"),r.push("f"),r.push("q"),r.push("1 1 "+od($o.internal.getWidth(s)-2)+" "+od($o.internal.getHeight(s)-2)+" re"),r.push("W"),r.push("n"),r.push(od(n.x1.x)+" "+od(n.x1.y)+" m"),r.push(od(n.x2.x)+" "+od(n.x2.y)+" l"),r.push(od(n.x4.x)+" "+od(n.x4.y)+" m"),r.push(od(n.x3.x)+" "+od(n.x3.y)+" l"),r.push("s"),r.push("Q"),t.stream=r.join(` `),t},OffPushDown:function(s){var t=x5(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+od($o.internal.getWidth(s))+" "+od($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 Tm(s)==="object"&&(t=j4t(s.Rect[2])),t},$o.internal.getHeight=function(s){var t=0;return Tm(s)==="object"&&(t=j4t(s.Rect[3])),t};var rWn=cx.addField=function(s){if(nWn(this,s),!(s instanceof AC))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};cx.AcroFormChoiceField=IV,cx.AcroFormListBox=LV,cx.AcroFormComboBox=RV,cx.AcroFormEditBox=A3e,cx.AcroFormButton=hv,cx.AcroFormPushButton=E3e,cx.AcroFormRadioButton=DV,cx.AcroFormCheckBox=T3e,cx.AcroFormTextField=N7,cx.AcroFormPasswordField=M3e,cx.AcroFormAppearance=$o,cx.AcroForm={ChoiceField:IV,ListBox:LV,ComboBox:RV,EditBox:A3e,Button:hv,PushButton:E3e,RadioButton:DV,CheckBox:T3e,TextField:N7,PasswordField:M3e,Appearance:$o},Go.AcroForm={ChoiceField:IV,ListBox:LV,ComboBox:RV,EditBox:A3e,Button:hv,PushButton:E3e,RadioButton:DV,CheckBox:T3e,TextField:N7,PasswordField:M3e,Appearance:$o};Go.AcroForm;function Vts(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,Z,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,le=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 v=0,y=n,b="",w=0;for(v=0;v>"),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,v=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 y=d.maxWidth;y>0?typeof c=="string"?c=this.splitTextToSize(c,y):Object.prototype.toString.call(c)==="[object Array]"&&(c=c.reduce(function(w,S){return w.concat(v.splitTextToSize(S,y))},[])):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,v,y=[],b=[],w=[],S={},A={},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=y=Object.keys(u[0]),w=y.map(function(){return"left"});else if(Array.isArray(h)&&Tm(h[0])==="object")for(y=h.map(function(re){return re.name}),b=h.map(function(re){return re.prompt||re.name||""}),w=h.map(function(re){return re.align||"left"}),f=0;f0&&this.setTableHeaderRow(m),this.setFont(void 0,"normal"),n=!1}}(Go.API);var Hts={italic:["italic","oblique","normal"],oblique:["oblique","italic","normal"],normal:["normal","oblique","italic"]},Gts=["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],oZe=Vts(Gts),Wts=[100,200,300,400,500,600,700,800,900],aWn=Vts(Wts);function b$e(s){var t=s.family.replace(/"|'/g,"").toLowerCase(),n=function(i){return Hts[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 oZe[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 N4t(s,t,n,r){var a;for(a=n;a>=0&&a=0&&a>>1)&255}return a}function R4t(s,t,n){var r=s.length,a=[];a[0]=4;for(var i=0;i>i&l}function D4t(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,Kts(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 v=s[t++]|s[t++]<<8,y=s[t++]|s[t++]<<8,b=s[t++]|s[t++]<<8,w=s[t++]|s[t++]<<8,S=s[t++],A=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:v,y,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:!!A,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 Z=new Uint8Array(G);F4t(s,V.data_offset,Z,G);var X=V.palette_offset,ae=V.transparent_index;ae===null&&(ae=256);var le=V.width,re=n-le,te=le,J=4*(V.y*n+V.x),ce=4*((V.y+V.height)*n+V.x),ve=J,fe=4*re;V.interlaced===!0&&(fe+=4*n*7);for(var ue=8,be=0,Ee=Z.length;be=ce&&(fe=4*re+4*n*(ue-1),ve=J+(le+re)*(ue<<1),ue>>=1)),ke===ae)ve+=4;else{var Ie=s[X+3*ke],Fe=s[X+3*ke+1],Ne=s[X+3*ke+2];W[ve++]=Ne,W[ve++]=Fe,W[ve++]=Ie,W[ve++]=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 Z=new Uint8Array(G);F4t(s,V.data_offset,Z,G);var X=V.palette_offset,ae=V.transparent_index;ae===null&&(ae=256);var le=V.width,re=n-le,te=le,J=4*(V.y*n+V.x),ce=4*((V.y+V.height)*n+V.x),ve=J,fe=4*re;V.interlaced===!0&&(fe+=4*n*7);for(var ue=8,be=0,Ee=Z.length;be=ce&&(fe=4*re+4*n*(ue-1),ve=J+(le+re)*(ue<<1),ue>>=1)),ke===ae)ve+=4;else{var Ie=s[X+3*ke],Fe=s[X+3*ke+1],Ne=s[X+3*ke+2];W[ve++]=Ie,W[ve++]=Fe,W[ve++]=Ne,W[ve++]=255}--te}}}function F4t(s,t,n,r){for(var a=s[t++],i=1<>=c,u-=c,v!==i){if(v===l)break;for(var y=vi;)w=g[w]>>8,++b;var S=w;if(m+b+(y!==v?1:0)>r)return void yf.log("Warning, gif stream longer than expected.");n[m++]=S;var A=m+=b;for(y!==v&&(n[m++]=S),w=y;b--;)w=g[w],n[--A]=255&w,w>>=8;x!==null&&o<4096&&(g[o++]=x<<8|S,o>=d+1&&c<12&&(++c,d=d<<1|1)),x=v}else o=l+1,d=(1<<(c=a+1))-1,x=null}return m!==r&&yf.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 j$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=[],v=0,y=7,b=new Array(64),w=new Array(64),S=new Array(64),A=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 Z(J,ce){for(var ve=0,fe=0,ue=new Array,be=1;be<=16;be++){for(var Ee=1;Ee<=J[be];Ee++)ue[ce[fe]]=[],ue[ce[fe]][0]=ve,ue[ce[fe]][1]=be,fe++,ve++;ve*=2}return ue}function X(J){for(var ce=J[0],ve=J[1]-1;ve>=0;)ce&1<>8&255),ae(255&J)}function re(J,ce,ve,fe,ue){for(var be,Ee=ue[0],ke=ue[240],Ie=function(Ve,ht){var Qe,at,rt,Ke,Je,ft,gt,es,Ht,as,bs=0;for(Ht=0;Ht<8;++Ht){Qe=Ve[bs],at=Ve[bs+1],rt=Ve[bs+2],Ke=Ve[bs+3],Je=Ve[bs+4],ft=Ve[bs+5],gt=Ve[bs+6];var Ut=Qe+(es=Ve[bs+7]),Ft=Qe-es,is=at+gt,jt=at-gt,zs=rt+ft,yt=rt-ft,gs=Ke+Je,Ss=Ke-Je,Ds=Ut+gs,Bt=Ut-gs,zt=is+zs,vs=is-zs;Ve[bs]=Ds+zt,Ve[bs+4]=Ds-zt;var dn=.707106781*(vs+Bt);Ve[bs+2]=Bt+dn,Ve[bs+6]=Bt-dn;var Ks=.382683433*((Ds=Ss+yt)-(vs=jt+Ft)),Cn=.5411961*Ds+Ks,Rr=1.306562965*vs+Ks,ia=.707106781*(zt=yt+jt),Hs=Ft+ia,Br=Ft-ia;Ve[bs+5]=Br+Cn,Ve[bs+3]=Br-Cn,Ve[bs+1]=Hs+Rr,Ve[bs+7]=Hs-Rr,bs+=8}for(bs=0,Ht=0;Ht<8;++Ht){Qe=Ve[bs],at=Ve[bs+8],rt=Ve[bs+16],Ke=Ve[bs+24],Je=Ve[bs+32],ft=Ve[bs+40],gt=Ve[bs+48];var Ur=Qe+(es=Ve[bs+56]),Wn=Qe-es,Sn=at+gt,Fn=at-gt,bn=rt+ft,xs=rt-ft,Tr=Ke+Je,Lr=Ke-Je,la=Ur+Tr,Xn=Ur-Tr,wr=Sn+bn,Bn=Sn-bn;Ve[bs]=la+wr,Ve[bs+32]=la-wr;var cr=.707106781*(Bn+Xn);Ve[bs+16]=Xn+cr,Ve[bs+48]=Xn-cr;var Pa=.382683433*((la=Lr+xs)-(Bn=Fn+Wn)),ii=.5411961*la+Pa,$i=1.306562965*Bn+Pa,Ln=.707106781*(wr=xs+Fn),xa=Wn+Ln,Ka=Wn-Ln;Ve[bs+40]=Ka+ii,Ve[bs+24]=Ka-ii,Ve[bs+8]=xa+$i,Ve[bs+56]=xa-$i,bs++}for(Ht=0;Ht<64;++Ht)as=Ve[Ht]*ht[Ht],f[Ht]=as>0?as+.5|0:as-.5|0;return f}(J,ce),Fe=0;Fe<64;++Fe)g[I[Fe]]=Ie[Fe];var Ne=g[0]-ve;ve=g[0],Ne==0?X(fe[0]):(X(fe[m[be=32767+Ne]]),X(h[be]));for(var Be=63;Be>0&&g[Be]==0;)Be--;if(Be==0)return X(Ee),ve;for(var Se,Ae=1;Ae<=Be;){for(var Ce=Ae;g[Ae]==0&&Ae<=Be;)++Ae;var qe=Ae-Ce;if(qe>=16){Se=qe>>4;for(var ze=1;ze<=Se;++ze)X(ke);qe&=15}be=32767+g[Ae],X(ue[(qe<<4)+m[be]]),X(h[be]),Ae++}return Be!=63&&X(Ee),ve}function te(J){J=Math.min(Math.max(J,1),100),i!=J&&(function(ce){for(var ve=[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],fe=0;fe<64;fe++){var ue=l((ve[fe]*ce+50)/100);ue=Math.min(Math.max(ue,1),255),o[I[fe]]=ue}for(var be=[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 ke=l((be[Ee]*ce+50)/100);ke=Math.min(Math.max(ke,1),255),c[I[Ee]]=ke}for(var Ie=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],Fe=0,Ne=0;Ne<8;Ne++)for(var Be=0;Be<8;Be++)d[Fe]=1/(o[I[Fe]]*Ie[Ne]*Ie[Be]*8),u[Fe]=1/(c[I[Fe]]*Ie[Ne]*Ie[Be]*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,v=0,y=7,le(65496),le(65504),le(16),ae(74),ae(70),ae(73),ae(70),ae(0),ae(1),ae(1),ae(0),le(1),le(1),ae(0),ae(0),function(){le(65499),le(132),ae(0);for(var at=0;at<64;at++)ae(o[at]);ae(1);for(var rt=0;rt<64;rt++)ae(c[rt])}(),function(at,rt){le(65472),le(17),ae(8),le(rt),le(at),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(){le(65476),le(418),ae(0);for(var at=0;at<16;at++)ae(P[at+1]);for(var rt=0;rt<=11;rt++)ae(R[rt]);ae(16);for(var Ke=0;Ke<16;Ke++)ae(D[Ke+1]);for(var Je=0;Je<=161;Je++)ae(O[Je]);ae(1);for(var ft=0;ft<16;ft++)ae(U[ft+1]);for(var gt=0;gt<=11;gt++)ae(W[gt]);ae(17);for(var es=0;es<16;es++)ae(V[es+1]);for(var Ht=0;Ht<=161;Ht++)ae(G[Ht])}(),le(65498),le(12),ae(3),ae(1),ae(0),ae(2),ae(17),ae(3),ae(17),ae(0),ae(63),ae(0);var ve=0,fe=0,ue=0;v=0,y=7,this.encode.displayName="_encode_";for(var be,Ee,ke,Ie,Fe,Ne,Be,Se,Ae,Ce=J.data,qe=J.width,ze=J.height,Ve=4*qe,ht=0;ht>3)*Ve+(Be=4*(7&Ae)),ht+Se>=ze&&(Ne-=Ve*(ht+1+Se-ze)),be+Be>=Ve&&(Ne-=be+Be-Ve+4),Ee=Ce[Ne++],ke=Ce[Ne++],Ie=Ce[Ne++],b[Ae]=(E[Ee]+E[ke+256|0]+E[Ie+512|0]>>16)-128,w[Ae]=(E[Ee+768|0]+E[ke+1024|0]+E[Ie+1280|0]>>16)-128,S[Ae]=(E[Ee+1280|0]+E[ke+1536|0]+E[Ie+1792|0]>>16)-128;ve=re(b,d,ve,t,r),fe=re(w,u,fe,n,a),ue=re(S,u,ue,n,a),be+=32}ht+=8}if(y>=0){var Qe=[];Qe[1]=y+1,Qe[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,cs){t(!(Tt%pt));do Pe[He+(Tt-=pt)]=cs;while(0=cs),512>=cs)var ks=i(512);else if((ks=i(cs))==null)return 0;return function(As,Is,qs,an,Kn,jr){var Qs,ir,yr=Is,ra=1<Qs;++Qs){if(dr[Qs]>1<(bl-=dr[Qs]))return 0;for(;0=Qs;++Qs,Kn<<=1){if(Fi+=bl<<=1,0>(bl-=dr[Qs]))return 0;for(;0Ua&&!(0>=(lr-=dr[Ua]));)++Ua,lr<<=1;ra+=oo=1<<(lr=Ua-qs),As[Is+(Ua=_o&Aa)].g=lr+qs,As[Is+Ua].value=yr-Is-Ua}an.g=Qs-qs,an.value=jr[ir++],O(As,yr+(_o>>qs),Kn,oo,an),_o=D(_o,Qs)}}return Fi!=2*ua[15]-1?0:ra}(Pe,He,pt,Tt,cs,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(rd,V)}function Z(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;fe(Pe)&&(Pe.h=1,Pe.u=0)}function te(Pe,He){if(t(0<=He),!Pe.h&&He<=Pf){var pt=ve(Pe)&ih[He];return Pe.u+=He,re(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 ve(Pe){return Pe.Ra>>>(Pe.u&Od-1)>>>0}function fe(Pe){return t(Pe.bb<=Pe.Sb),Pe.h||Pe.bb==Pe.Sb&&Pe.u>Od}function ue(Pe,He){Pe.u=He,Pe.h=fe(Pe)}function be(Pe){Pe.u>=ad&&(t(Pe.u>=ad),re(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,cs=pt*He>>>8,ks=(Pe.I>>>Tt>cs)+0;for(ks?(pt-=cs,Pe.I-=cs+1<>>0):pt=cs+1,Tt=pt,cs=0;256<=Tt;)cs+=8,Tt>>=8;return Tt=7^cs+Ph[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 Ne(Pe,He){return Pe[He+0]|Pe[He+1]<<8}function Be(Pe,He){return Ne(Pe,He)|Pe[He+2]<<16}function Se(Pe,He){return Ne(Pe,He)|Ne(Pe,He+2)<<16}function Ae(Pe,He){var pt=1<=cs||0>=ks?0:(pt[0]=cs,Tt[0]=ks,1)}function Ve(Pe,He){return Pe+(1<>>He}function ht(Pe,He){return((4278255360&Pe)+(4278255360&He)>>>0&4278255360)+((16711935&Pe)+(16711935&He)>>>0&16711935)>>>0}function Qe(Pe,He){R[He]=function(pt,Tt,cs,ks,As,Is,qs){var an;for(an=0;an>>1)+(Pe&He)>>>0}function Ke(Pe){return 0<=Pe&&256>Pe?Pe:0>Pe?0:255>1))}function ft(Pe,He,pt){return Math.abs(He-pt)-Math.abs(Pe-pt)}function gt(Pe,He,pt,Tt,cs,ks,As){for(Tt=ks[As-1],pt=0;pt>8&255,qs=16711935&(qs=(qs=16711935&As)+((Is<<16)+Is));Tt[cs+ks]=(4278255360&As)+qs>>>0}}function Ht(Pe,He){He.jd=255&Pe,He.hd=Pe>>8&255,He.ud=Pe>>16&255}function as(Pe,He,pt,Tt,cs,ks){var As;for(As=0;As>>8,an=Is,Kn=255&(Kn=(Kn=Is>>>16)+((Pe.jd<<24>>24)*(qs<<24>>24)>>>5));an=255&(an=(an+=(Pe.hd<<24>>24)*(qs<<24>>24)>>>5)+((Pe.ud<<24>>24)*(Kn<<24>>24)>>>5)),cs[ks+As]=(4278255360&Is)+(Kn<<16)+an}}function bs(Pe,He,pt,Tt,cs){R[He]=function(ks,As,Is,qs,an,Kn,jr,Qs,ir){for(qs=jr;qs>ks.b,ir=ks.Ea,yr=ks.K[0],ra=ks.w;if(8>Qs)for(ks=(1<>=Qs}else R["VP8LMapColor"+pt](qs,an,yr,ra,Kn,jr,As,Is,ir)}}function Ut(Pe,He,pt,Tt,cs){for(pt=He+pt;He>16&255,Tt[cs++]=ks>>8&255,Tt[cs++]=255&ks}}function Ft(Pe,He,pt,Tt,cs){for(pt=He+pt;He>16&255,Tt[cs++]=ks>>8&255,Tt[cs++]=255&ks,Tt[cs++]=ks>>24&255}}function is(Pe,He,pt,Tt,cs){for(pt=He+pt;He>16&240|As>>12&15,As=240&As|As>>28&15;Tt[cs++]=ks,Tt[cs++]=As}}function jt(Pe,He,pt,Tt,cs){for(pt=He+pt;He>16&248|As>>13&7,As=As>>5&224|As>>3&31;Tt[cs++]=ks,Tt[cs++]=As}}function zs(Pe,He,pt,Tt,cs){for(pt=He+pt;He>8&255,Tt[cs++]=ks>>16&255}}function yt(Pe,He,pt,Tt,cs,ks){if(ks==0)for(pt=He+pt;He>24|ks[1]>>8&65280|ks[2]<<8&16711680|ks[3]<<24)>>>0),cs+=32;else r(Tt,cs,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==I1||Pe==L1||Pe==Kw||Pe==Yw}function Ds(){this.eb=[],this.size=this.A=this.fb=0}function Bt(){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 zt(){this.Rd=this.height=this.width=this.S=0,this.f={},this.f.RGBA=new Ds,this.f.kb=new Bt,this.sd=null}function vs(){this.width=[0],this.height=[0],this.Pd=[0],this.Qd=[0],this.format=[0]}function dn(){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 Ks(Pe){return alert("todo:WebPSamplerProcessPlane"),Pe.T}function Cn(Pe,He){var pt=Pe.T,Tt=He.ba.f.RGBA,cs=Tt.eb,ks=Tt.fb+Pe.ka*Tt.A,As=ap[He.ba.S],Is=Pe.y,qs=Pe.O,an=Pe.f,Kn=Pe.N,jr=Pe.ea,Qs=Pe.W,ir=He.cc,yr=He.dc,ra=He.Mc,dr=He.Nc,ua=Pe.ka,lr=Pe.ka+Pe.T,Ua=Pe.U,Aa=Ua+1>>1;for(ua==0?As(Is,qs,null,null,an,Kn,jr,Qs,an,Kn,jr,Qs,cs,ks,null,null,Ua):(As(He.ec,He.fc,Is,qs,ir,yr,ra,dr,an,Kn,jr,Qs,cs,ks-Tt.A,cs,ks,Ua),++pt);ua+2pt,cs=pt==sp||pt==lh||pt==Ic||pt==Yg||pt==12||Ss(pt);if(He.memory=null,He.Ib=null,He.Jb=null,He.Nd=null,!Ad(He.Oa,Pe,cs?11:12))return 0;if(cs&&Ss(pt)&&Pl(),Pe.da)alert("todo:use_scaling");else{if(Tt){if(He.Ib=Ks,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=Cn,Pl()}}else alert("todo:EmitYUV");cs&&(He.Jb=Rr,Tt&&fo())}if(Tt&&!Rk){for(Pe=0;256>Pe;++Pe)Dk[Pe]=89858*(Pe-128)+q0>>U0,O_[Pe]=-22014*(Pe-128)+q0,Xw[Pe]=-45773*(Pe-128),F_[Pe]=113618*(Pe-128)+q0>>U0;for(Pe=Dx;Pe>U0,RC[Pe-Dx]=ea(He,255),V2[Pe-Dx]=ea(He+8>>4,15);Rk=1}return 1}function Hs(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 Br(Pe){Pe.ma.memory=null}function Ur(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 Wn(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=ve(pt),cs=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)])>oo.b)*Fi;raUa&&(yo=Ua),(0,Xc[Lc[hf++]>>8&15])(Qs,ir+ +Xl,ua,lr+Xl-Ua,yo-Xl,ua,lr+Xl),Xl=yo}ir+=Ua,lr+=Ua,++ra&_o||(oo+=Fi)}jr!=an.nc&&r(qs,Is-yr,qs,Is+(jr-Kn-1)*yr,yr);break;case 1:for(yr=Qs,dr=ir,Ua=(Qs=an.Ea)-(lr=Qs&~(ua=(ir=1<>an.b)*ra;Kn=cs),0ks.o&&(Tt=ks.o),pt=Tt?pt=0:(cs[0]+=4*ks.v,ks.ka=pt-ks.j,ks.U=ks.va-ks.v,ks.T=Tt-pt,pt=1),pt){if(Is=Is[0],11>(pt=Pe.ca).S){var Kn=pt.f.RGBA,jr=(Tt=pt.S,cs=ks.U,ks=ks.T,an=Kn.eb,Kn.A),Qs=ks;for(Kn=Kn.fb+Pe.Ma*Kn.A;0Tt){var cs=Pe.l.width,ks=pt.ca,As=pt.tb+cs*Tt,Is=Pe.V,qs=Pe.Ba+Pe.c*Tt,an=Pe.gc;t(Pe.ab==1),t(an[0].hc==3),Ed(an[0],Tt,He,Is,qs,ks,As),Xn(pt,Tt,He,ks,As,cs)}Pe.C=Pe.Ma=He}function Bn(Pe,He,pt,Tt,cs,ks,As){var Is=Pe.$/Tt,qs=Pe.$%Tt,an=Pe.m,Kn=Pe.s,jr=pt+Pe.$,Qs=jr;cs=pt+Tt*cs;var ir=pt+Tt*ks,yr=280+Kn.ua,ra=Pe.Pb?Is:16777216,dr=0=ra){var _o=jr-pt;t((ra=Pe).Pb),ra.wd=ra.m,ra.xd=_o,0bl.g?(ue(Aa,Aa.u+bl.g),_o[Fi]=bl.value,Aa=0):(ue(Aa,Aa.u+bl.g-256),t(256<=bl.value),Aa=bl.value),Aa==0&&(Ua=!0)}else Aa=Fn(lr.G[0],lr.H[0],an);if(an.h)break;if(Ua||256>Aa){if(!Ua)if(lr.nd)He[jr]=(lr.qb|Aa<<8)>>>0;else{if(be(an),Ua=Fn(lr.G[1],lr.H[1],an),be(an),_o=Fn(lr.G[2],lr.H[2],an),Fi=Fn(lr.G[3],lr.H[3],an),an.h)break;He[jr]=(Fi<<24|Ua<<16|Aa<<8|_o)>>>0}if(Ua=!1,++jr,++qs>=Tt&&(qs=0,++Is,As!=null&&Is<=ks&&!(Is%16)&&As(Pe,Is),dr!=null))for(;Qs>>dr.Mb]=Aa}else if(280>Aa){if(Aa=Wn(Aa-256,an),_o=Fn(lr.G[4],lr.H[4],an),be(an),_o=Sn(Tt,_o=Wn(_o,an)),an.h)break;if(jr-pt<_o||cs-jr=Tt;)qs-=Tt,++Is,As!=null&&Is<=ks&&!(Is%16)&&As(Pe,Is);if(t(jr<=cs),qs&ua&&(lr=xs(Kn,qs,Is)),dr!=null)for(;Qs>>dr.Mb]=Aa}else{if(!(Aa>>dr.Mb]=Aa;Aa=jr,t(!(Ua>>>(_o=dr).Xa)),He[Aa]=_o.X[Ua],Ua=!0}Ua||t(an.h==fe(an))}if(Pe.Pb&&an.h&&jrks?ks:Is),Pe.a=0,Pe.$=jr-pt}return 1}return Pe.a=3,0}function cr(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 Xr;return Pe==null?null:(Pe.a=0,Pe.xb=S3,gs("Predictor","VP8LPredictors"),gs("Predictor","VP8LPredictors_C"),gs("PredictorAdd","VP8LPredictorsAdd"),gs("PredictorAdd","VP8LPredictorsAdd_C"),dd=es,vd=as,Ap=Ut,Dv=Ft,Px=is,ya=jt,Ky=zs,R.VP8LMapColor32b=Xi,R.VP8LMapColor8b=ou,Pe)}function ii(Pe,He,pt,Tt,cs){var ks=1,As=[Pe],Is=[He],qs=Tt.m,an=Tt.s,Kn=null,jr=0;e:for(;;){if(pt)for(;ks&&te(qs,1);){var Qs=As,ir=Is,yr=Tt,ra=1,dr=yr.m,ua=yr.gc[yr.ab],lr=te(dr,2);if(yr.Oc&1<=yr.ab),lr){case 0:case 1:ua.b=te(dr,3)+2,ra=ii(Ve(ua.Ea,ua.b),Ve(ua.nc,ua.b),0,yr,ua.K),ua.K=ua.K[0];break;case 3:var Ua,Aa=te(dr,8)+1,_o=16>oo.b),hf=i(Lc);if(hf==null)Ua=0;else{var Xl=oo.K[0],yo=oo.w;for(hf[0]=oo.K[0][0],Fi=1;Fi<1*bl;++Fi)hf[Fi]=ht(Xl[yo+Fi],hf[Fi-1]);for(;Fi<4*Lc;++Fi)hf[Fi]=0;oo.K[0]=null,oo.K[0]=hf,Ua=1}}ra=Ua;break;case 2:break;default:t(0)}ks=ra}}if(As=As[0],Is=Is[0],ks&&te(qs,1)&&!(ks=1<=(jr=te(qs,4))&&11>=jr)){Tt.a=3;break e}var vi;if(vi=ks)t:{var hm,To,Ql,$c=Tt,If=As,rg=Is,Yd=jr,ag=pt,Lh=$c.m,mf=$c.s,ud=[null],lu=1,ch=0,cu=np[Yd];s:for(;;){if(ag&&te(Lh,1)){var Lf=te(Lh,3)+2,ip=Ve(If,Lf),dh=Ve(rg,Lf),vh=ip*dh;if(!ii(ip,dh,0,$c,ud))break s;for(ud=ud[0],mf.xc=Lf,hm=0;hm>8&65535;ud[hm]=xc,xc>=lu&&(lu=xc+1)}}if(Lh.h)break s;for(To=0;5>To;++To){var Rh=Pb[To];!To&&0=Rf),Jg=Tp;var Mp=i(ch);if(Jg==null||Mp==null||Bm==null){$c.a=1;break s}var ex=Bm;for(hm=Ql=0;hmTo;++To){Rh=Pb[To],ff[To]=ex,Td[To]=Ql,!To&&0Yy)break n}else Ox=Yy;for($1=0;$1q1)zk[$1++]=q1,q1!=0&&(lp=q1);else{var C3=q1==16,Bk=q1-16,VT=Mk[Bk],Bv=te(Zy,D_[Bk])+VT;if($1+Bv>Yy)break n;for(var $v=C3?lp:0;0=To){var V0,$_=Mp[0];for(V0=1;V0$_&&($_=Mp[V0]);bd+=$_}}if(Zd.nd=Ud,Zd.Qb=0,Ud&&(Zd.qb=(ff[3][Td[3]+0].value<<24|ff[1][Td[1]+0].value<<16|ff[2][Td[2]+0].value)>>>0,Jl==0&&256>ff[0][Td[0]+0].value&&(Zd.Qb=1,Zd.qb+=ff[0][Td[0]+0].value<<8)),Zd.jc=!Zd.Qb&&6>bd,Zd.jc){var og,H0=Zd;for(og=0;og>=bn(Uv,8,dp),Xy>>=bn(H0.G[1][H0.H[1]+Xy],16,dp),Xy>>=bn(H0.G[2][H0.H[2]+Xy],0,dp),bn(H0.G[3][H0.H[3]+Xy],24,dp))}}}mf.vc=ud,mf.Wb=lu,mf.Ya=Jg,mf.yc=Bm,vi=1;break t}vi=0}if(!(ks=vi)){Tt.a=3;break e}if(0Tt+1?[]:0),!(cs.lengthPe?0:Pe>He?He:Pe}function pc(){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 ml(){var Pe=new ro;return Pe!=null&&(Pe.a=0,Pe.sc="OK",Pe.cb=0,Pe.Xb=0,rp||(rp=nd)),Pe}function Co(Pe,He,pt){return Pe.a==0&&(Pe.a=He,Pe.sc=pt,Pe.cb=0),0}function mu(Pe,He,pt){return 3<=pt&&Pe[He+0]==157&&Pe[He+1]==1&&Pe[He+2]==42}function cc(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,cs=He.ha;if(4>cs)return Co(Pe,7,"Truncated header.");var ks=pt[Tt+0]|pt[Tt+1]<<8|pt[Tt+2]<<16,As=Pe.Od;if(As.Rb=!(1&ks),As.td=ks>>1&7,As.yd=ks>>4&1,As.ub=ks>>5,3cs)return Co(Pe,7,"cannot parse picture header");if(!mu(pt,Tt,cs))return Co(Pe,3,"Bad code word");Is.c=16383&(pt[Tt+4]<<8|pt[Tt+3]),Is.Td=pt[Tt+4]>>6,Is.i=16383&(pt[Tt+6]<<8|pt[Tt+5]),Is.Ud=pt[Tt+6]>>6,Tt+=7,cs-=7,Pe.za=Is.c+15>>4,Pe.Ub=Is.i+15>>4,He.width=Is.c,He.height=Is.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(As.ub>cs)return Co(Pe,7,"bad partition length");Z(ks=Pe.m,pt,Tt,As.ub),Tt+=As.ub,cs-=As.ub,As.Rb&&(Is.Ld=ke(ks),Is.Kd=ke(ks)),Is=Pe.Qa;var qs,an=Pe.Pa;if(t(ks!=null),t(Is!=null),Is.Cb=ke(ks),Is.Cb){if(Is.Bb=ke(ks),ke(ks)){for(Is.Fb=ke(ks),qs=0;4>qs;++qs)Is.Zb[qs]=ke(ks)?ae(ks,7):0;for(qs=0;4>qs;++qs)Is.Lb[qs]=ke(ks)?ae(ks,6):0}if(Is.Bb)for(qs=0;3>qs;++qs)an.jb[qs]=ke(ks)?X(ks,8):255}else Is.Bb=0;if(ks.Ka)return Co(Pe,3,"cannot parse segment header");if((Is=Pe.ed).zd=ke(ks),Is.Tb=X(ks,6),Is.wb=X(ks,3),Is.Pc=ke(ks),Is.Pc&&ke(ks)){for(an=0;4>an;++an)ke(ks)&&(Is.vd[an]=ae(ks,6));for(an=0;4>an;++an)ke(ks)&&(Is.od[an]=ae(ks,6))}if(Pe.L=Is.Tb==0?0:Is.zd?1:2,ks.Ka)return Co(Pe,3,"cannot parse filter header");var Kn=cs;if(cs=qs=Tt,Tt=qs+Kn,Is=Kn,Pe.Xb=(1<Is&&(jr=Is),Z(Pe.Jc[+Kn],pt,qs,jr),qs+=jr,Is-=jr,cs+=3}Z(Pe.Jc[+an],pt,qs,Is),pt=qsjr;++jr){if(Kn.Cb){var Qs=Kn.Zb[jr];Kn.Fb||(Qs+=pt)}else{if(0>16,8>ir.Eb[1]&&(ir.Eb[1]=8),ir.Qc[0]=R1[ea(Qs+an,117)],ir.Qc[1]=Zg[ea(Qs+qs,127)],ir.lc=Qs+qs}if(!As.Rb)return Co(Pe,4,"Not a key frame.");for(ke(ks),As=Pe.Pa,pt=0;4>pt;++pt){for(cs=0;8>cs;++cs)for(Tt=0;3>Tt;++Tt)for(Is=0;11>Is;++Is)an=Ie(ks,qT[pt][cs][Tt][Is])?X(ks,8):PC[pt][cs][Tt][Is],As.Wc[pt][cs].Yb[Tt][Is]=an;for(cs=0;17>cs;++cs)As.Xc[pt][cs]=As.Wc[pt][k3[cs]]}return Pe.kc=ke(ks),Pe.kc&&(Pe.Bd=X(ks,8)),Pe.cb=1}function nd(Pe,He,pt,Tt,cs,ks,As){var Is=He[cs].Yb[pt];for(pt=0;16>cs;++cs){if(!Ie(Pe,Is[pt+0]))return cs;for(;!Ie(Pe,Is[pt+1]);)if(Is=He[++cs].Yb[0],pt=0,cs==16)return 16;var qs=He[cs+1].Yb;if(Ie(Pe,Is[pt+2])){var an=Pe,Kn=0;if(Ie(an,(Qs=Is)[(jr=pt)+3]))if(Ie(an,Qs[jr+6])){for(Is=0,jr=2*(Kn=Ie(an,Qs[jr+8]))+(Qs=Ie(an,Qs[jr+9+Kn])),Kn=0,Qs=Rx[jr];Qs[Is];++Is)Kn+=Kn+Ie(an,Qs[Is]);Kn+=3+(8<(an=Pe).b&&Ee(an);var jr,Qs=an.b,ir=(jr=an.Ca>>1)-(an.I>>Qs)>>31;--an.b,an.Ca+=ir,an.Ca|=1,an.I-=(jr+1&ir)<>3),Pe[He+pt+32*Tt]=-256&cs?0>cs?0:255:cs}function zc(Pe,He,pt,Tt,cs,ks){Hi(Pe,He,0,pt,Tt+cs),Hi(Pe,He,1,pt,Tt+ks),Hi(Pe,He,2,pt,Tt-ks),Hi(Pe,He,3,pt,Tt-cs)}function Bc(Pe){return(20091*Pe>>16)+Pe}function gc(Pe,He,pt,Tt){var cs,ks=0,As=i(16);for(cs=0;4>cs;++cs){var Is=Pe[He+0]+Pe[He+8],qs=Pe[He+0]-Pe[He+8],an=(35468*Pe[He+4]>>16)-Bc(Pe[He+12]),Kn=Bc(Pe[He+4])+(35468*Pe[He+12]>>16);As[ks+0]=Is+Kn,As[ks+1]=qs+an,As[ks+2]=qs-an,As[ks+3]=Is-Kn,ks+=4,He++}for(cs=ks=0;4>cs;++cs)Is=(Pe=As[ks+0]+4)+As[ks+8],qs=Pe-As[ks+8],an=(35468*As[ks+4]>>16)-Bc(As[ks+12]),Hi(pt,Tt,0,0,Is+(Kn=Bc(As[ks+4])+(35468*As[ks+12]>>16))),Hi(pt,Tt,1,0,qs+an),Hi(pt,Tt,2,0,qs-an),Hi(pt,Tt,3,0,Is-Kn),ks++,Tt+=32}function $l(Pe,He,pt,Tt){var cs=Pe[He+0]+4,ks=35468*Pe[He+4]>>16,As=Bc(Pe[He+4]),Is=35468*Pe[He+1]>>16;zc(pt,Tt,0,cs+As,Pe=Bc(Pe[He+1]),Is),zc(pt,Tt,1,cs+ks,Pe,Is),zc(pt,Tt,2,cs-ks,Pe,Is),zc(pt,Tt,3,cs-As,Pe,Is)}function sg(Pe,He,pt,Tt,cs){gc(Pe,He,pt,Tt),cs&&gc(Pe,He+16,pt,Tt+4)}function Mx(Pe,He,pt,Tt){Wg(Pe,He+0,pt,Tt,1),Wg(Pe,He+32,pt,Tt+128,1)}function Yo(Pe,He,pt,Tt){var cs;for(Pe=Pe[He+0]+4,cs=0;4>cs;++cs)for(He=0;4>He;++He)Hi(pt,Tt,He,cs,Pe)}function Mc(Pe,He,pt,Tt){Pe[He+0]&&Gu(Pe,He+0,pt,Tt),Pe[He+16]&&Gu(Pe,He+16,pt,Tt+4),Pe[He+32]&&Gu(Pe,He+32,pt,Tt+128),Pe[He+48]&&Gu(Pe,He+48,pt,Tt+128+4)}function Mh(Pe,He,pt,Tt){var cs,ks=i(16);for(cs=0;4>cs;++cs){var As=Pe[He+0+cs]+Pe[He+12+cs],Is=Pe[He+4+cs]+Pe[He+8+cs],qs=Pe[He+4+cs]-Pe[He+8+cs],an=Pe[He+0+cs]-Pe[He+12+cs];ks[0+cs]=As+Is,ks[8+cs]=As-Is,ks[4+cs]=an+qs,ks[12+cs]=an-qs}for(cs=0;4>cs;++cs)As=(Pe=ks[0+4*cs]+3)+ks[3+4*cs],Is=ks[1+4*cs]+ks[2+4*cs],qs=ks[1+4*cs]-ks[2+4*cs],an=Pe-ks[3+4*cs],pt[Tt+0]=As+Is>>3,pt[Tt+16]=an+qs>>3,pt[Tt+32]=As-Is>>3,pt[Tt+48]=an-qs>>3,Tt+=64}function lm(Pe,He,pt){var Tt,cs=He-32,ks=Ui,As=255-Pe[cs-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];ao(Tt>>5,Pe,He)}function qi(Pe,He){var pt,Tt=8;for(pt=0;16>pt;++pt)Tt+=Pe[He-1+32*pt];ao(Tt>>4,Pe,He)}function cm(Pe,He){var pt,Tt=8;for(pt=0;16>pt;++pt)Tt+=Pe[He+pt-32];ao(Tt>>4,Pe,He)}function Zo(Pe,He){ao(128,Pe,He)}function vo(Pe,He,pt){return Pe+2*He+pt+2>>2}function Gg(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 Fl(Pe,He){var pt=Pe[He-1],Tt=Pe[He-1+32],cs=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,cs)),Fe(Pe,He+64,16843009*vo(Tt,cs,ks)),Fe(Pe,He+96,16843009*vo(cs,ks,ks))}function Ol(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 fy(Pe,He){var pt=Pe[He-1+0],Tt=Pe[He-1+32],cs=Pe[He-1+64],ks=Pe[He-1-32],As=Pe[He+0-32],Is=Pe[He+1-32],qs=Pe[He+2-32],an=Pe[He+3-32];Pe[He+0+96]=vo(Tt,cs,Pe[He-1+96]),Pe[He+1+96]=Pe[He+0+64]=vo(pt,Tt,cs),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(As,ks,pt),Pe[He+3+64]=Pe[He+2+32]=Pe[He+1+0]=vo(Is,As,ks),Pe[He+3+32]=Pe[He+2+0]=vo(qs,Is,As),Pe[He+3+0]=vo(an,qs,Is)}function Kd(Pe,He){var pt=Pe[He+1-32],Tt=Pe[He+2-32],cs=Pe[He+3-32],ks=Pe[He+4-32],As=Pe[He+5-32],Is=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,cs),Pe[He+2+0]=Pe[He+1+32]=Pe[He+0+64]=vo(Tt,cs,ks),Pe[He+3+0]=Pe[He+2+32]=Pe[He+1+64]=Pe[He+0+96]=vo(cs,ks,As),Pe[He+3+32]=Pe[He+2+64]=Pe[He+1+96]=vo(ks,As,Is),Pe[He+3+64]=Pe[He+2+96]=vo(As,Is,qs),Pe[He+3+96]=vo(Is,qs,qs)}function Vh(Pe,He){var pt=Pe[He-1+0],Tt=Pe[He-1+32],cs=Pe[He-1+64],ks=Pe[He-1-32],As=Pe[He+0-32],Is=Pe[He+1-32],qs=Pe[He+2-32],an=Pe[He+3-32];Pe[He+0+0]=Pe[He+1+64]=ks+As+1>>1,Pe[He+1+0]=Pe[He+2+64]=As+Is+1>>1,Pe[He+2+0]=Pe[He+3+64]=Is+qs+1>>1,Pe[He+3+0]=qs+an+1>>1,Pe[He+0+96]=vo(cs,Tt,pt),Pe[He+0+64]=vo(Tt,pt,ks),Pe[He+0+32]=Pe[He+1+96]=vo(pt,ks,As),Pe[He+1+32]=Pe[He+2+96]=vo(ks,As,Is),Pe[He+2+32]=Pe[He+3+96]=vo(As,Is,qs),Pe[He+3+32]=vo(Is,qs,an)}function cf(Pe,He){var pt=Pe[He+0-32],Tt=Pe[He+1-32],cs=Pe[He+2-32],ks=Pe[He+3-32],As=Pe[He+4-32],Is=Pe[He+5-32],qs=Pe[He+6-32],an=Pe[He+7-32];Pe[He+0+0]=pt+Tt+1>>1,Pe[He+1+0]=Pe[He+0+64]=Tt+cs+1>>1,Pe[He+2+0]=Pe[He+1+64]=cs+ks+1>>1,Pe[He+3+0]=Pe[He+2+64]=ks+As+1>>1,Pe[He+0+32]=vo(pt,Tt,cs),Pe[He+1+32]=Pe[He+0+96]=vo(Tt,cs,ks),Pe[He+2+32]=Pe[He+1+96]=vo(cs,ks,As),Pe[He+3+32]=Pe[He+2+96]=vo(ks,As,Is),Pe[He+3+64]=vo(As,Is,qs),Pe[He+3+96]=vo(Is,qs,an)}function Wy(Pe,He){var pt=Pe[He-1+0],Tt=Pe[He-1+32],cs=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+cs+1>>1,Pe[He+2+32]=Pe[He+0+64]=cs+ks+1>>1,Pe[He+1+0]=vo(pt,Tt,cs),Pe[He+3+0]=Pe[He+1+32]=vo(Tt,cs,ks),Pe[He+3+32]=Pe[He+1+64]=vo(cs,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 ah(Pe,He){var pt=Pe[He-1+0],Tt=Pe[He-1+32],cs=Pe[He-1+64],ks=Pe[He-1+96],As=Pe[He-1-32],Is=Pe[He+0-32],qs=Pe[He+1-32],an=Pe[He+2-32];Pe[He+0+0]=Pe[He+2+32]=pt+As+1>>1,Pe[He+0+32]=Pe[He+2+64]=Tt+pt+1>>1,Pe[He+0+64]=Pe[He+2+96]=cs+Tt+1>>1,Pe[He+0+96]=ks+cs+1>>1,Pe[He+3+0]=vo(Is,qs,an),Pe[He+2+0]=vo(As,Is,qs),Pe[He+1+0]=Pe[He+3+32]=vo(pt,As,Is),Pe[He+1+32]=Pe[He+3+64]=vo(Tt,pt,As),Pe[He+1+64]=Pe[He+3+96]=vo(cs,Tt,pt),Pe[He+1+96]=vo(ks,cs,Tt)}function gh(Pe,He){var pt;for(pt=0;8>pt;++pt)r(Pe,He+32*pt,Pe,He-32,8)}function xt(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 ct(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 Nt(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 $t(Pe,He){We(128,Pe,He)}function Wt(Pe,He,pt){var Tt=Pe[He-pt],cs=Pe[He+0],ks=3*(cs-Tt)+Ih[1020+Pe[He-2*pt]-Pe[He+pt]],As=yh[112+(ks+4>>3)];Pe[He-pt]=Ui[255+Tt+yh[112+(ks+3>>3)]],Pe[He+0]=Ui[255+cs-As]}function js(Pe,He,pt,Tt){var cs=Pe[He+0],ks=Pe[He+pt];return um[255+Pe[He-2*pt]-Pe[He-pt]]>Tt||um[255+ks-cs]>Tt}function Ts(Pe,He,pt,Tt){return 4*um[255+Pe[He-pt]-Pe[He+0]]+um[255+Pe[He-2*pt]-Pe[He+pt]]<=Tt}function Ns(Pe,He,pt,Tt,cs){var ks=Pe[He-3*pt],As=Pe[He-2*pt],Is=Pe[He-pt],qs=Pe[He+0],an=Pe[He+pt],Kn=Pe[He+2*pt],jr=Pe[He+3*pt];return 4*um[255+Is-qs]+um[255+As-an]>Tt?0:um[255+Pe[He-4*pt]-ks]<=cs&&um[255+ks-As]<=cs&&um[255+As-Is]<=cs&&um[255+jr-Kn]<=cs&&um[255+Kn-an]<=cs&&um[255+an-qs]<=cs}function Ms(Pe,He,pt,Tt){var cs=2*Tt+1;for(Tt=0;16>Tt;++Tt)Ts(Pe,He+Tt,pt,cs)&&Wt(Pe,He+Tt,pt)}function hn(Pe,He,pt,Tt){var cs=2*Tt+1;for(Tt=0;16>Tt;++Tt)Ts(Pe,He+Tt*pt,1,cs)&&Wt(Pe,He+Tt*pt,1)}function fn(Pe,He,pt,Tt){var cs;for(cs=3;0>7,ua=18*lr+63>>7,lr=9*lr+63>>7;qs[an-3*Kn]=Ui[255+qs[an-3*Kn]+lr],qs[an-2*Kn]=Ui[255+jr+ua],qs[an-Kn]=Ui[255+Qs+dr],qs[an+0]=Ui[255+ir-dr],qs[an+Kn]=Ui[255+yr-ua],qs[an+2*Kn]=Ui[255+ra-lr]}He+=Tt}}function ar(Pe,He,pt,Tt,cs,ks,As,Is){for(ks=2*ks+1;0>3)],ra=yh[112+(ra+3>>3)],dr=yr+1>>1;qs[an-2*Kn]=Ui[255+qs[an-2*Kn]+dr],qs[an-Kn]=Ui[255+jr+ra],qs[an+0]=Ui[255+Qs-yr],qs[an+Kn]=Ui[255+ir-dr]}He+=Tt}}function Jn(Pe,He,pt,Tt,cs,ks){Mn(Pe,He,pt,1,16,Tt,cs,ks)}function er(Pe,He,pt,Tt,cs,ks){Mn(Pe,He,1,pt,16,Tt,cs,ks)}function xr(Pe,He,pt,Tt,cs,ks){var As;for(As=3;0an?0:255:an)&255,an=qs,cs[ks+Is]=Kn}}function eo(Pe,He,pt,Tt){var cs=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 As;if(Pe.ga=new sa,(As=Pe.ga==null)||(As=He.width*He.o,t(Pe.Gb.length==0),Pe.Gb=i(As),Pe.Uc=0,Pe.Gb==null?As=0:(Pe.mb=Pe.Gb,Pe.nb=Pe.Uc,Pe.rc=null,As=1),As=!As),!As){As=Pe.ga;var Is=Pe.Fa,qs=Pe.P,an=Pe.qc,Kn=Pe.mb,jr=Pe.nb,Qs=qs+1,ir=an-1,yr=As.l;if(t(Is!=null&&Kn!=null&&He!=null),Lb[0]=null,Lb[1]=$a,Lb[2]=Na,Lb[3]=La,As.ca=Kn,As.tb=jr,As.c=He.width,As.i=He.height,t(0=an)He=0;else if(As.$a=3&Is[qs+0],As.Z=Is[qs+0]>>2&3,As.Lc=Is[qs+0]>>4&3,qs=Is[qs+0]>>6&3,0>As.$a||1=As.c*As.i;As=!He}if(As)return null;Pe.ga.Lc!=1?Pe.Ga=0:Tt=ks-pt}t(Pe.ga!=null),t(pt+Tt<=ks);e:{if(He=(Is=Pe.ga).c,ks=Is.l.o,Is.$a==0){if(Qs=Pe.rc,ir=Pe.Vc,yr=Pe.Fa,qs=Pe.P+1+pt*He,an=Pe.mb,Kn=Pe.nb+pt*He,t(qs<=Pe.P+Pe.qc),Is.Z!=0)for(t(Lb[Is.Z]!=null),As=0;As=He)He=1;else if(Is.ic||fo(),Is.ic){Is=As.V,Qs=As.Ba,ir=As.c;var ra=As.i,dr=(yr=1,qs=As.$/ir,an=As.$%ir,Kn=As.m,jr=As.s,As.$),ua=ir*ra,lr=ir*He,Ua=jr.wc,Aa=dr(ra=Fn(Aa.G[0],Aa.H[0],Kn)))Is[Qs+dr]=ra,++dr,++an>=ir&&(an=0,++qs<=He&&!(qs%16)&&wr(As,qs));else{if(!(280>ra)){yr=0;break t}ra=Wn(ra-256,Kn);var _o,Fi=Fn(Aa.G[4],Aa.H[4],Kn);if(be(Kn),!(dr>=(Fi=Sn(ir,Fi=Wn(Fi,Kn)))&&ua-dr>=ra)){yr=0;break t}for(_o=0;_o=ir;)an-=ir,++qs<=He&&!(qs%16)&&wr(As,qs);drHe?He:qs);break t}!yr||Kn.h&&dr=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,Is[qs+4*As+1]=Is[qs+4*As+1]*jr>>23,Is[qs+4*As+2]=Is[qs+4*As+2]*jr>>23)}He+=ks}}function io(Pe,He,pt,Tt,cs){for(;0>4)*qs>>16;Pe[He+2*ks+0]=(240&As|As>>4)*qs>>16&240|(15&As|As<<4)*qs>>16>>4&15,Pe[He+2*ks+1]=240&an|Is}He+=cs}}function Lo(Pe,He,pt,Tt,cs,ks,As,Is){var qs,an,Kn=255;for(an=0;an>8}function fo(){Bd=xo,gu=io,R_=Lo,Fv=Ul}function nl(Pe,He,pt){R[Pe]=function(Tt,cs,ks,As,Is,qs,an,Kn,jr,Qs,ir,yr,ra,dr,ua,lr,Ua){var Aa,_o=Ua-1>>1,Fi=Is[qs+0]|an[Kn+0]<<16,bl=jr[Qs+0]|ir[yr+0]<<16;t(Tt!=null);var oo=3*Fi+bl+131074>>2;for(He(Tt[cs+0],255&oo,oo>>16,ra,dr),ks!=null&&(oo=3*bl+Fi+131074>>2,He(ks[As+0],255&oo,oo>>16,ua,lr)),Aa=1;Aa<=_o;++Aa){var Lc=Is[qs+Aa]|an[Kn+Aa]<<16,hf=jr[Qs+Aa]|ir[yr+Aa]<<16,Xl=Fi+Lc+bl+hf+524296,yo=Xl+2*(Lc+bl)>>3;oo=yo+Fi>>1,Fi=(Xl=Xl+2*(Fi+hf)>>3)+Lc>>1,He(Tt[cs+2*Aa-1],255&oo,oo>>16,ra,dr+(2*Aa-1)*pt),He(Tt[cs+2*Aa-0],255&Fi,Fi>>16,ra,dr+(2*Aa-0)*pt),ks!=null&&(oo=Xl+bl>>1,Fi=yo+hf>>1,He(ks[As+2*Aa-1],255&oo,oo>>16,ua,lr+(2*Aa-1)*pt),He(ks[As+2*Aa+0],255&Fi,Fi>>16,ua,lr+(2*Aa+0)*pt)),Fi=Lc,bl=hf}1&Ua||(oo=3*Fi+bl+131074>>2,He(Tt[cs+Ua-1],255&oo,oo>>16,ra,dr+(Ua-1)*pt),ks!=null&&(oo=3*bl+Fi+131074>>2,He(ks[As+Ua-1],255&oo,oo>>16,ua,lr+(Ua-1)*pt)))}}function Pl(){ap[oh]=Zw,ap[sp]=Ik,ap[Kg]=Pr,ap[lh]=LC,ap[Ic]=Xg,ap[Yg]=uf,ap[P1]=D1,ap[I1]=Ik,ap[L1]=LC,ap[Kw]=Xg,ap[Yw]=uf}function Cd(Pe){return Pe&-16384?0>Pe?0:255:Pe>>q2}function au(Pe,He){return Cd((19077*Pe>>8)+(26149*He>>8)-14234)}function Vt(Pe,He,pt){return Cd((19077*Pe>>8)-(6419*He>>8)-(13320*pt>>8)+8708)}function Nn(Pe,He){return Cd((19077*Pe>>8)+(33050*He>>8)-17685)}function nr(Pe,He,pt,Tt,cs){Tt[cs+0]=au(Pe,pt),Tt[cs+1]=Vt(Pe,He,pt),Tt[cs+2]=Nn(Pe,He)}function na(Pe,He,pt,Tt,cs){Tt[cs+0]=Nn(Pe,He),Tt[cs+1]=Vt(Pe,He,pt),Tt[cs+2]=au(Pe,pt)}function Wr(Pe,He,pt,Tt,cs){var ks=Vt(Pe,He,pt);He=ks<<3&224|Nn(Pe,He)>>3,Tt[cs+0]=248&au(Pe,pt)|ks>>5,Tt[cs+1]=He}function Ca(Pe,He,pt,Tt,cs){var ks=240&Nn(Pe,He)|15;Tt[cs+0]=240&au(Pe,pt)|Vt(Pe,He,pt)>>4,Tt[cs+1]=ks}function gi(Pe,He,pt,Tt,cs){Tt[cs+0]=255,nr(Pe,He,pt,Tt,cs+1)}function Ia(Pe,He,pt,Tt,cs){na(Pe,He,pt,Tt,cs),Tt[cs+3]=255}function el(Pe,He,pt,Tt,cs){nr(Pe,He,pt,Tt,cs),Tt[cs+3]=255}function zo(Pe,He,pt){R[Pe]=function(Tt,cs,ks,As,Is,qs,an,Kn,jr){for(var Qs=Kn+(-2&jr)*pt;Kn!=Qs;)He(Tt[cs+0],ks[As+0],Is[qs+0],an,Kn),He(Tt[cs+1],ks[As+0],Is[qs+0],an,Kn+pt),cs+=2,++As,++qs,Kn+=2*pt;1&jr&&He(Tt[cs+0],ks[As+0],Is[qs+0],an,Kn)}}function Pc(Pe,He,pt){return pt==0?Pe==0?He==0?6:5:He==0?4:0:pt}function Eu(Pe,He,pt,Tt,cs){switch(Pe>>>30){case 3:Wg(He,pt,Tt,cs,0);break;case 2:Om(He,pt,Tt,cs);break;case 1:Gu(He,pt,Tt,cs)}}function iu(Pe,He){var pt,Tt,cs=He.M,ks=He.Nb,As=Pe.oc,Is=Pe.pc+40,qs=Pe.oc,an=Pe.pc+584,Kn=Pe.oc,jr=Pe.pc+600;for(pt=0;16>pt;++pt)As[Is+32*pt-1]=129;for(pt=0;8>pt;++pt)qs[an+32*pt-1]=129,Kn[jr+32*pt-1]=129;for(0pt;++pt)r(As,Is+32*pt-4,As,Is+32*pt+12,4);for(pt=-1;8>pt;++pt)r(qs,an+32*pt-4,qs,an+32*pt+4,4),r(Kn,jr+32*pt-4,Kn,jr+32*pt+4,4)}var ir=Pe.Gd,yr=Pe.Hd+Tt,ra=Qs.ad,dr=Qs.Hc;if(0=Pe.za-1?a(ua,lr,ir[yr].y[15],4):r(ua,lr,ir[yr+1].y,0,4)),pt=0;4>pt;pt++)ua[lr+128+pt]=ua[lr+256+pt]=ua[lr+384+pt]=ua[lr+0+pt];for(pt=0;16>pt;++pt,dr<<=2)ua=As,lr=Is+z_[pt],Ep[Qs.Ob[pt]](ua,lr),Eu(dr,ra,16*+pt,ua,lr)}else if(ua=Pc(Tt,cs,Qs.Ob[0]),Ib[ua](As,Is),dr!=0)for(pt=0;16>pt;++pt,dr<<=2)Eu(dr,ra,16*+pt,As,Is+z_[pt]);for(pt=Qs.Gc,ua=Pc(Tt,cs,Qs.Dd),$0[ua](qs,an),$0[ua](Kn,jr),dr=ra,ua=qs,lr=an,255&(Qs=0|pt)&&(170&Qs?Ix(dr,256,ua,lr):kc(dr,256,ua,lr)),Qs=Kn,dr=jr,255&(pt>>=8)&&(170&pt?Ix(ra,320,Qs,dr):kc(ra,320,Qs,dr)),cspt;++pt)r(ir,yr+pt*Pe.R,As,Is+32*pt,16);for(pt=0;8>pt;++pt)r(ra,Qs+pt*Pe.B,qs,an+32*pt,8),r(dr,ua+pt*Pe.B,Kn,jr+32*pt,8)}}function dm(Pe,He,pt,Tt,cs,ks,As,Is,qs){var an=[0],Kn=[0],jr=0,Qs=qs!=null?qs.kd:0,ir=qs??new en;if(Pe==null||12>pt)return 7;ir.data=Pe,ir.w=He,ir.ha=pt,He=[He],pt=[pt],ir.gb=[ir.gb];e:{var yr=He,ra=pt,dr=ir.gb;if(t(Pe!=null),t(ra!=null),t(dr!=null),dr[0]=0,12<=ra[0]&&!n(Pe,yr[0],"RIFF")){if(n(Pe,yr[0]+8,"WEBP")){dr=3;break e}var ua=Se(Pe,yr[0]+4);if(12>ua||4294967286ra[0]-8){dr=7;break e}dr[0]=ua,yr[0]+=12,ra[0]-=12}dr=0}if(dr!=0)return dr;for(ua=0dr[0])dr=7;else{if(!n(lr,ra[0],"VP8X")){if(Se(lr,ra[0]+4)!=10){dr=3;break e}if(18>dr[0]){dr=7;break e}var Fi=Se(lr,ra[0]+8),bl=1+Be(lr,ra[0]+12);if(2147483648<=bl*(lr=1+Be(lr,ra[0]+15))){dr=3;break e}_o!=null&&(_o[0]=Fi),Ua!=null&&(Ua[0]=bl),Aa!=null&&(Aa[0]=lr),ra[0]+=18,dr[0]-=18,oo[0]=1}dr=0}}if(jr=jr[0],yr=yr[0],dr!=0)return dr;if(ra=!!(2&yr),!ua&&jr)return 3;if(ks!=null&&(ks[0]=!!(16&yr)),As!=null&&(As[0]=ra),Is!=null&&(Is[0]=0),As=an[0],yr=Kn[0],jr&&ra&&qs==null){dr=0;break}if(4>pt){dr=7;break}if(ua&&jr||!ua&&!jr&&!n(Pe,He[0],"ALPH")){pt=[pt],ir.na=[ir.na],ir.P=[ir.P],ir.Sa=[ir.Sa];e:{Fi=Pe,dr=He,ua=pt;var oo=ir.gb;Ua=ir.na,Aa=ir.P,_o=ir.Sa,bl=22,t(Fi!=null),t(ua!=null),lr=dr[0];var Lc=ua[0];for(t(Ua!=null),t(_o!=null),Ua[0]=null,Aa[0]=null,_o[0]=0;;){if(dr[0]=lr,ua[0]=Lc,8>Lc){dr=7;break e}var hf=Se(Fi,lr+4);if(4294967286oo){dr=3;break e}if(!n(Fi,lr,"VP8 ")||!n(Fi,lr,"VP8L")){dr=0;break e}if(Lc[0]ua[0])dr=7;else{if(lr||bl){if(oo=Se(oo,Fi+4),12<=Ua&&oo>Ua-12){dr=3;break e}if(Qs&&oo>ua[0]-8){dr=7;break e}Aa[0]=oo,dr[0]+=8,ua[0]-=8,_o[0]=bl}else _o[0]=5<=ua[0]&&oo[Fi+0]==47&&!(oo[Fi+4]>>5),Aa[0]=ua[0];dr=0}if(pt=pt[0],ir.Ja=ir.Ja[0],ir.xa=ir.xa[0],He=He[0],dr!=0)break;if(4294967286pt){dr=7;break}Is=As,Qs=yr,ra=ks,Pe==null||5>pt?Pe=0:5<=pt&&Pe[He+0]==47&&!(Pe[He+4]>>5)?(ua=[0],oo=[0],Ua=[0],le(Aa=new ce,Pe,He,pt),Ur(Aa,ua,oo,Ua)?(Is!=null&&(Is[0]=ua[0]),Qs!=null&&(Qs[0]=oo[0]),ra!=null&&(ra[0]=Ua[0]),Pe=1):Pe=0):Pe=0}else{if(10>pt){dr=7;break}Is=yr,Pe==null||10>pt||!mu(Pe,He+3,pt-3)?Pe=0:(Qs=Pe[He+0]|Pe[He+1]<<8|Pe[He+2]<<16,ra=16383&(Pe[He+7]<<8|Pe[He+6]),Pe=16383&(Pe[He+9]<<8|Pe[He+8]),1&Qs||3<(Qs>>1&7)||!(Qs>>4&1)||Qs>>5>=ir.Ja||!ra||!Pe?Pe=0:(As&&(As[0]=ra),Is&&(Is[0]=Pe),Pe=1))}if(!Pe||(As=As[0],yr=yr[0],jr&&(an[0]!=As||Kn[0]!=yr)))return 3;qs!=null&&(qs[0]=ir,qs.offset=He-qs.w,t(4294967286>He-qs.w),t(qs.offset==qs.ha-pt));break}return dr==0||dr==7&&jr&&qs==null?(ks!=null&&(ks[0]|=ir.na!=null&&0pt||(ks&=-2,As&=-2),0>ks||0>As||0>=Is||0>=qs||ks+Is>Tt||As+qs>cs))return 0;if(He.v=ks,He.j=As,He.va=ks+Is,He.o=As+qs,He.U=Is,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 Zc(Pe,He,pt,Tt){if(Tt==null||0>=Pe||0>=He)return 2;if(pt!=null){if(pt.Da){var cs=pt.cd,ks=pt.bd,As=-2&pt.v,Is=-2&pt.j;if(0>As||0>Is||0>=cs||0>=ks||As+cs>Pe||Is+ks>He)return 2;Pe=cs,He=ks}if(pt.da){if(!ze(Pe,He,cs=[pt.ib],ks=[pt.hb]))return 2;Pe=cs[0],He=ks[0]}}Tt.width=Pe,Tt.height=He;e:{var qs=Tt.width,an=Tt.height;if(Pe=Tt.S,0>=qs||0>=an||!(Pe>=oh&&13>Pe))Pe=2;else{if(0>=Tt.Rd&&Tt.sd==null){As=ks=cs=He=0;var Kn=(Is=qs*Qw[Pe])*an;if(11>Pe||(ks=(an+1)/2*(He=(qs+1)/2),Pe==12&&(As=(cs=qs)*an)),(an=i(Kn+2*ks+As))==null){Pe=1;break e}Tt.sd=an,11>Pe?((qs=Tt.f.RGBA).eb=an,qs.fb=0,qs.A=Is,qs.size=Kn):((qs=Tt.f.kb).y=an,qs.O=0,qs.fa=Is,qs.Fd=Kn,qs.f=an,qs.N=0+Kn,qs.Ab=He,qs.Cd=ks,qs.ea=an,qs.W=0+Kn+ks,qs.Db=He,qs.Ed=ks,Pe==12&&(qs.F=an,qs.J=0+Kn+2*ks),qs.Tc=As,qs.lb=cs)}if(He=1,cs=Tt.S,ks=Tt.width,As=Tt.height,cs>=oh&&13>cs)if(11>cs)Pe=Tt.f.RGBA,He&=(Is=Math.abs(Pe.A))*(As-1)+ks<=Pe.size,He&=Is>=ks*Qw[cs],He&=Pe.eb!=null;else{Pe=Tt.f.kb,Is=(ks+1)/2,Kn=(As+1)/2,qs=Math.abs(Pe.fa),an=Math.abs(Pe.Ab);var jr=Math.abs(Pe.Db),Qs=Math.abs(Pe.lb),ir=Qs*(As-1)+ks;He&=qs*(As-1)+ks<=Pe.Fd,He&=an*(Kn-1)+Is<=Pe.Cd,He=(He&=jr*(Kn-1)+Is<=Pe.Ed)&qs>=ks&an>=Is&jr>=Is,He&=Pe.y!=null,He&=Pe.f!=null,He&=Pe.ea!=null,cs==12&&(He&=Qs>=ks,He&=ir<=Pe.Tc,He&=Pe.F!=null)}else He=0;Pe=He?0:2}}return Pe!=0||pt!=null&&pt.fd&&(Pe=fu(Tt)),Pe}var rd=64,ih=[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],Pf=24,Od=32,ad=8,Ph=[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];Qe("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 rt(rt(Pe,He[pt+1]),He[pt+0])},R.Predictor6=function(Pe,He,pt){return rt(Pe,He[pt-1])},R.Predictor7=function(Pe,He,pt){return rt(Pe,He[pt+0])},R.Predictor8=function(Pe,He,pt){return rt(He[pt-1],He[pt+0])},R.Predictor9=function(Pe,He,pt){return rt(He[pt+0],He[pt+1])},R.Predictor10=function(Pe,He,pt){return rt(rt(Pe,He[pt-1]),rt(He[pt+0],He[pt+1]))},R.Predictor11=function(Pe,He,pt){var Tt=He[pt+0];return 0>=ft(Tt>>24&255,Pe>>24&255,(He=He[pt-1])>>24&255)+ft(Tt>>16&255,Pe>>16&255,He>>16&255)+ft(Tt>>8&255,Pe>>8&255,He>>8&255)+ft(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(Je((Pe=rt(Pe,He[pt+0]))>>24&255,Tt>>24&255)<<24|Je(Pe>>16&255,Tt>>16&255)<<16|Je(Pe>>8&255,Tt>>8&255)<<8|Je(255&Pe,255&Tt))>>>0};var Hu=R.PredictorAdd0;R.PredictorAdd1=gt,Qe("Predictor2","PredictorAdd2"),Qe("Predictor3","PredictorAdd3"),Qe("Predictor4","PredictorAdd4"),Qe("Predictor5","PredictorAdd5"),Qe("Predictor6","PredictorAdd6"),Qe("Predictor7","PredictorAdd7"),Qe("Predictor8","PredictorAdd8"),Qe("Predictor9","PredictorAdd9"),Qe("Predictor10","PredictorAdd10"),Qe("Predictor11","PredictorAdd11"),Qe("Predictor12","PredictorAdd12"),Qe("Predictor13","PredictorAdd13");var zd=R.PredictorAdd2;bs("ColorIndexInverseTransform","MapARGB","32b",function(Pe){return Pe>>8&255},function(Pe){return Pe}),bs("VP8LColorIndexInverseTransformAlpha","MapAlpha","8b",function(Pe){return Pe},function(Pe){return Pe>>8&255});var dd,zl=R.ColorIndexInverseTransform,Xi=R.MapARGB,Ed=R.VP8LColorIndexInverseTransformAlpha,ou=R.MapAlpha,Xc=R.VP8LPredictorsAdd=[];Xc.length=16,(R.VP8LPredictors=[]).length=16,(R.VP8LPredictorsAdd_C=[]).length=16,(R.VP8LPredictors_C=[]).length=16;var vd,Ap,Dv,Px,ya,Ky,Ci,Wg,Om,Ix,Gu,kc,Ro,kl,pu,da,Ao,fl,Qc,ng,Wo,B0,xh,df,Bd,gu,R_,Fv,Lx=i(511),Mb=i(2041),Ww=i(225),zm=i(767),xu=0,Ih=Mb,yh=Ww,Ui=zm,um=Lx,oh=0,sp=1,Kg=2,lh=3,Ic=4,Yg=5,P1=6,I1=7,L1=8,Kw=9,Yw=10,D_=[2,3,7],Mk=[3,3,11],Pb=[280,256,256,256,40],Ov=[0,1,1,1,0],N3=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],U2=[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],np=[2954,2956,2958,2962,2970,2986,3018,3082,3212,3468,3980,5004],Pk=8,R1=[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],Zg=[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],rp=null,Rx=[[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]],$d=[0,1,4,8,5,2,3,6,9,12,13,10,7,11,14,15],zv=[-0,1,-1,2,-2,3,4,6,-3,5,-4,-5,-6,7,-7,8,-8,-9],PC=[[[[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]]]],UT=[[[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]]],qT=[[[[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]]]],k3=[0,1,2,3,6,4,5,6,6,6,6,6,6,6,6,7,0],Ib=[],Ep=[],$0=[],IC=1,S3=2,Lb=[],ap=[];nl("UpsampleRgbLinePair",nr,3),nl("UpsampleBgrLinePair",na,3),nl("UpsampleRgbaLinePair",el,4),nl("UpsampleBgraLinePair",Ia,4),nl("UpsampleArgbLinePair",gi,4),nl("UpsampleRgba4444LinePair",Ca,2),nl("UpsampleRgb565LinePair",Wr,2);var Zw=R.UpsampleRgbLinePair,Pr=R.UpsampleBgrLinePair,Ik=R.UpsampleRgbaLinePair,LC=R.UpsampleBgraLinePair,Xg=R.UpsampleArgbLinePair,uf=R.UpsampleRgba4444LinePair,D1=R.UpsampleRgb565LinePair,U0=16,q0=1<Tt.ca.S||(alert("todo:WebPInitConvertARGBToYUV"),Tt.ca.f.kb.F!=null&&fo()),Tt.Pb&&0(qs=pt.Md)?0:100an;++an)12>(jr=cs.pb[an]).lc&&(jr.ia=qs*DC[0>jr.lc?0:jr.lc]>>3),Kn|=jr.ia;Kn&&(alert("todo:VP8InitRandom"),cs.ia=1)}cs.Ga=pt.Id,100cs.Ga&&(cs.Ga=0)}(function(Qs,ir){if(Qs==null)return 0;if(ir==null)return Co(Qs,2,"NULL VP8Io parameter in VP8Decode().");if(!Qs.cb&&!cc(Qs,ir))return 0;if(t(Qs.cb),ir.ac==null||ir.ac(ir)){ir.ob&&(Qs.L=0);var yr=Qg[Qs.L];if(Qs.L==2?(Qs.yb=0,Qs.zb=0):(Qs.yb=ir.v-yr>>4,Qs.zb=ir.j-yr>>4,0>Qs.yb&&(Qs.yb=0),0>Qs.zb&&(Qs.zb=0)),Qs.Va=ir.o+15+yr>>4,Qs.Hb=ir.va+15+yr>>4,Qs.Hb>Qs.za&&(Qs.Hb=Qs.za),Qs.Va>Qs.Ub&&(Qs.Va=Qs.Ub),0yr;++yr){var dr;if(Qs.Qa.Cb){var ua=Qs.Qa.Lb[yr];Qs.Qa.Fb||(ua+=ra.Tb)}else ua=ra.Tb;for(dr=0;1>=dr;++dr){var lr=Qs.gd[yr][dr],Ua=ua;if(ra.Pc&&(Ua+=ra.vd[0],dr&&(Ua+=ra.od[0])),0<(Ua=0>Ua?0:63>2:Aa>>1)>9-ra.wb&&(Aa=9-ra.wb),1>Aa&&(Aa=1),lr.dd=Aa,lr.tc=2*Ua+Aa,lr.ld=40<=Ua?2:15<=Ua?1:0}else lr.tc=0;lr.La=dr}}}yr=0}else Co(Qs,6,"Frame setup failed"),yr=Qs.a;if(yr=yr==0){if(yr){Qs.$c=0,0Qs.Vb){if(Qs.Vb=0,Qs.Ec=i(lr),Qs.Fc=0,Qs.Ec==null){yr=Co(Qs,1,"no memory during frame initialization.");break t}Qs.Vb=lr}lr=Qs.Ec,Ua=Qs.Fc,Qs.Ac=lr,Qs.Bc=Ua,Ua+=ra,Qs.Gd=l(_o,rh),Qs.Hd=0,Qs.rb=l(Fi+1,ti),Qs.sb=1,Qs.wa=bl?l(bl,Ho):null,Qs.Y=0,Qs.D.Nb=0,Qs.D.wa=Qs.wa,Qs.D.Y=Qs.Y,0=yr;++yr)Lx[255+yr]=0>yr?-yr:yr;for(yr=-1020;1020>=yr;++yr)Mb[1020+yr]=-128>yr?-128:127=yr;++yr)Ww[112+yr]=-16>yr?-16:15=yr;++yr)zm[255+yr]=0>yr?0:255Ql;++Ql){var mf,ud=rg[0+Ql];for(mf=0;4>mf;++mf){ud=UT[$c[If+mf]][ud];for(var lu=zv[Ie(To,ud[0])];0>3;for(lu=0;256>lu;lu+=16)Ql[ag+lu]=vh}Lf=1,ip=If[0]}var xc=15&To.la,Rh=15&Lh.la;for(lu=0;4>lu;++lu){var Bm=1&Rh;for(vh=cu=0;4>vh;++vh)xc=xc>>1|(Bm=(dh=rp($c,ip,dh=Bm+(1&xc),Yd.Sc,Lf,Ql,ag))>Lf)<<7,cu=cu<<2|(3>=4,Rh=Rh>>1|Bm<<7,mf=(mf<<8|cu)>>>0}for(ip=xc,Lf=Rh>>4,ch=0;4>ch;ch+=2){for(cu=0,xc=To.la>>4+ch,Rh=Lh.la>>4+ch,lu=0;2>lu;++lu){for(Bm=1&Rh,vh=0;2>vh;++vh)dh=Bm+(1&xc),xc=xc>>1|(Bm=0<(dh=rp($c,If[2],dh,Yd.Qc,0,Ql,ag)))<<3,cu=cu<<2|(3>=2,Rh=Rh>>1|Bm<<5}ud|=cu<<4*ch,ip|=xc<<4<=yo.zb&&yo.M<=yo.Va,yo.Aa==0)t:{if(Xl.M=yo.M,Xl.uc=To,iu(yo,Xl),hm=1,Xl=(cu=yo.D).Nb,To=(ud=Qg[yo.L])*yo.R,$c=ud/2*yo.B,lu=16*Xl*yo.R,vh=8*Xl*yo.B,If=yo.sa,rg=yo.ta-To+lu,Yd=yo.qa,Ql=yo.ra-$c+vh,ag=yo.Ha,Lh=yo.Ia-$c+vh,Rh=(xc=cu.M)==0,mf=xc>=yo.Va-1,yo.Aa==2&&iu(yo,cu),cu.uc)for(Bm=(dh=yo).D.M,t(dh.D.uc),cu=dh.yb;cuvi.o&&(xc=vi.o),vi.F=null,vi.J=null,yo.Fa!=null&&0>1),vi.W+=yo.B*(ud>>1),vi.F!=null&&(vi.J+=vi.width*ud)),cu>1,vi.W+=vi.v>>1,vi.F!=null&&(vi.J+=vi.v),vi.ka=cu-vi.j,vi.U=vi.va-vi.v,vi.T=xc-cu,hm=vi.put(vi))}Xl+1!=yo.Ic||mf||(r(yo.sa,yo.ta-To,If,rg+16*yo.R,To),r(yo.qa,yo.ra-$c,Yd,Ql+8*yo.B,$c),r(yo.Ha,yo.Ia-$c,ag,Lh+8*yo.B,$c))}if(!hm)return Co(Lc,6,"Output aborted.")}return 1}(Qs,ir)),ir.bc!=null&&ir.bc(ir),yr&=1}return yr?(Qs.cb=0,yr):0})(Pe,Tt)||(He=Pe.a)}}else He=Pe.a}He==0&&As.Oa!=null&&As.Oa.fd&&(He=fu(As.ba))}As=He}ks=As!=0?null:11>ks?Is.f.RGBA.eb:Is.f.kb.y}else ks=null;return ks};var Qw=[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=[],v=new c,y=s,b=function(R,D){var O={},U=0,W=!1,V=0,G=0;if(O.frames=[],!function(J,ce){for(var ve=0;ve<4;ve++)if(J[ce+ve]!="RIFF".charCodeAt(ve))return!0;return!1}(R,D)){for(m(R,D+=4),D+=8;D>1&1}Z!="ANMF"&&(D+=ae)}return O}}(y,0);b.response=y,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 A=0;A'+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 fWn(){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 ve=!1;Object.defineProperty(this,"pageWrapXEnabled",{get:function(){return ve},set:function(Ae){ve=!!Ae}});var fe=!1;Object.defineProperty(this,"pageWrapYEnabled",{get:function(){return fe},set:function(Ae){fe=!!Ae}});var ue=0;Object.defineProperty(this,"posX",{get:function(){return ue},set:function(Ae){isNaN(Ae)||(ue=Ae)}});var be=0;Object.defineProperty(this,"posY",{get:function(){return be},set:function(Ae){isNaN(Ae)||(be=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 ke=0;Object.defineProperty(this,"lastBreak",{get:function(){return ke},set:function(Ae){ke=Ae}});var Ie=[];Object.defineProperty(this,"pageBreaks",{get:function(){return Ie},set:function(Ae){Ie=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 Ne=null,Be=null,Se=null;Object.defineProperty(this,"fontFaces",{get:function(){return Se},set:function(Ae){Ne=null,Be=null,Se=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],Ve=Ce[4];Ce[5];var ht=Ce[6],Qe=/^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i.exec(Ve)[2];Ve=Math.floor(Qe==="px"?parseFloat(Ve)*this.pdf.internal.scaleFactor:Qe==="em"?parseFloat(Ve)*this.pdf.getFontSize():parseFloat(Ve)*this.pdf.internal.scaleFactor),this.pdf.setFontSize(Ve);var at=function(bs){var Ut,Ft,is=[],jt=bs.trim();if(jt==="")return _$e;if(jt in k4t)return[k4t[jt]];for(;jt!=="";){switch(Ft=null,Ut=(jt=C4t(jt)).charAt(0)){case'"':case"'":Ft=oWn(jt.substring(1),Ut);break;default:Ft=lWn(jt)}if(Ft===null||(is.push(Ft[0]),(jt=C4t(Ft[1]))!==""&&jt.charAt(0)!==","))return _$e;jt=jt.replace(/^,/,"")}return is}(ht);if(this.fontFaces){var rt=function(bs,Ut){var Ft=bs.getFontList(),is=JSON.stringify(Ft);if(Ne===null||Be!==is){var jt=function(zs){var yt=[];return Object.keys(zs).forEach(function(gs){zs[gs].forEach(function(Ss){var Ds=null;switch(Ss){case"bold":Ds={family:gs,weight:"bold"};break;case"italic":Ds={family:gs,style:"italic"};break;case"bolditalic":Ds={family:gs,weight:"bold",style:"italic"};break;case"":case"normal":Ds={family:gs}}Ds!==null&&(Ds.ref={name:gs,style:Ss},yt.push(Ds))})}),yt}(Ft);Ne=function(zs){for(var yt={},gs=0;gs=700||qe==="bold")&&(ft="bold"),qe==="italic"&&(ft+="italic"),ft.length===0&&(ft="normal");for(var gt="",es={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"},Ht=0;Ht=2*Math.PI&&(fe=0,ue=2*Math.PI),this.path.push({type:"arc",x:J,y:ce,radius:ve,startAngle:fe,endAngle:ue,counterclockwise:be})},h.prototype.arcTo=function(J,ce,ve,fe,ue){throw new Error("arcTo not implemented.")},h.prototype.rect=function(J,ce,ve,fe){if(isNaN(J)||isNaN(ce)||isNaN(ve)||isNaN(fe))throw yf.error("jsPDF.context2d.rect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.rect");this.moveTo(J,ce),this.lineTo(J+ve,ce),this.lineTo(J+ve,ce+fe),this.lineTo(J,ce+fe),this.lineTo(J,ce),this.lineTo(J+ve,ce),this.lineTo(J,ce)},h.prototype.fillRect=function(J,ce,ve,fe){if(isNaN(J)||isNaN(ce)||isNaN(ve)||isNaN(fe))throw yf.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,ve,fe),this.fill(),ue.hasOwnProperty("lineCap")&&(this.lineCap=ue.lineCap),ue.hasOwnProperty("lineJoin")&&(this.lineJoin=ue.lineJoin)}},h.prototype.strokeRect=function(J,ce,ve,fe){if(isNaN(J)||isNaN(ce)||isNaN(ve)||isNaN(fe))throw yf.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,ve,fe),this.stroke())},h.prototype.clearRect=function(J,ce,ve,fe){if(isNaN(J)||isNaN(ce)||isNaN(ve)||isNaN(fe))throw yf.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,ve,fe))},h.prototype.save=function(J){J=typeof J!="boolean"||J;for(var ce=this.pdf.internal.getCurrentPageInfo().pageNumber,ve=0;ve0||this.margin[1]>0||this.margin[2]>0||this.margin[3]>0};h.prototype.drawImage=function(J,ce,ve,fe,ue,be,Ee,ke,Ie){var Fe=this.pdf.getImageProperties(J),Ne=1,Be=1,Se=1,Ae=1;fe!==void 0&&ke!==void 0&&(Se=ke/fe,Ae=Ie/ue,Ne=Fe.width/fe*ke/fe,Be=Fe.height/ue*Ie/ue),be===void 0&&(be=ce,Ee=ve,ce=0,ve=0),fe!==void 0&&ke===void 0&&(ke=fe,Ie=ue),fe===void 0&&ke===void 0&&(ke=Fe.width,Ie=Fe.height);var Ce=this.ctx.transform.decompose(),qe=ae(Ce.rotate.shx),ze=new c,Ve=(ze=(ze=(ze=ze.multiply(Ce.translate)).multiply(Ce.skew)).multiply(Ce.scale)).applyToRectangle(new o(be-ce*Se,Ee-ve*Ae,fe*Ne,ue*Be));if(this.autoPaging){for(var ht,Qe=v.call(this,Ve),at=[],rt=0;rtKe||ftVe||Qe0)){for(;Ie>=0;Ie--)if(ue[Ie-1].close!==!0&&ue[Ie-1].begin!==!0){ue[Ie-1].deltas.push(ve),ue[Ie-1].abs.push(ke);break}}break;case"bct":ve=[ke.x1-be[Ee-1].x,ke.y1-be[Ee-1].y,ke.x2-be[Ee-1].x,ke.y2-be[Ee-1].y,ke.x-be[Ee-1].x,ke.y-be[Ee-1].y],ue[ue.length-1].deltas.push(ve);break;case"qct":var Fe=be[Ee-1].x+2/3*(ke.x1-be[Ee-1].x),Ne=be[Ee-1].y+2/3*(ke.y1-be[Ee-1].y),Be=ke.x+2/3*(ke.x1-ke.x),Se=ke.y+2/3*(ke.y1-ke.y),Ae=ke.x,Ce=ke.y;ve=[Fe-be[Ee-1].x,Ne-be[Ee-1].y,Be-be[Ee-1].x,Se-be[Ee-1].y,Ae-be[Ee-1].x,Ce-be[Ee-1].y],ue[ue.length-1].deltas.push(ve);break;case"arc":ue.push({deltas:[],abs:[],arc:!0}),Array.isArray(ue[ue.length-1].abs)&&ue[ue.length-1].abs.push(ke)}}fe=ce?null:J==="stroke"?"stroke":"fill";for(var qe=!1,ze=0;ze=.01&&(fe=this.pdf.internal.getFontSize(),this.pdf.setFontSize(fe*J.scale),ue=this.lineWidth,this.lineWidth=ue*J.scale);var as=this.autoPaging!=="text";if(as||Ht.y+Ht.h<=rt){if(as||Ht.y>=Qe&&Ht.x<=Je){var bs=as?J.text:this.pdf.splitTextToSize(J.text,J.maxWidth||Je-Ht.x)[0],Ut=b([JSON.parse(JSON.stringify(Be))],this.posX+this.margin[3],-gt+Qe+this.ctx.prevPageLastElemOffset)[0],Ft=as&&(ht>ze||ht=.01&&(this.pdf.setFontSize(fe),this.lineWidth=ue)}}else J.scale>=.01&&(fe=this.pdf.internal.getFontSize(),this.pdf.setFontSize(fe*J.scale),ue=this.lineWidth,this.lineWidth=ue*J.scale),this.pdf.text(J.text,Ie.x+this.posX,Ie.y+this.posY,{angle:J.angle,align:ce,renderingMode:J.renderingMode,maxWidth:J.maxWidth}),J.scale>=.01&&(this.pdf.setFontSize(fe),this.lineWidth=ue)},W=function(J,ce,ve,fe){ve=ve||0,fe=fe||0,this.pdf.internal.out(n(J+ve)+" "+r(ce+fe)+" l")},V=function(J,ce,ve){return this.pdf.lines(J,ce,ve,null,null)},G=function(J,ce,ve,fe,ue,be,Ee,ke){this.pdf.internal.out([t(a(ve+J)),t(i(fe+ce)),t(a(ue+J)),t(i(be+ce)),t(a(Ee+J)),t(i(ke+ce)),"c"].join(" "))},Z=function(J,ce,ve,fe){for(var ue=2*Math.PI,be=Math.PI/2;ce>ve;)ce-=ue;var Ee=Math.abs(ve-ce);Ee1e-5;){var Ne=Fe+Ie*Math.min(Ee,be);ke.push(X.call(this,J,Fe,Ne)),Ee-=Math.abs(Ne-Fe),Fe=Ne}return ke},X=function(J,ce,ve){var fe=(ve-ce)/2,ue=J*Math.cos(fe),be=J*Math.sin(fe),Ee=ue,ke=-be,Ie=Ee*Ee+ke*ke,Fe=Ie+Ee*ue+ke*be,Ne=4/3*(Math.sqrt(2*Ie*Fe)-Fe)/(Ee*be-ke*ue),Be=Ee-Ne*ke,Se=ke+Ne*Ee,Ae=Be,Ce=-Se,qe=fe+ce,ze=Math.cos(qe),Ve=Math.sin(qe);return{x1:J*Math.cos(ce),y1:J*Math.sin(ce),x2:Be*ze-Se*Ve,y2:Be*Ve+Se*ze,x3:Ae*ze-Ce*Ve,y3:Ae*Ve+Ce*ze,x4:J*Math.cos(ve),y4:J*Math.sin(ve)}},ae=function(J){return 180*J/Math.PI},le=function(J,ce,ve,fe,ue,be){var Ee=J+.5*(ve-J),ke=ce+.5*(fe-ce),Ie=ue+.5*(ve-ue),Fe=be+.5*(fe-be),Ne=Math.min(J,ue,Ee,Ie),Be=Math.max(J,ue,Ee,Ie),Se=Math.min(ce,be,ke,Fe),Ae=Math.max(ce,be,ke,Fe);return new o(Ne,Se,Be-Ne,Ae-Se)},re=function(J,ce,ve,fe,ue,be,Ee,ke){var Ie,Fe,Ne,Be,Se,Ae,Ce,qe,ze,Ve,ht,Qe,at,rt,Ke=ve-J,Je=fe-ce,ft=ue-ve,gt=be-fe,es=Ee-ue,Ht=ke-be;for(Fe=0;Fe<41;Fe++)ze=(Ce=(Ne=J+(Ie=Fe/40)*Ke)+Ie*((Se=ve+Ie*ft)-Ne))+Ie*(Se+Ie*(ue+Ie*es-Se)-Ce),Ve=(qe=(Be=ce+Ie*Je)+Ie*((Ae=fe+Ie*gt)-Be))+Ie*(Ae+Ie*(be+Ie*Ht-Ae)-qe),Fe==0?(ht=ze,Qe=Ve,at=ze,rt=Ve):(ht=Math.min(ht,ze),Qe=Math.min(Qe,Ve),at=Math.max(at,ze),rt=Math.max(rt,Ve));return new o(Math.round(ht),Math.round(Qe),Math.round(at-ht),Math.round(rt-Qe))},te=function(){if(this.prevLineDash||this.ctx.lineDash.length||this.ctx.lineDashOffset){var J,ce,ve=(J=this.ctx.lineDash,ce=this.ctx.lineDashOffset,JSON.stringify({lineDash:J,lineDashOffset:ce}));this.prevLineDash!==ve&&(this.pdf.setLineDash(this.ctx.lineDash,this.ctx.lineDashOffset),this.prevLineDash=ve)}}})(Go.API),function(s){var t=function(l){var o,c,d,u,h,m,f,g,x,v;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-(v=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,v+33)):c.push(122);return function(y,b){for(var w=b;w>0;w--)y.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",v="slice",y="replace";for(l[v](-2),l=l[v](0,-2)[y](/\s/g,"")[y]("z","!!!!!"),d=[],u=0,h=(l+=o="uuuuu"[v](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(Dc.DOMPurify?Promise.resolve(Dc.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=Tm(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=v,v=x,x=g);else{if(o!=="l"&&o!=="landscape")throw"Invalid orientation: "+o;o="l",x>v&&(g=v,v=x,x=g)}return{width:v,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(b$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,Z=void 0;var ue=R*D;X=new Uint8Array(ue);for(var be=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){yf.log("bit decode error:"+n)}},eS.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)}},eS.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)}},eS.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}},eS.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}},eS.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},T4t=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(" "),v=kue.apply(this,[" ",n])[0];if(c=n.lineIndent===-1?x[0].length+2:n.lineIndent||0){var y=Array(c).join(" "),b=[];x.map(function(S){(S=S.split(/\s*\n/)).length>1?b=b.concat(S.map(function(A,E){return(E&&A.length?` `:"")+A})):b.push(S[0])}),x=b,c=A4t.apply(this,[y,n])}for(i=0,l=x.length;it||w){if(g>t){for(o=E4t.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,A){return S+A},0)}else u=[r];h.push(u),m=g+c,f=v}else u.push(r),m+=f+g,f=v}return d=c?function(S,A){return(A?y:"")+S.join(" ")}:function(S){return S.join(" ")},h.map(d)},$$.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-Bi27UDU-.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",fWn),this.internal.events.subscribe("postPutResources",mWn)),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 /"+bU(o.fontName)),c("/FontDescriptor "+y+" 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 "+v+" 0 R"),c("/BaseFont /"+bU(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 y=0;y>"),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,v="",y=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]),y=0;y","<","[","]","[","{","}","{","«","»","«","‹","›","‹","⁅","⁆","⁅","⁽","⁾","⁽","₍","₎","₍","≤","≥","≤","〈","〉","〈","﹙","﹚","﹙","﹛","﹜","﹛","﹝","﹞","﹝","﹤","﹥","﹤"],y=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":y.test(W)?"L":W===8?"R":"N"},A=function(O){for(var U,W=0;W=U.length||(G=W[V-1])!=="EN"&&G!=="AN"||(Z=U[V+1])!=="EN"&&Z!=="AN"?le="N":b&&(Z="AN"),le=Z===G?Z:"N";break;case"ES":le=(G=V>0?W[V-1]:"B")==="EN"&&V+10&&W[V-1]==="EN"){le="EN";break}if(b){le="N";break}for(X=V+1,ae=U.length;X=1425&&re<=2303||re===64286;if(G=U[X],te&&(G==="R"||G==="AL")){le="R";break}}}le=V<1||(G=U[V-1])==="B"?"N":W[V-1];break;case"B":b=!1,a=!0,le=w;break;case"S":i=!0,le="N"}return le},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,Z,X,ae,le=-1,re=O.length,te=0,J=[],ce=w?f:m,ve=[];for(b=!1,a=!1,i=!1,G=0;G0)if(V===16){for(G=le;G-1){for(G=le;G=0&&fe[ke]==="WS";ke--)ue[ke]=w}}(ve,U,re)},R=function(O,U,W,V,G){if(!(G.hiLevel=O){for(ae=te+1;ae=O;)ae++;for(le=te,X=ae-1;le=0&&(Z[re]=v[le+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,Z){if(Z)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 EC,OL=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 OL).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=Zts.call(n);n.length%4;)n.push(0);for(i=new OL(n),a=0,r=0,l=n.length;rm;c=0<=m?++S:--S)A.push(t.readUInt16());return A}(),t.pos+=2,x=function(){var S,A;for(A=[],c=S=0;0<=m?Sm;c=0<=m?++S:--S)A.push(t.readUInt16());return A}(),d=function(){var S,A;for(A=[],c=S=0;0<=m?Sm;c=0<=m?++S:--S)A.push(t.readUInt16());return A}(),u=function(){var S,A;for(A=[],c=S=0;0<=m?Sm;c=0<=m?++S:--S)A.push(t.readUInt16());return A}(),a=(this.length-t.pos+this.offset)/2,o=function(){var S,A;for(A=[],c=S=0;0<=a?Sa;c=0<=a?++S:--S)A.push(t.readUInt16());return A}(),c=y=0,w=i.length;y=v;r=g<=v?++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,v,y,b,w,S,A,E,I,P,R,D,O,U,W,V,G,Z,X,ae,le,re,te,J,ce,ve,fe,ue,be,Ee,ke,Ie,Fe,Ne;switch(V=new OL,l=Object.keys(t).sort(function(Be,Se){return Be-Se}),n){case"macroman":for(x=0,v=function(){var Be=[];for(g=0;g<256;++g)Be.push(0);return Be}(),b={0:0},i={},G=0,le=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),be=0,J=h.length;bea;r=0<=a?++r:--r)n=new z4t(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=z4t.encode(t,n),(a=new OL).writeUInt16(0),a.writeUInt16(1),r.table=a.data.concat(r.subtable),r},s}(),yWn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return b3(s,EC),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}(),vWn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return b3(s,EC),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}(),bWn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return b3(s,EC),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}(),_Wn=function(s,t){this.raw=s,this.length=s.length,this.platformID=t.platformID,this.encodingID=t.encodingID,this.languageID=t.languageID},wWn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return b3(s,EC),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}(),Zts=[].slice,kWn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return b3(s,EC),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 OL(n.read(a))).readShort(),d=o.readShort(),h=o.readShort(),c=o.readShort(),u=o.readShort(),this.cache[t]=l===-1?new CWn(o,d,h,c,u):new SWn(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}(),EWn=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,v,y;for(a in r=Yts.encode(this.generateCmap(),"unicode"),l=this.glyphsFor(t),f={0:0},y=r.charMap)f[(c=y[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 lZe=[{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}],TWn="signature";function MWn(s){return lZe.find(t=>t.id===s)||lZe[0]}const xd=792,Hf=612,wa=52;function U$(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 Pg(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 _3=[22,24,28],N_=[124,128,136],Xo=[255,255,255];function PWn(s){return s==null||!Number.isFinite(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Number(s))}const N$e="https://relzejiswnotikjgvjhz.supabase.co";function IWn(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(N$e).origin?s:`${N$e}/functions/v1/image-proxy?url=${encodeURIComponent(t.toString())}`}catch{return s}}async function iX(s,t=2e3){if(!s)return null;try{const n=await fetch(IWn(s),{mode:"cors"});if(!n.ok)return null;const r=await n.blob(),a=URL.createObjectURL(r),i=await new Promise((x,v)=>{const y=new Image;y.crossOrigin="anonymous",y.onload=()=>x(y),y.onerror=v,y.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 v=new Image;v.onload=()=>x(v),v.onerror=()=>x(v),v.src=f}),dataUrl:f,w:o,h:c,format:m}}catch{return null}}let Xts={x:.5,y:.5};function LWn(s){Xts={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 $ie(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,v=t.w,y=t.h;const b=l.focal??Xts;if(m>f?(v=t.h*f,g=Math.min(Math.max(0,t.w*b.x-v/2),t.w-v)):(y=t.w/f,x=Math.min(Math.max(0,t.h*b.y-y/2),t.h-y)),l.radius&&l.radius>0){const A=Math.min(l.radius*o,c/2,d/2);h.beginPath(),h.moveTo(A,0),h.arcTo(c,0,c,d,A),h.arcTo(c,d,0,d,A),h.arcTo(0,d,0,0,A),h.arcTo(0,0,c,0,A),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,v,y,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[A,E,I]=l.tint.color;h.globalCompositeOperation="multiply",h.fillStyle=`rgba(${A},${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 A=h.createLinearGradient(0,0,0,d);A.addColorStop(0,"rgba(0,0,0,0)"),A.addColorStop(.45,"rgba(0,0,0,0.05)"),A.addColorStop(1,"rgba(0,0,0,0.8)"),h.fillStyle=A,h.fillRect(0,0,c,d)}else if(l.gradient==="full"){const A=h.createLinearGradient(0,0,0,d);A.addColorStop(0,"rgba(0,0,0,0.4)"),A.addColorStop(.5,"rgba(0,0,0,0.18)"),A.addColorStop(1,"rgba(0,0,0,0.85)"),h.fillStyle=A,h.fillRect(0,0,c,d)}else if(l.gradient==="left"){const A=h.createLinearGradient(0,0,c,0);A.addColorStop(0,"rgba(0,0,0,0.75)"),A.addColorStop(.6,"rgba(0,0,0,0.15)"),A.addColorStop(1,"rgba(0,0,0,0)"),h.fillStyle=A,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 k7(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 xot(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 cw(s,t){const n=s.GState;n&&s.setGState(new n({opacity:t}))}function RWn(s,t,n,r,a,i={font:"helvetica",size:10,color:_3}){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 ZK(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=RWn(s,c,n+13,l,a-13,{font:i.font,size:i.size,color:i.color,leading:o})+(i.gap??7)}),l}function k1(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 i9='',o9='',DWn={title:"Facebook",slug:"facebook",get svg(){return i9+"Facebook"+o9+this.path+l9},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"},FWn={title:"Instagram",slug:"instagram",get svg(){return i9+"Instagram"+o9+this.path+l9},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"},OWn={title:"Pinterest",slug:"pinterest",get svg(){return i9+"Pinterest"+o9+this.path+l9},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"},zWn={title:"TikTok",slug:"tiktok",get svg(){return i9+"TikTok"+o9+this.path+l9},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"},BWn={title:"trulia",slug:"trulia",get svg(){return i9+"trulia"+o9+this.path+l9},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"},$Wn={title:"YouTube",slug:"youtube",get svg(){return i9+"YouTube"+o9+this.path+l9},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"},UWn={title:"Zillow",slug:"zillow",get svg(){return i9+"Zillow"+o9+this.path+l9},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"},qWn={facebook:DWn,instagram:FWn,youtube:$Wn,tiktok:zWn,pinterest:OWn,zillow:UWn,trulia:BWn},B4t=new Map;function VWn(s,t,n){return`${s}|${t}|${n}`}function HWn(s,t,n=128){const r=s.toLowerCase().replace(/[^a-z]/g,""),a=qWn[r];if(!a)return null;const i=VWn(r,t,n),l=B4t.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 B4t.set(i,d),d}catch{return null}}const zu="helvetica";let bW="helvetica";function Qts(s,t,n,r,a,i){const l=`#${n.map(d=>Math.round(d).toString(16).padStart(2,"0")).join("")}`,o=HWn(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(zu,"bold"),s.setFontSize(c*1.15),s.setTextColor(...Xo),s.text(t.charAt(0).toUpperCase(),r,a+c*.42,{align:"center"})}let Uie=[252,251,248],uB=[244,247,250],Lw=[223,228,234],Eb=[72,78,88];function qie(s,t){return tts(s.data.pages,t)}function yot(s){var n;const t=s.coAgent;return t!=null&&t.enabled&&((n=t.name)!=null&&n.trim())?t:null}function Jts(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 GWn(s){return[s.agent.brokerageName,s.agent.phone,s.agent.email].filter(Boolean).join(" | ")}function sy(s,t,n,r,a,i,l){const o=l.font||zu,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 im(s,t,n,r,a,i){s.setFont(zu,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 XK(s,t,n,r,a,i){const{doc:l}=s;l.setFont(zu,"bold"),l.setFontSize(7.5),l.setTextColor(...a||s.accent),l.text(t.toUpperCase(),n,r,{charSpace:1.8,align:i})}function Lv(s,t=Uie){s.doc.addPage("letter","landscape"),s.pageNo+=1,s.doc.setFillColor(...t),s.doc.rect(0,0,xd,Hf,"F")}function Tb(s,t,n,r,a={}){const{doc:i}=s,l=!!a.dark,o=a.width??xd-wa*2-60;XK(s,t,wa,62,s.accent),i.setFont(bW,"bold"),i.setFontSize(bW==="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=im(i,r,wa,d+26,Math.min(o+40,xd-wa*2),{size:10,color:l?Pg(Xo,s.deep,.28):N_,leading:15,maxLines:2})),d+34}function Rv(s,t=!1){const{doc:n,data:r}=s,a=t?Pg(Xo,s.deep,.7):Lw;n.setDrawColor(...a),n.setLineWidth(.6),n.line(wa,Hf-46,xd-wa,Hf-46);const i=Hf-30;n.setFont(zu,"bold"),n.setFontSize(7),n.setTextColor(...t?Xo:s.brand),t&&cw(n,.9),n.text((r.agent.name||"").toUpperCase(),wa,i,{charSpace:1.4});const l=GWn(r);l&&(n.setFont(zu,"normal"),n.setFontSize(7),n.setTextColor(...t?Xo:N_),sy(n,l,xd/2,i,xd/2-wa-40,7,{color:t?Xo:N_,align:"center"})),n.setFont(zu,"normal"),n.setFontSize(7),n.setTextColor(...t?Xo:N_),n.text(String(s.pageNo).padStart(2,"0"),xd-wa,i,{align:"right"}),t&&cw(n,1)}function ess(s,t,n,r,a){const{doc:i}=s;i.setFont(zu,"bold"),i.setFontSize(8);const l=i.splitTextToSize(t,a-28),o=16+l.length*12;return k1(i,n,r,a,o,6,Pg(s.accent,Xo,.86)),i.setTextColor(...Pg(s.brand,_3,.2)),l.forEach((c,d)=>i.text(c,n+14,r+20+d*12)),r+o}function vot(s,t,n,r,a,i={}){const{doc:l}=s;s.hero?$ie(l,s.hero,t,n,r,a,{radius:10,dpi:s.dpi,tint:i.tint?{color:s.deep,amount:i.tint}:void 0}):k1(l,t,n,r,a,10,Pg(s.deep,Xo,.12))}function WWn(s){const{doc:t,data:n}=s,{line1:r,line2:a}=Jts(n),i=336;s.hero?$ie(t,s.hero,0,0,xd,Hf,{dpi:s.dpi,darken:.12}):(t.setFillColor(...s.deep),t.rect(0,0,xd,Hf,"F")),t.setFillColor(...s.deep),t.rect(0,0,i,Hf,"F"),t.setFillColor(...s.accent),t.rect(i-3,0,3,Hf,"F");const l=qie(s,"cover");XK(s,l.kicker,wa,66),t.setFont(bW,"bold"),t.setFontSize(bW==="times"?29:26),t.setTextColor(...Xo);const o=t.splitTextToSize(r,i-wa*2).slice(0,3);o.forEach((v,y)=>t.text(v,wa,102+y*30));let c=102+(o.length-1)*30;a&&(t.setFont(zu,"normal"),t.setFontSize(9),cw(t,.9),sy(t,a.toUpperCase(),wa,c+22,i-wa*2,9,{color:Xo,charSpace:1.4}),cw(t,1),c+=22),c=im(t,l.body,wa,c+34,i-wa*2,{size:10,color:Pg(Xo,s.deep,.22),leading:16});const d=[PWn(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),sy(t,d.join(" · "),wa,c+54,i-wa*2,10,{style:"bold",color:Xo,charSpace:1}));const u=yot(n),h=Hf-(u?152:128);let m=wa;s.headshot&&(k7(t,s.headshot,wa+22,h+18,22),u&&s.coHeadshot?(k7(t,s.coHeadshot,wa+56,h+18,22),m=wa+90):m=wa+56),sy(t,u?`${n.agent.name} + ${u.name}`:n.agent.name,m,h+12,i-m-24,14,{style:"bold",color:Xo}),t.setFont(zu,"normal"),t.setFontSize(8),cw(t,.85);const f=[n.agent.brokerageName].filter(Boolean).join("");f&&sy(t,f,m,h+26,i-m-24,8,{color:Xo});const g=[n.agent.phone,n.agent.email].filter(Boolean).join(" · ");if(g&&sy(t,g,m,h+38,i-m-24,8,{color:Xo}),u){const v=[u.title||"Co-listing agent",u.phone].filter(Boolean).join(" · ");v&&sy(t,v,wa,h+56,i-wa-24,8,{color:Xo})}cw(t,1),s.logo&&(cw(t,.95),xot(t,s.logo,wa,Hf-74,132,30,"left"),cw(t,1));const x=n.sellerName?`PREPARED FOR ${n.sellerName.toUpperCase()}`:"PREPARED FOR YOUR HOME";t.setFont(zu,"bold"),t.setFontSize(7.5),t.setTextColor(...Xo),cw(t,.9),t.text(x,xd-wa,Hf-34,{align:"right",charSpace:1.6}),cw(t,1)}function KWn(s){Lv(s);const{doc:t}=s,n=qie(s,"welcome"),r=Tb(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(...Pg(s.accent,Xo,.85)),t.circle(wa+13,i-3,13,"F"),t.setFont(zu,"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=xd-d-wa-40;t.setFont(zu,"bold"),t.setFontSize(11.5),t.setTextColor(..._3),t.text(l,d,i),im(t,o,d,i+18,u,{size:9.5,color:Eb,leading:14,maxLines:2}),i+=88}),Rv(s)}function YWn(s){Lv(s,Xo);const{doc:t,data:n}=s,r=qie(s,"agent"),a=Tb(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=yot(n),l=xd-wa-260,o=a-6,c=262;if(i){const g=(x,v,y,b)=>{k1(t,l,x,260,124,10,uB,"FD",Lw),t.setFillColor(...s.accent),t.rect(l,x,260,3,"F");let w=l+18;y&&(k7(t,y,l+48,x+62+2,30),w=l+90);const S=260-(w-l)-18;sy(t,v,w,x+40,S,13,{style:"bold",color:s.brand});let A=x+56;b.filter(Boolean).slice(0,4).forEach(E=>{sy(t,String(E),w,A,S,8,{color:N_}),A+=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{k1(t,l,o,260,c,10,uB,"FD",Lw),t.setFillColor(...s.accent),t.rect(l,o,260,3,"F"),s.headshot&&k7(t,s.headshot,l+130,o+72,42),sy(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=>{sy(t,String(f),l+130,m,220,8.5,{color:N_,align:"center"}),m+=14}),s.logo&&xot(t,s.logo,l+80,o+c-44,100,28,"left")}const d=l-wa-44;let u=im(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:Eb,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(zu,"bold"),t.setFontSize(7),t.setTextColor(...N_),t.text(m.toUpperCase(),wa,u,{charSpace:1.4}),sy(t,f,wa+86,u,d-86,10.5,{color:_3}),t.setDrawColor(...Lw),t.setLineWidth(.5),t.line(wa,u+11,wa+d,u+11),u+=36}),Rv(s)}function ZWn(s,t){Lv(s);const{doc:n}=s,r=qie(s,"overview"),a=Tb(s,r.kicker,r.headline,r.subhead||null),i=4,l=14,o=(xd-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);k1(n,h,m,o,c,8,Xo,"FD",Lw),n.setFillColor(...s.accent),n.rect(h,m,3,c,"F"),n.setFont(zu,"bold"),n.setFontSize(15),n.setTextColor(...Pg(s.brand,Xo,.55)),n.text(String(u+1).padStart(2,"0"),h+16,m+30),im(n,d.title,h+16,m+52,o-30,{size:9.5,style:"bold",color:_3,leading:13,maxLines:3})}),Rv(s)}function A6(s,t=5){var n;return(((n=s.options)==null?void 0:n.filter(r=>r.enabled).map(r=>r.label))??OVn[s.key]??[]).slice(0,t)}function $4t(s,t,n){Lv(s,n.dark?s.deep:Uie);const{doc:r}=s,a=Tb(s,n.kicker,n.headline,n.sub,{dark:n.dark}),i=404,l=272,o=!!n.flip,c=o?xd-wa-i:wa,d=o?wa:wa+i+40,u=xd-wa*2-i-40;vot(s,c,a,i,l,{tint:n.dark?.1:0}),XK(s,t.title,d,a+12);let h=im(r,t.body,d,a+32,u,{size:9.5,color:n.dark?Pg(Xo,s.deep,.2):Eb,leading:15,maxLines:4});const m=A6(t,5);if(m.length&&(h=ZK(r,m,d,h+28,u,{font:zu,size:9.5,color:n.dark?Xo:_3,accent:s.accent,gap:7})),n.note&&!n.dark){const f=Math.min(h+14,Hf-120);ess(s,n.note,d,f,u)}else n.note&&(r.setFont(zu,"bold"),r.setFontSize(9.5),r.setTextColor(...Xo),cw(r,.9),im(r,n.note,wa,Hf-78,xd-wa*2,{size:9.5,style:"bold",color:Xo,leading:13,maxLines:1}),cw(r,1));Rv(s,n.dark)}function XWn(s,t){Lv(s);const{doc:n}=s,r=Tb(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=A6(t,4),i=["Price + position","MLS story","Media ready","Go live"],l=Math.max(1,a.length||4),o=16,c=(xd-wa*2-o*(l-1))/l,d=176;(a.length?a:i).forEach((u,h)=>{const m=wa+h*(c+o);k1(n,m,r,c,d,8,Xo,"FD",Lw),n.setFont(zu,"bold"),n.setFontSize(16),n.setTextColor(...s.accent),n.text(String(h+1),m+16,r+34),n.setFont(zu,"bold"),n.setFontSize(7.5),n.setTextColor(...N_),n.text((i[h]||`STEP ${h+1}`).toUpperCase(),m+16,r+56,{charSpace:1.2}),im(n,u,m+16,r+76,c-32,{size:9,color:Eb,leading:13,maxLines:5})}),im(n,t.body,wa,r+d+34,xd-wa*2-120,{size:10,style:"bold",color:s.brand,leading:15,maxLines:2}),Rv(s)}function QWn(s,t){Lv(s);const{doc:n}=s,r=Tb(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=(xd-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);k1(n,f,g,o,c,8,Xo,"FD",Lw),Qts(n,u,h,f+28,g+c/2,20),sy(n,u,f+48,g+c/2+4,o-64,13,{style:"bold",color:h})});const d=r+2*(c+l)+22;im(n,t.body,wa,d,xd-wa*2-140,{size:9.5,color:Eb,leading:14,maxLines:3}),n.setFont(zu,"normal"),n.setFontSize(7.5),n.setTextColor(...N_),n.text("Distribution varies by MLS, market, and portal policies.",wa,Hf-62),Rv(s)}function JWn(s,t){Lv(s,uB);const{doc:n,data:r}=s,{line1:a}=Jts(r),i=Tb(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;k1(n,wa,i,l,o,10,Xo,"FD",Lw),k1(n,wa,i,l,22,10,s.deep),n.setFillColor(...s.deep),n.rect(wa,i+12,l,10,"F"),n.setFont(zu,"bold"),n.setFontSize(7),n.setTextColor(...Xo);const c=(r.agent.website||`${a}`).replace(/^https?:\/\//,"").toUpperCase();sy(n,c,wa+14,i+15,l-28,7,{style:"bold",color:Xo,charSpace:1}),vot(s,wa+14,i+36,186,142);const d=wa+214,u=l-228;sy(n,a,d,i+54,u,12,{style:"bold",color:s.brand}),im(n,"Welcome home.",d,i+72,u,{size:9,color:s.accent,leading:12,maxLines:1}),im(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:Eb,leading:12,maxLines:5}),ess(s,"Shareable. Trackable. Memorable.",wa+14,i+o-46,l-28);const h=wa+l+40,m=xd-h-wa;XK(s,t.title,h,i+12);let f=im(n,t.body,h,i+32,m,{size:9.5,color:Eb,leading:15,maxLines:5});const g=A6(t,5);g.length&&ZK(n,g,h,f+26,m,{font:zu,size:9,color:_3,accent:s.accent,gap:7}),Rv(s)}function eKn(s,t){Lv(s,s.deep);const{doc:n}=s,r=Tb(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);k1(n,m,r,i,i,12,Xo),Qts(n,d,u,m+i/2,r+i/2-4,30),n.setFont(zu,"bold"),n.setFontSize(6.5),n.setTextColor(...N_),n.text(d.toUpperCase(),m+i/2,r+i-8,{align:"center",charSpace:.6})});const o=wa+5*(i+l)+14,c=xd-o-wa;XK(s,"The campaign can include",o,r+12),ZK(n,A6(t,5),o,r+32,c,{font:zu,size:9,color:Xo,accent:s.accent,gap:7}),im(n,t.body,wa,r+i+44,420,{size:9.5,color:Pg(Xo,s.deep,.2),leading:15,maxLines:4}),im(n,"Every post sends attention back to the property.",wa,Hf-84,460,{size:11,style:"bold",color:Xo,leading:14,maxLines:1}),Rv(s,!0)}function tKn(s,t){Lv(s);const{doc:n}=s,r=Tb(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=A6(t,4),i=["Email announcement","Agent-to-agent outreach","Database follow-up","Local community visibility"];let l=r+6;a.forEach((o,c)=>{k1(n,wa,l-14,34,34,8,Pg(s.accent,Xo,.85)),n.setFont(zu,"bold"),n.setFontSize(11),n.setTextColor(...s.brand),n.text(String(c+1),wa+17,l+7,{align:"center"});const d=wa+52,u=xd-d-wa-20;n.setFont(zu,"bold"),n.setFontSize(8),n.setTextColor(...s.brand),n.text((i[c]||t.title).toUpperCase(),d,l-2,{charSpace:1.2}),im(n,o,d,l+14,u,{size:9.5,color:Eb,leading:14,maxLines:2}),l+=76}),im(n,t.body,wa,Math.min(l+8,Hf-92),xd-wa*2-120,{size:9.5,color:N_,leading:14,maxLines:2}),Rv(s)}function sKn(s,t){Lv(s);const{doc:n}=s,r=Tb(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=A6(t,4),i=["Open house","Signage","Neighborhood","Follow-up"],l=2,o=20,c=(xd-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);k1(n,m,f,c,d,8,uB,"FD",Lw),n.setFont(zu,"bold"),n.setFontSize(7.5),n.setTextColor(...s.brand),n.text((i[h]||t.title).toUpperCase(),m+16,f+24,{charSpace:1.2}),im(n,u,m+16,f+46,c-32,{size:9.5,color:Eb,leading:14,maxLines:3})}),Rv(s)}function nKn(s,t){Lv(s,uB);const{doc:n}=s,r=Tb(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=A6(t,4),i=["Weekly update","Market check","Smart adjustments","Direct access"];let l=r+10;a.forEach((o,c)=>{n.setFont(zu,"bold"),n.setFontSize(11),n.setTextColor(...s.accent),n.text(String(c+1).padStart(2,"0"),wa,l),n.setFont(zu,"bold"),n.setFontSize(9),n.setTextColor(...s.brand),n.text((i[c]||"").toUpperCase(),wa+48,l,{charSpace:1.2}),im(n,o,wa+250,l-1,xd-wa-250-wa,{size:9.5,color:Eb,leading:13,maxLines:2}),n.setDrawColor(...Lw),n.setLineWidth(.5),n.line(wa,l+22,xd-wa,l+22),l+=62}),im(n,"Marketing creates opportunity. Communication helps us act on it.",wa,Math.min(l+18,Hf-84),520,{size:11,style:"bold",color:s.brand,leading:14,maxLines:1}),Rv(s)}function rKn(s){Lv(s,s.deep);const{doc:t,data:n}=s;s.hero&&$ie(t,s.hero,0,0,xd,Hf,{tint:{color:s.deep,amount:.92},darken:.25,dpi:s.dpi});const r=qie(s,"closing"),a=Tb(s,r.kicker,r.headline,r.subhead||null,{dark:!0,width:520}),i=420;let l=im(t,r.body,wa,a,i,{size:10.5,color:Pg(Xo,s.deep,.18),leading:17});l+=30,ZK(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:zu,size:9.5,color:Xo,accent:s.accent,gap:8});const o=yot(n),c=250,d=xd-wa-c,u=a-20,h=o?300:258;k1(t,d,u,c,h,10,Xo),t.setFillColor(...s.accent),t.rect(d,u,c,3,"F"),s.headshot&&(o&&s.coHeadshot?(k7(t,s.headshot,d+c/2-34,u+70,32),k7(t,s.coHeadshot,d+c/2+34,u+70,32)):k7(t,s.headshot,d+c/2,u+70,38)),sy(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=>{sy(t,String(f),d+c/2,m,c-30,8.5,{color:N_,align:"center"}),m+=14}),o?(m+=6,t.setDrawColor(...Lw),t.setLineWidth(.5),t.line(d+24,m-8,d+c-24,m-8),sy(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=>{sy(t,String(f),d+c/2,m,c-30,8.5,{color:N_,align:"center"}),m+=13})):s.logo&&xot(t,s.logo,d+c/2-50,u+h-44,100,28,"left"),t.setFont(zu,"bold"),t.setFontSize(9),t.setTextColor(...Xo),cw(t,.9),t.text("LET'S MAKE YOUR HOME THE ONE BUYERS REMEMBER.",wa,Hf-72,{charSpace:1.4}),cw(t,1),Rv(s,!0)}function bot(s,t){return s.customImages[t.id]||null}function tss(s,t,n,r,a,i){const l=bot(s,t);l?$ie(s.doc,l,n,r,a,i,{radius:10,dpi:s.dpi}):vot(s,n,r,a,i)}function aKn(s,t){Lv(s,t.dark?s.deep:Uie);const{doc:n}=s,r=Tb(s,t.kicker||"About",t.headline,t.subhead||null,{dark:t.dark}),a=300,i=t.imageSide!=="left",l=i?xd-wa-a:wa,o=i?wa:wa+a+40,c=xd-wa*2-a-40;tss(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=im(n,h,o,u,c,{size:10,color:t.dark?Pg(Xo,s.deep,.2):Eb,leading:16,maxLines:7}),u+=26}),t.bullets.length&&ZK(n,t.bullets.slice(0,5),o,Math.min(u,Hf-150),c,{font:zu,size:9.5,color:t.dark?Xo:_3,accent:s.accent,gap:7}),Rv(s,t.dark)}function iKn(s,t){Lv(s,t.dark?s.deep:uB);const{doc:n}=s,r=Tb(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=(xd-wa*2-l*(i-1))/i,c=Math.ceil(a.length/i)||1,d=Hf-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);k1(n,g,x,o,u,10,t.dark?Pg(s.deep,Xo,.08):Xo,"FD",Lw),n.setFillColor(...s.accent),n.rect(g,x,3,u,"F"),n.setFont(bW,"bold"),n.setFontSize(30),n.setTextColor(...Pg(s.accent,t.dark?s.deep:Xo,.4)),n.text("“",g+18,x+40),im(n,m.quote,g+18,x+56,o-40,{size:9.5,color:t.dark?Pg(Xo,s.deep,.2):Eb,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(zu,"bold"),n.setFontSize(8),n.setTextColor(...s.brand);const v=[m.name,m.detail].filter(Boolean).join(" · ");v&&sy(n,v.toUpperCase(),g+18,x+u-16,o-36,8,{style:"bold",color:t.dark?Xo:s.brand,charSpace:1.1})}),t.body&&im(n,t.body,wa,Math.min(r+c*(u+l)+14,Hf-88),xd-wa*2-120,{size:9.5,color:t.dark?Pg(Xo,s.deep,.2):N_,leading:14,maxLines:2}),Rv(s,t.dark)}function oKn(s,t){Lv(s,t.dark?s.deep:Uie);const{doc:n}=s,r=Tb(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=(xd-wa*2-18*(a.length-1))/a.length,o=150;a.forEach((c,d)=>{const u=wa+d*(l+18);k1(n,u,r,l,o,10,t.dark?Pg(s.deep,Xo,.1):Xo,"FD",Lw),n.setFillColor(...s.accent),n.rect(u,r,l,3,"F"),sy(n,c.value||"—",u+l/2,r+76,l-28,34,{style:"bold",color:t.dark?Xo:s.brand,align:"center"}),im(n,c.label||"",u+20,r+100,l-40,{size:9,color:t.dark?Pg(Xo,s.deep,.3):N_,leading:12,maxLines:2,align:"center"})}),t.body&&im(n,t.body,wa,r+o+40,xd-wa*2-140,{size:10,color:t.dark?Pg(Xo,s.deep,.2):Eb,leading:15,maxLines:3})}else t.body&&im(n,t.body,wa,r,xd-wa*2-140,{size:10.5,color:t.dark?Xo:Eb,leading:16});Rv(s,t.dark)}function lKn(s,t){Lv(s,t.dark?s.deep:Xo);const{doc:n}=s,r=Tb(s,t.kicker||"Our promise",t.headline,t.subhead||null,{dark:t.dark}),i=!!bot(s,t)||!!s.hero,l=i?xd-wa*2-280:xd-wa*2-140;let o=r;t.body&&(o=im(n,t.body,wa,o,l,{size:10,color:t.dark?Pg(Xo,s.deep,.2):Eb,leading:15,maxLines:3})+28),t.bullets.filter(d=>d==null?void 0:d.trim()).slice(0,7).forEach(d=>{k1(n,wa,o-9,14,14,4,s.accent),n.setFont(zu,"bold"),n.setFontSize(8),n.setTextColor(...Xo),n.text("✓",wa+7,o+1,{align:"center"}),o=im(n,d,wa+26,o,l-26,{size:10,color:t.dark?Xo:_3,leading:14,maxLines:2})+22}),i&&tss(s,t,xd-wa-240,r,240,250),Rv(s,t.dark)}function cKn(s,t){Lv(s,s.deep);const{doc:n}=s,r=bot(s,t)||s.hero;r&&$ie(n,r,0,0,xd,Hf,{tint:{color:s.deep,amount:.82},darken:.28,dpi:s.dpi}),XK(s,t.kicker||"Our approach",wa,Hf/2-84),n.setFont(zu,"bold"),n.setFontSize(30),n.setTextColor(...Xo);const a=n.splitTextToSize(t.headline||"",xd-wa*2-140).slice(0,4);a.forEach((i,l)=>n.text(i,wa,Hf/2-44+l*38)),t.body&&im(n,t.body,wa,Hf/2+a.length*38-24,480,{size:10.5,color:Pg(Xo,s.deep,.2),leading:16,maxLines:4}),Rv(s,!0)}function U4t(s,t){switch(t.layout){case"testimonials":return iKn(s,t);case"stats":return oKn(s,t);case"checklist":return lKn(s,t);case"statement":return cKn(s,t);case"story":default:return aKn(s,t)}}async function dKn(s,t,n){var I,P,R,D;const r=n==="print"?4:2,a=n==="print"?2600:1600,i=MWn((I=t.pages)==null?void 0:I.theme);Uie=U$(i.paper),uB=U$(i.paperCool),Lw=U$(i.softLine),Eb=U$(i.bodyInk),bW=i.headFont;const l=U$((i.useAgentColors?t.agent.brandColor:i.brand)||i.brand||"#0E1B2C"),o=U$((i.useAgentColors?t.agent.accentColor:i.accent)||i.accent||"#B8965A"),c=Pg(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([iX(t.property.photoUrl,a),iX(t.agent.headshotUrl,700),iX(t.agent.brokerageLogoUrl,800),iX((d==null?void 0:d.headshotUrl)||null,700),...u.map(O=>iX(O.imageUrl||null,a))]),v={};u.forEach((O,U)=>{v[O.id]=x[U]??null}),LWn(t.focal);const y={doc:s,data:t,brand:l,accent:o,deep:c,hero:h,headshot:m,coHeadshot:g,logo:f,customImages:v,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);WWn(y),b.has("welcome")||KWn(y),b.has("agent")||YWn(y),u.filter(O=>O.placement!=="end").forEach(O=>U4t(y,O)),b.has("overview")||ZWn(y,w);const A=new Set,E=(O,U)=>{const W=S(O);W&&(A.add(O),U(W))};E("photography",O=>$4t(y,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=>$4t(y,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=>XWn(y,O)),E("syndication",O=>QWn(y,O)),E("website",O=>JWn(y,O)),E("social",O=>eKn(y,O)),E("email",O=>tKn(y,O)),E("openhouse",O=>sKn(y,O)),E("communication",O=>nKn(y,O)),w.filter(O=>!A.has(O.key)).forEach(O=>{Lv(y);const U=Tb(y,"Marketing",O.title,null),W=A6(O,6),V=im(s,O.body,wa,U,xd-wa*2-160,{size:10.5,color:Eb,leading:16});W.length&&ZK(s,W,wa,V+30,xd-wa*2-160,{font:zu,size:9.5,color:_3,accent:y.accent,gap:8}),Rv(y)}),u.filter(O=>O.placement==="end").forEach(O=>U4t(y,O)),b.has("closing")||rKn(y)}const q4t=[{id:"signature",name:"Signature",description:"Editorial full-bleed cover with a brand-tinted photo motif throughout.",render:dKn}];function uKn(s){return q4t.find(t=>t.id===s)||q4t[0]}async function sss(s,t,n="screen"){const r=new Go({unit:"pt",format:"letter",orientation:"landscape",compress:!0});return await uKn(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 hKn(s){return`${(s.property.addressLine1||s.title||"listing-presentation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing-presentation"}-presentation.pdf`}const mKn={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 cPe(s){if(!s)return null;const{data:t}=await q.storage.from(FL).createSignedUrl(s,3600);return(t==null?void 0:t.signedUrl)??null}function dPe(s,t,n){const r=s.agent_snapshot||{},a={...mKn,...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:ats(s.custom_pages),services:ZYe(s.services),pages:s.page_settings&&Object.keys(s.page_settings).length?s.page_settings:KYe,focal:s.photo_focal||YYe}}async function nss(s,t){if(s.property.photoUrl||!t)return s;const n=await cPe(t);return{...s,property:{...s.property,photoUrl:n}}}async function rss(s,t,n){const r=await nss(s,n);return(await sss(r,t,"screen")).output("blob")}async function ass(s,t,n="print",r){const a=await nss(s,r),l=(await sss(a,t,n)).output("blob"),o=URL.createObjectURL(l),c=document.createElement("a");return c.href=o,c.download=hKn(a),document.body.appendChild(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(o),4e3),l}async function iss(s,t,n){const r=`${s}/${t}/presentation.pdf`,{error:a}=await q.storage.from(FL).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 oss(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 fKn(s,t,n){const r=await oss(n),a=`${s}/${t}/photo.jpg`,{error:i}=await q.storage.from(FL).upload(a,r,{upsert:!0,contentType:"image/jpeg"});if(i)throw i;return a}async function pKn(s,t,n="presentation",r=1800){const a=await oss(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 gKn({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 DVn(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 V4t=60*60*24*30;function lss({open:s,onOpenChange:t,row:n,brand:r,photoUrl:a}){const{user:i}=_s(),[l,o]=j.useState([]),[c,d]=j.useState(""),[u,h]=j.useState([]),[m,f]=j.useState(!1),[g,x]=j.useState(""),[v,y]=j.useState(""),[b,w]=j.useState(!1),S=j.useRef(null),A=(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 ${A}`),y(`Hi {{first_name}}, Thank you for the opportunity to talk about selling ${A}. 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)){ne.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){ne.error("Add the primary exterior photo before emailing the presentation");return}w(!0);try{const D=await rss(dPe(n,r,a??null),n.template_id,n.property_photo_path),O=await iss(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(FL).createSignedUrl(O,V4t);if(W||!(U!=null&&U.signedUrl))throw new Error("Could not create a share link");const V=await cPe(n.property_photo_path).then(ae=>ae).catch(()=>null),{data:G}=await q.storage.from(FL).createSignedUrl(n.property_photo_path,V4t),{data:Z,error:X}=await q.functions.invoke("listing-presentation-email",{body:{presentation_id:n.id,subject:g,message:v,pdf_url:U.signedUrl,photo_url:(G==null?void 0:G.signedUrl)||V,recipients:l}});if(X)throw X;if(!(Z!=null&&Z.success))throw new Error((Z==null?void 0:Z.error)||"Could not send the email");ne.success(Z.failed?`Sent to ${Z.sent} · ${Z.failed} failed`:`Presentation emailed to ${Z.sent} ${Z.sent===1?"contact":"contacts"}`),t(!1)}catch(D){ne.error((D==null?void 0:D.message)||"Could not send the presentation")}finally{w(!1)}}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-4 w-4"})," Email this presentation"]}),e.jsxs(Er,{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($e,{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(mr,{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(cn,{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(Ct,{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:v,onChange:D=>y(D.target.value)})]})]}),e.jsxs(Nr,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),b?"Sending…":`Send${l.length?` (${l.length})`:""}`]})]})]})})}const xKn=()=>{const s=Zn(),{presentations:t,isLoading:n,create:r,duplicate:a,remove:i,update:l}=ets(),{data:o}=LVn(),{data:c}=w6e(),{savedTemplates:d,remove:u}=Jes(),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,v]=j.useState(null),[y,b]=j.useState(null),[w,S]=j.useState(null),A=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:rPe},[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:A});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:A,page_settings:R.page_settings});s(`/apps/listing-presentation-studio/${D.id}`)},P=async R=>{try{b(R.id),await ass(dPe(R,c),R.template_id,"print",R.property_photo_path)}catch(D){ne.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($e,{variant:"secondary",className:"gap-1",children:[e.jsx(wn,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(cn,{className:"h-4 w-4"}),"New presentation"]}),d.length>0&&e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsxs($,{size:"lg",variant:"outline",className:"gap-2",children:[e.jsx(A0,{className:"h-4 w-4"})," From template",e.jsx(wl,{className:"h-4 w-4"})]})}),e.jsx(Cu,{align:"end",className:"w-64",children:d.map(R=>e.jsxs(ja,{onClick:()=>I(R),children:[e.jsx(A0,{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(je,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Le,{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(A0,{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(qn,{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(xn,{className:"h-56 rounded-xl"},R))}):t.length===0?e.jsx(je,{className:"border-dashed",children:e.jsxs(Le,{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(Qr,{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(cn,{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(je,{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(gKn,{path:R.property_photo_path,alt:`${D} property photo`})}),e.jsxs(Le,{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(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Cu,{align:"end",children:[e.jsxs(ja,{onClick:()=>s(`/apps/listing-presentation-studio/${R.id}`),children:[e.jsx(pi,{className:"mr-2 h-4 w-4"})," Open"]}),e.jsxs(ja,{onClick:()=>{m(R),g(R.title)},children:[e.jsx(Qr,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(ja,{onClick:()=>a.mutate(R),children:[e.jsx(Za,{className:"mr-2 h-4 w-4"})," Duplicate"]}),e.jsxs(ja,{onClick:()=>P(R),children:[e.jsx(ji,{className:"mr-2 h-4 w-4"})," Download PDF"]}),e.jsxs(ja,{onClick:()=>S(R),children:[e.jsx(pn,{className:"mr-2 h-4 w-4"})," Email to a contact"]}),e.jsx(P0,{}),e.jsxs(ja,{className:"text-destructive",onClick:()=>v(R),children:[e.jsx(qn,{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 ",Js(new Date(R.updated_at),"MMM d, yyyy")]}),R.last_generated_at?e.jsx($e,{variant:"secondary",className:"text-[10px]",children:"PDF ready"}):e.jsx($e,{variant:"outline",className:"text-[10px]",children:"Draft"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",disabled:y===R.id,onClick:()=>P(R),children:[y===R.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(ji,{className:"h-4 w-4"}),"Download PDF"]})]})]},R.id)})})]}),e.jsx(Os,{open:!!h,onOpenChange:R=>!R&&m(null),children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{children:"Rename presentation"})}),e.jsx(pe,{value:f,onChange:R=>g(R.target.value),autoFocus:!0}),e.jsxs(Nr,{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),ne.success("Renamed"))},children:"Save"})]})]})}),e.jsx(fc,{open:!!x,onOpenChange:R=>!R&&v(null),children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Delete this presentation?"}),e.jsx(ic,{children:"This permanently removes the presentation, its property photo, and the generated PDF."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{x&&i.mutate(x),v(null)},children:"Delete"})]})]})}),e.jsx(lss,{open:!!w,onOpenChange:R=>!R&&S(null),row:w,brand:c})]})};var Jee={};Jee.d=(s,t)=>{for(var n in t)Jee.o(t,n)&&!Jee.o(s,n)&&Object.defineProperty(s,n,{enumerable:!0,get:t[n]})};Jee.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var cd=globalThis.pdfjsLib={};Jee.d(cd,{AbortException:()=>d9,AnnotationEditorLayer:()=>vXe,AnnotationEditorParamsType:()=>td,AnnotationEditorType:()=>Rd,AnnotationEditorUIManager:()=>mB,AnnotationLayer:()=>pZn,AnnotationMode:()=>CP,ColorPicker:()=>fPe,DOMSVGFactory:()=>Pot,DrawLayer:()=>jXe,FeatureTest:()=>k_,GlobalWorkerOptions:()=>hE,ImageKind:()=>P3e,InvalidPDFException:()=>dss,MissingPDFException:()=>c9,OPS:()=>fS,OutputScale:()=>mZe,PDFDataRangeTransport:()=>ins,PDFDateString:()=>kot,PDFWorker:()=>OV,PasswordResponses:()=>_Kn,PermissionFlag:()=>bKn,PixelsPerInch:()=>zL,RenderingCancelledException:()=>jot,TextLayer:()=>pne,UnexpectedResponseException:()=>IDe,Util:()=>ol,VerbosityLevel:()=>TDe,XfaLayer:()=>lns,build:()=>YYn,createValidAbsoluteUrl:()=>kKn,fetchData:()=>RDe,getDocument:()=>BYn,getFilenameFromUrl:()=>LKn,getPdfFilenameFromUrl:()=>RKn,getXfaPageViewport:()=>DKn,isDataScheme:()=>DDe,isPdfFile:()=>Not,noContextMenu:()=>fk,normalizeUnicode:()=>MKn,setLayerDimensions:()=>hB,shadow:()=>eh,version:()=>KYn});const f1=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),css=[1,0,0,1,0,0],cZe=[.001,0,0,.001,0,0],yKn=1e7,k$e=1.35,Fj={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},CP={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},vKn="pdfjs_internal_editor_",Rd={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},td={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},bKn={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Qb={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},P3e={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},r0={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},oX={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},TDe={ERRORS:0,WARNINGS:1,INFOS:5},fS={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},_Kn={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let MDe=TDe.WARNINGS;function wKn(s){Number.isInteger(s)&&(MDe=s)}function jKn(){return MDe}function PDe(s){MDe>=TDe.INFOS&&console.log(`Info: ${s}`)}function tu(s){MDe>=TDe.WARNINGS&&console.log(`Warning: ${s}`)}function Np(s){throw new Error(s)}function _0(s,t){s||Np(t)}function NKn(s){switch(s==null?void 0:s.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function kKn(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=TKn(s)}catch{}}const r=t?new URL(s,t):new URL(s);if(NKn(r))return r}catch{}return null}function eh(s,t,n,r=!1){return Object.defineProperty(s,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}const E6=function(){function t(n,r){this.message=n,this.name=r}return t.prototype=new Error,t.constructor=t,t}();class dZe extends E6{constructor(t,n){super(t,"PasswordException"),this.code=n}}class uZe extends E6{constructor(t,n){super(t,"UnknownErrorException"),this.details=n}}class dss extends E6{constructor(t){super(t,"InvalidPDFException")}}class c9 extends E6{constructor(t){super(t,"MissingPDFException")}}class IDe extends E6{constructor(t,n){super(t,"UnexpectedResponseException"),this.status=n}}class SKn extends E6{constructor(t){super(t,"FormatError")}}class d9 extends E6{constructor(t){super(t,"AbortException")}}function uss(s){(typeof s!="object"||(s==null?void 0:s.length)===void 0)&&Np("Invalid argument for bytesToString");const t=s.length,n=8192;if(t>24&255,s>>16&255,s>>8&255,s&255)}function _ot(s){const t=Object.create(null);for(const[n,r]of s)t[n]=r;return t}function AKn(){const s=new Uint8Array(4);return s[0]=1,new Uint32Array(s.buffer,0,1)[0]===1}function EKn(){try{return new Function(""),!0}catch{return!1}}class k_{static get isLittleEndian(){return eh(this,"isLittleEndian",AKn())}static get isEvalSupported(){return eh(this,"isEvalSupported",EKn())}static get isOffscreenCanvasSupported(){return eh(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?eh(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")}):eh(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,n;return eh(this,"isCSSRoundSupported",(n=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:n.call(t,"width: round(1.5px, 1px)"))}}const S$e=Array.from(Array(256).keys(),s=>s.toString(16).padStart(2,"0"));var eT,I3e,hZe;class ol{static makeHexColor(t,n,r){return`#${S$e[t]}${S$e[n]}${S$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)],ds(this,eT,hZe).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),ds(this,eT,hZe).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}}eT=new WeakSet,I3e=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)},hZe=function(t,n,r,a,i,l,o,c,d,u,h,m){if(Math.abs(d)<1e-12){Math.abs(u)>=1e-12&&ds(this,eT,I3e).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;ds(this,eT,I3e).call(this,t,n,r,a,i,l,o,c,(-u+g)/x,m),ds(this,eT,I3e).call(this,t,n,r,a,i,l,o,c,(-u-g)/x,m)},ys(ol,eT);function TKn(s){return decodeURIComponent(escape(s))}let C$e=null,H4t=null;function MKn(s){return C$e||(C$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,H4t=new Map([["ſt","ſt"]])),s.replaceAll(C$e,(t,n,r)=>n?n.normalize("NFKC"):H4t.get(r))}function PKn(){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 uss(s)}const wot="pdfjs_internal_id_",oA={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 IKn(s){return Uint8Array.prototype.toBase64?s.toBase64():btoa(uss(s))}const bA="http://www.w3.org/2000/svg",ZO=class ZO{};_r(ZO,"CSS",96),_r(ZO,"PDF",72),_r(ZO,"PDF_TO_CSS_UNITS",ZO.CSS/ZO.PDF);let zL=ZO;async function RDe(s,t="text"){if(wQ(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 Vie{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,v;d===0?(f=Math.abs(c-t[1])*n+a,g=Math.abs(o-t[0])*n+i,x=(t[3]-t[1])*n,v=(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,v=(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=v}get rawDims(){const{viewBox:t}=this;return eh(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 Vie({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 jot extends E6{constructor(t,n=0){super(t,"RenderingCancelledException"),this.extraDelay=n}}function DDe(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))}}Kne=new WeakMap,ys(kot,Kne);function DKn(s,{scale:t=1,rotation:n=0}){const{width:r,height:a}=s.attributes.style,i=[0,0,parseInt(r),parseInt(a)];return new Vie({viewBox:i,scale:t,rotation:n})}function Sot(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):(tu(`Not a valid color format: "${s}"`),[0,0,0])}function FKn(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,Sot(r))}t.remove()}function bg(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform();return[t,n,r,a,i,l]}function lA(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 hB(s,t,n=!1,r=!0){if(t instanceof Vie){const{pageWidth:a,pageHeight:i}=t.rawDims,{style:l}=s,o=k_.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 mZe{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 FP,I8,xS,L8,Yne,Zne,nIe,hss,A_,mss,fss,L3e,pss,pZe;const EA=class EA{constructor(t){ys(this,A_);ys(this,FP,null);ys(this,I8,null);ys(this,xS);ys(this,L8,null);ys(this,Yne,null);Yt(this,xS,t),ye(EA,Zne)||Yt(EA,Zne,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=Yt(this,FP,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const n=ye(this,xS)._uiManager._signal;t.addEventListener("contextmenu",fk,{signal:n}),t.addEventListener("pointerdown",ds(EA,nIe,hss),{signal:n});const r=Yt(this,L8,document.createElement("div"));r.className="buttons",t.append(r);const a=ye(this,xS).toolbarPosition;if(a){const{style:i}=t,l=ye(this,xS)._uiManager.direction==="ltr"?1-a[0]:a[0];i.insetInlineEnd=`${100*l}%`,i.top=`calc(${100*a[1]}% + var(--editor-toolbar-vert-offset))`}return ds(this,A_,pss).call(this),t}get div(){return ye(this,FP)}hide(){var t;ye(this,FP).classList.add("hidden"),(t=ye(this,I8))==null||t.hideDropdown()}show(){var t;ye(this,FP).classList.remove("hidden"),(t=ye(this,Yne))==null||t.shown()}async addAltText(t){const n=await t.render();ds(this,A_,L3e).call(this,n),ye(this,L8).prepend(n,ye(this,A_,pZe)),Yt(this,Yne,t)}addColorPicker(t){Yt(this,I8,t);const n=t.renderButton();ds(this,A_,L3e).call(this,n),ye(this,L8).prepend(n,ye(this,A_,pZe))}remove(){var t;ye(this,FP).remove(),(t=ye(this,I8))==null||t.destroy(),Yt(this,I8,null)}};FP=new WeakMap,I8=new WeakMap,xS=new WeakMap,L8=new WeakMap,Yne=new WeakMap,Zne=new WeakMap,nIe=new WeakSet,hss=function(t){t.stopPropagation()},A_=new WeakSet,mss=function(t){ye(this,xS)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},fss=function(t){ye(this,xS)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},L3e=function(t){const n=ye(this,xS)._uiManager._signal;t.addEventListener("focusin",ds(this,A_,mss).bind(this),{capture:!0,signal:n}),t.addEventListener("focusout",ds(this,A_,fss).bind(this),{capture:!0,signal:n}),t.addEventListener("contextmenu",fk,{signal:n})},pss=function(){const{editorType:t,_uiManager:n}=ye(this,xS),r=document.createElement("button");r.className="delete",r.tabIndex=0,r.setAttribute("data-l10n-id",ye(EA,Zne)[t]),ds(this,A_,L3e).call(this,r),r.addEventListener("click",a=>{n.delete()},{signal:n._signal}),ye(this,L8).append(r)},pZe=function(){const t=document.createElement("div");return t.className="divider",t},ys(EA,nIe),ys(EA,Zne,null);let fZe=EA;var Xne,R8,D8,GL,gss,xss,yss;class OKn{constructor(t){ys(this,GL);ys(this,Xne,null);ys(this,R8,null);ys(this,D8);Yt(this,D8,t)}show(t,n,r){const[a,i]=ds(this,GL,xss).call(this,n,r),{style:l}=ye(this,R8)||Yt(this,R8,ds(this,GL,gss).call(this));t.append(ye(this,R8)),l.insetInlineEnd=`${100*a}%`,l.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){ye(this,R8).remove()}}Xne=new WeakMap,R8=new WeakMap,D8=new WeakMap,GL=new WeakSet,gss=function(){const t=Yt(this,R8,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",fk,{signal:ye(this,D8)._signal});const n=Yt(this,Xne,document.createElement("div"));return n.className="buttons",t.append(n),ds(this,GL,yss).call(this),t},xss=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,D8).highlightSelection("floating_button")},{signal:r}),ye(this,Xne).append(t)};function uPe(s,t,n){for(const r of n)t.addEventListener(r,s[r].bind(s))}function zKn(s){return Math.round(Math.min(255,Math.max(1,255*s))).toString(16).padStart(2,"0")}var rIe;class BKn{constructor(){ys(this,rIe,0)}get id(){return`${vKn}${Z0(this,rIe)._++}`}}rIe=new WeakMap;var aH,Qne,s1,iH,R3e;const Gct=class Gct{constructor(){ys(this,iH);ys(this,aH,PKn());ys(this,Qne,0);ys(this,s1,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 eh(this,"_isSVGFittingCanvas",i)}async getFromFile(t){const{lastModified:n,name:r,size:a,type:i}=t;return ds(this,iH,R3e).call(this,`${n}_${r}_${a}_${i}`,t)}async getFromUrl(t){return ds(this,iH,R3e).call(this,t,t)}async getFromBlob(t,n){const r=await n;return ds(this,iH,R3e).call(this,t,r)}async getFromId(t){ye(this,s1)||Yt(this,s1,new Map);const n=ye(this,s1).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,s1)||Yt(this,s1,new Map);let r=ye(this,s1).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,aH)}_${Z0(this,Qne)._++}`,refCounter:1,isSvg:!1},ye(this,s1).set(t,r),ye(this,s1).set(r.id,r),r}getSvgUrl(t){const n=ye(this,s1).get(t);return n!=null&&n.isSvg?n.svgUrl:null}deleteId(t){var a;ye(this,s1)||Yt(this,s1,new Map);const n=ye(this,s1).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,aH)}_`)}};aH=new WeakMap,Qne=new WeakMap,s1=new WeakMap,iH=new WeakSet,R3e=async function(t,n){ye(this,s1)||Yt(this,s1,new Map);let r=ye(this,s1).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,aH)}_${Z0(this,Qne)._++}`,refCounter:0,isSvg:!1});let a;if(typeof n=="string"?(r.url=n,a=await RDe(n,"blob")):n instanceof File?a=r.file=n:n instanceof Blob&&(a=n),a.type==="image/svg+xml"){const i=Gct._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,s1).set(t,r),r&&ye(this,s1).set(r.id,r),r};let gZe=Gct;var tv,OP,Jne,sv;class $Kn{constructor(t=128){ys(this,tv,[]);ys(this,OP,!1);ys(this,Jne);ys(this,sv,-1);Yt(this,Jne,t)}add({cmd:t,undo:n,post:r,mustExec:a,type:i=NaN,overwriteIfSameType:l=!1,keepUndo:o=!1}){if(a&&t(),ye(this,OP))return;const c={cmd:t,undo:n,post:r,type:i};if(ye(this,sv)===-1){ye(this,tv).length>0&&(ye(this,tv).length=0),Yt(this,sv,0),ye(this,tv).push(c);return}if(l&&ye(this,tv)[ye(this,sv)].type===i){o&&(c.undo=ye(this,tv)[ye(this,sv)].undo),ye(this,tv)[ye(this,sv)]=c;return}const d=ye(this,sv)+1;d===ye(this,Jne)?ye(this,tv).splice(0,1):(Yt(this,sv,d),di===n[l]))return iIe._colorsMapping.get(r);return n}getHexCode(t){const n=this._colors.get(t);return n?ol.makeHexColor(...n):t}};_r(iIe,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let xZe=iIe;var oH,Aj,o0,Zv,lH,BA,cH,yS,zP,dH,F8,R5,vS,O8,ere,tre,uH,sre,D5,BP,hH,$P,F5,oIe,UP,nre,qP,z8,rre,are,nv,Nm,$A,B8,ire,ore,VP,O5,UA,lre,gN,Ji,D3e,yZe,bss,_ss,F3e,wss,jss,Nss,vZe,kss,bZe,_Ze,Sss,J1,KM,Css,Ass,wZe,Ess,jQ,jZe;const gq=class gq{constructor(t,n,r,a,i,l,o,c,d,u,h){ys(this,Ji);ys(this,oH,new AbortController);ys(this,Aj,null);ys(this,o0,new Map);ys(this,Zv,new Map);ys(this,lH,null);ys(this,BA,null);ys(this,cH,null);ys(this,yS,new $Kn);ys(this,zP,null);ys(this,dH,0);ys(this,F8,new Set);ys(this,R5,null);ys(this,vS,null);ys(this,O8,new Set);ys(this,ere,!1);ys(this,tre,!1);ys(this,uH,!1);ys(this,sre,null);ys(this,D5,null);ys(this,BP,null);ys(this,hH,null);ys(this,$P,!1);ys(this,F5,null);ys(this,oIe,new BKn);ys(this,UP,!1);ys(this,nre,!1);ys(this,qP,null);ys(this,z8,null);ys(this,rre,null);ys(this,are,null);ys(this,nv,Rd.NONE);ys(this,Nm,new Set);ys(this,$A,null);ys(this,B8,null);ys(this,ire,null);ys(this,ore,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});ys(this,VP,[0,0]);ys(this,O5,null);ys(this,UA,null);ys(this,lre,null);ys(this,gN,null);const m=this._signal=ye(this,oH).signal;Yt(this,UA,t),Yt(this,lre,n),Yt(this,lH,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}),ds(this,Ji,wss).call(this),ds(this,Ji,Sss).call(this),ds(this,Ji,vZe).call(this),Yt(this,BA,i.annotationStorage),Yt(this,sre,i.filterFactory),Yt(this,B8,l),Yt(this,hH,o||null),Yt(this,ere,c),Yt(this,tre,d),Yt(this,uH,u),Yt(this,are,h||null),this.viewParameters={realScale:zL.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=gq.prototype,n=l=>ye(l,UA).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 eh(this,"_keyboardManager",new Hie([[["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,UA).contains(o)&&!l.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&ye(l,UA).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,gN))==null||t.resolve(),Yt(this,gN,null),(n=ye(this,oH))==null||n.abort(),Yt(this,oH,null),this._signal=null;for(const i of ye(this,Zv).values())i.destroy();ye(this,Zv).clear(),ye(this,o0).clear(),ye(this,O8).clear(),Yt(this,Aj,null),ye(this,Nm).clear(),ye(this,yS).destroy(),(r=ye(this,lH))==null||r.destroy(),(a=ye(this,F5))==null||a.hide(),Yt(this,F5,null),ye(this,D5)&&(clearTimeout(ye(this,D5)),Yt(this,D5,null)),ye(this,O5)&&(clearTimeout(ye(this,O5)),Yt(this,O5,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return ye(this,are)}get useNewAltTextFlow(){return ye(this,tre)}get useNewAltTextWhenAddingImage(){return ye(this,uH)}get hcmFilter(){return eh(this,"hcmFilter",ye(this,B8)?ye(this,sre).addHCMFilter(ye(this,B8).foreground,ye(this,B8).background):"none")}get direction(){return eh(this,"direction",getComputedStyle(ye(this,UA)).direction)}get highlightColors(){return eh(this,"highlightColors",ye(this,hH)?new Map(ye(this,hH).split(",").map(t=>t.split("=").map(n=>n.trim()))):null)}get highlightColorNames(){return eh(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){Yt(this,rre,t)}editAltText(t,n=!1){var r;(r=ye(this,lH))==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":Yt(this,uH,n);break}}onPageChanging({pageNumber:t}){Yt(this,dH,t-1)}focusMainContainer(){ye(this,UA).focus()}findParent(t,n){for(const r of ye(this,Zv).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,lre).classList.toggle("noUserSelect",t)}addShouldRescale(t){ye(this,O8).add(t)}removeShouldRescale(t){ye(this,O8).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*zL.PDF_TO_CSS_UNITS;for(const n of ye(this,O8))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=ds(this,Ji,D3e).call(this,n).closest(".textLayer"),u=this.getSelectionBoxes(d);if(!u)return;n.empty();const h=ds(this,Ji,yZe).call(this,d),m=ye(this,nv)===Rd.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(Rd.HIGHLIGHT,f);return}f()}addToAnnotationStorage(t){!t.isEmpty()&&ye(this,BA)&&!ye(this,BA).has(t.id)&&ye(this,BA).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,ye(this,$P)&&(Yt(this,$P,!1),ds(this,Ji,F3e).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const n of ye(this,Nm))if(n.div.contains(t)){Yt(this,z8,[n,t]),n._focusEventsAllowed=!1;break}}focus(){if(!ye(this,z8))return;const[t,n]=ye(this,z8);Yt(this,z8,null),n.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),n.focus()}addEditListeners(){ds(this,Ji,vZe).call(this),ds(this,Ji,bZe).call(this)}removeEditListeners(){ds(this,Ji,kss).call(this),ds(this,Ji,_Ze).call(this)}dragOver(t){for(const{type:n}of t.dataTransfer.items)for(const r of ye(this,vS))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,vS))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer),t.preventDefault();return}}copy(t){var r;if(t.preventDefault(),(r=ye(this,Aj))==null||r.commitOrRemove(),!this.hasSelection)return;const n=[];for(const a of ye(this,Nm)){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,vS))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){tu(`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)ds(this,Ji,wZe).call(this,c);ds(this,Ji,jZe).call(this,i)},o=()=>{for(const c of i)c.remove()};this.addCommands({cmd:l,undo:o,mustExec:!0})}catch(i){tu(`paste: "${i.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),ye(this,nv)!==Rd.NONE&&!this.isEditorHandlingKeyboard&&gq._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,ye(this,$P)&&(Yt(this,$P,!1),ds(this,Ji,F3e).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?(ds(this,Ji,jss).call(this),ds(this,Ji,bZe).call(this),ds(this,Ji,J1).call(this,{isEditing:ye(this,nv)!==Rd.NONE,isEmpty:ds(this,Ji,jQ).call(this),hasSomethingToUndo:ye(this,yS).hasSomethingToUndo(),hasSomethingToRedo:ye(this,yS).hasSomethingToRedo(),hasSelectedEditor:!1})):(ds(this,Ji,Nss).call(this),ds(this,Ji,_Ze).call(this),ds(this,Ji,J1).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!ye(this,vS)){Yt(this,vS,t);for(const n of ye(this,vS))ds(this,Ji,KM).call(this,n.defaultPropertiesToUpdate)}}getId(){return ye(this,oIe).id}get currentLayer(){return ye(this,Zv).get(ye(this,dH))}getLayer(t){return ye(this,Zv).get(t)}get currentPageIndex(){return ye(this,dH)}addLayer(t){ye(this,Zv).set(t.pageIndex,t),ye(this,UP)?t.enable():t.disable()}removeLayer(t){ye(this,Zv).delete(t.pageIndex)}async updateMode(t,n=null,r=!1){if(ye(this,nv)!==t&&!(ye(this,gN)&&(await ye(this,gN).promise,!ye(this,gN)))){if(Yt(this,gN,Promise.withResolvers()),Yt(this,nv,t),t===Rd.NONE){this.setEditingState(!1),ds(this,Ji,Ass).call(this),ye(this,gN).resolve();return}this.setEditingState(!0),await ds(this,Ji,Css).call(this),this.unselectAll();for(const a of ye(this,Zv).values())a.updateMode(t);if(!n){r&&this.addNewEditorFromKeyboard(),ye(this,gN).resolve();return}for(const a of ye(this,o0).values())a.annotationElementId===n?(this.setSelected(a),a.enterInEditMode()):a.unselect();ye(this,gN).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==ye(this,nv)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,n){var r;if(ye(this,vS)){switch(t){case td.CREATE:this.currentLayer.addNewEditor();return;case td.HIGHLIGHT_DEFAULT_COLOR:(r=ye(this,rre))==null||r.updateColor(n);break;case td.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(ye(this,ire)||Yt(this,ire,new Map)).set(t,n),this.showAllEditors("highlight",n);break}for(const a of ye(this,Nm))a.updateParams(t,n);for(const a of ye(this,vS))a.updateDefaultParams(t,n)}}showAllEditors(t,n,r=!1){var i;for(const l of ye(this,o0).values())l.editorType===t&&l.show(n);(((i=ye(this,ire))==null?void 0:i.get(td.HIGHLIGHT_SHOW_ALL))??!0)!==n&&ds(this,Ji,KM).call(this,[[td.HIGHLIGHT_SHOW_ALL,n]])}enableWaiting(t=!1){if(ye(this,nre)!==t){Yt(this,nre,t);for(const n of ye(this,Zv).values())t?n.disableClick():n.enableClick(),n.div.classList.toggle("waiting",t)}}getEditors(t){const n=[];for(const r of ye(this,o0).values())r.pageIndex===t&&n.push(r);return n}getEditor(t){return ye(this,o0).get(t)}addEditor(t){ye(this,o0).set(t.id,t)}removeEditor(t){var n;t.div.contains(document.activeElement)&&(ye(this,D5)&&clearTimeout(ye(this,D5)),Yt(this,D5,setTimeout(()=>{this.focusMainContainer(),Yt(this,D5,null)},0))),ye(this,o0).delete(t.id),this.unselect(t),(!t.annotationElementId||!ye(this,F8).has(t.annotationElementId))&&((n=ye(this,BA))==null||n.remove(t.id))}addDeletedAnnotationElement(t){ye(this,F8).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return ye(this,F8).has(t)}removeDeletedAnnotationElement(t){ye(this,F8).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){ye(this,Aj)!==t&&(Yt(this,Aj,t),t&&ds(this,Ji,KM).call(this,t.propertiesToUpdate))}updateUI(t){ye(this,Ji,Ess)===t&&ds(this,Ji,KM).call(this,t.propertiesToUpdate)}toggleSelected(t){if(ye(this,Nm).has(t)){ye(this,Nm).delete(t),t.unselect(),ds(this,Ji,J1).call(this,{hasSelectedEditor:this.hasSelection});return}ye(this,Nm).add(t),t.select(),ds(this,Ji,KM).call(this,t.propertiesToUpdate),ds(this,Ji,J1).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const n of ye(this,Nm))n!==t&&n.unselect();ye(this,Nm).clear(),ye(this,Nm).add(t),t.select(),ds(this,Ji,KM).call(this,t.propertiesToUpdate),ds(this,Ji,J1).call(this,{hasSelectedEditor:!0})}isSelected(t){return ye(this,Nm).has(t)}get firstSelectedEditor(){return ye(this,Nm).values().next().value}unselect(t){t.unselect(),ye(this,Nm).delete(t),ds(this,Ji,J1).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return ye(this,Nm).size!==0}get isEnterHandled(){return ye(this,Nm).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){ye(this,yS).undo(),ds(this,Ji,J1).call(this,{hasSomethingToUndo:ye(this,yS).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:ds(this,Ji,jQ).call(this)})}redo(){ye(this,yS).redo(),ds(this,Ji,J1).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:ye(this,yS).hasSomethingToRedo(),isEmpty:ds(this,Ji,jQ).call(this)})}addCommands(t){ye(this,yS).add(t),ds(this,Ji,J1).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:ds(this,Ji,jQ).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...ye(this,Nm)],n=()=>{for(const a of t)a.remove()},r=()=>{for(const a of t)ds(this,Ji,wZe).call(this,a)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){var t;(t=ye(this,Aj))==null||t.commitOrRemove()}hasSomethingToControl(){return ye(this,Aj)||this.hasSelection}selectAll(){for(const t of ye(this,Nm))t.commit();ds(this,Ji,jZe).call(this,ye(this,o0).values())}unselectAll(){if(!(ye(this,Aj)&&(ye(this,Aj).commitOrRemove(),ye(this,nv)!==Rd.NONE))&&this.hasSelection){for(const t of ye(this,Nm))t.unselect();ye(this,Nm).clear(),ds(this,Ji,J1).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,n,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;ye(this,VP)[0]+=t,ye(this,VP)[1]+=n;const[a,i]=ye(this,VP),l=[...ye(this,Nm)],o=1e3;ye(this,O5)&&clearTimeout(ye(this,O5)),Yt(this,O5,setTimeout(()=>{Yt(this,O5,null),ye(this,VP)[0]=ye(this,VP)[1]=0,this.addCommands({cmd:()=>{for(const c of l)ye(this,o0).has(c.id)&&c.translateInPage(a,i)},undo:()=>{for(const c of l)ye(this,o0).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),Yt(this,R5,new Map);for(const t of ye(this,Nm))ye(this,R5).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!ye(this,R5))return!1;this.disableUserSelect(!1);const t=ye(this,R5);Yt(this,R5,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,o0).has(a.id)){const c=ye(this,Zv).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,R5))for(const r of ye(this,R5).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,Nm).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return ye(this,Aj)===t}getActive(){return ye(this,Aj)}getMode(){return ye(this,nv)}get imageManager(){return eh(this,"imageManager",new gZe)}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"&&ds(this,Ji,F3e).call(this,"main_toolbar"))};window.addEventListener("pointerup",h,{signal:u}),window.addEventListener("blur",h,{signal:u})}},F3e=function(t=""){ye(this,nv)===Rd.HIGHLIGHT?this.highlightSelection(t):ye(this,ere)&&ds(this,Ji,bss).call(this)},wss=function(){document.addEventListener("selectionchange",ds(this,Ji,_ss).bind(this),{signal:this._signal})},jss=function(){if(ye(this,BP))return;Yt(this,BP,new AbortController);const t=this.combinedSignal(ye(this,BP));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},Nss=function(){var t;(t=ye(this,BP))==null||t.abort(),Yt(this,BP,null)},vZe=function(){if(ye(this,qP))return;Yt(this,qP,new AbortController);const t=this.combinedSignal(ye(this,qP));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},kss=function(){var t;(t=ye(this,qP))==null||t.abort(),Yt(this,qP,null)},bZe=function(){if(ye(this,zP))return;Yt(this,zP,new AbortController);const t=this.combinedSignal(ye(this,zP));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})},_Ze=function(){var t;(t=ye(this,zP))==null||t.abort(),Yt(this,zP,null)},Sss=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},J1=function(t){Object.entries(t).some(([r,a])=>ye(this,ore)[r]!==a)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(ye(this,ore),t)}),ye(this,nv)===Rd.HIGHLIGHT&&t.hasSelectedEditor===!1&&ds(this,Ji,KM).call(this,[[td.HIGHLIGHT_FREE,!0]]))},KM=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},Css=async function(){if(!ye(this,UP)){Yt(this,UP,!0);const t=[];for(const n of ye(this,Zv).values())t.push(n.enable());await Promise.all(t);for(const n of ye(this,o0).values())n.enable()}},Ass=function(){if(this.unselectAll(),ye(this,UP)){Yt(this,UP,!1);for(const t of ye(this,Zv).values())t.disable();for(const t of ye(this,o0).values())t.disable()}},wZe=function(t){const n=ye(this,Zv).get(t.pageIndex);n?n.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},Ess=function(){let t=null;for(t of ye(this,Nm));return t},jQ=function(){if(ye(this,o0).size===0)return!0;if(ye(this,o0).size===1)for(const t of ye(this,o0).values())return t.isEmpty();return!1},jZe=function(t){for(const n of ye(this,Nm))n.unselect();ye(this,Nm).clear();for(const n of t)n.isEmpty()||(ye(this,Nm).add(n),n.select());ds(this,Ji,J1).call(this,{hasSelectedEditor:this.hasSelection})},_r(gq,"TRANSLATE_SMALL",1),_r(gq,"TRANSLATE_BIG",10);let mB=gq;var rv,z5,bS,mH,B5,Ej,fH,$5,rw,qA,$8,U5,HP,HS,NQ,O3e;const t_=class t_{constructor(t){ys(this,HS);ys(this,rv,null);ys(this,z5,!1);ys(this,bS,null);ys(this,mH,null);ys(this,B5,null);ys(this,Ej,null);ys(this,fH,!1);ys(this,$5,null);ys(this,rw,null);ys(this,qA,null);ys(this,$8,null);ys(this,U5,!1);Yt(this,rw,t),Yt(this,U5,t._uiManager.useNewAltTextFlow),ye(t_,HP)||Yt(t_,HP,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){t_._l10n??(t_._l10n=t)}async render(){const t=Yt(this,bS,document.createElement("button"));t.className="altText",t.tabIndex="0";const n=Yt(this,mH,document.createElement("span"));t.append(n),ye(this,U5)?(t.classList.add("new"),t.setAttribute("data-l10n-id",ye(t_,HP).missing),n.setAttribute("data-l10n-id",ye(t_,HP)["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,rw)._uiManager._signal;t.addEventListener("contextmenu",fk,{signal:r}),t.addEventListener("pointerdown",i=>i.stopPropagation(),{signal:r});const a=i=>{i.preventDefault(),ye(this,rw)._uiManager.editAltText(ye(this,rw)),ye(this,U5)&&ye(this,rw)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:ye(this,HS,NQ)}})};return t.addEventListener("click",a,{capture:!0,signal:r}),t.addEventListener("keydown",i=>{i.target===t&&i.key==="Enter"&&(Yt(this,fH,!0),a(i))},{signal:r}),await ds(this,HS,O3e).call(this),t}finish(){ye(this,bS)&&(ye(this,bS).focus({focusVisible:ye(this,fH)}),Yt(this,fH,!1))}isEmpty(){return ye(this,U5)?ye(this,rv)===null:!ye(this,rv)&&!ye(this,z5)}hasData(){return ye(this,U5)?ye(this,rv)!==null||!!ye(this,qA):this.isEmpty()}get guessedText(){return ye(this,qA)}async setGuessedText(t){ye(this,rv)===null&&(Yt(this,qA,t),Yt(this,$8,await t_._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),ds(this,HS,O3e).call(this))}toggleAltTextBadge(t=!1){var n;if(!ye(this,U5)||ye(this,rv)){(n=ye(this,$5))==null||n.remove(),Yt(this,$5,null);return}if(!ye(this,$5)){const r=Yt(this,$5,document.createElement("div"));r.className="noAltTextBadge",ye(this,rw).div.append(r)}ye(this,$5).classList.toggle("hidden",!t)}serialize(t){let n=ye(this,rv);return!t&&ye(this,qA)===n&&(n=ye(this,$8)),{altText:n,decorative:ye(this,z5),guessedText:ye(this,qA),textWithDisclaimer:ye(this,$8)}}get data(){return{altText:ye(this,rv),decorative:ye(this,z5)}}set data({altText:t,decorative:n,guessedText:r,textWithDisclaimer:a,cancel:i=!1}){r&&(Yt(this,qA,r),Yt(this,$8,a)),!(ye(this,rv)===t&&ye(this,z5)===n)&&(i||(Yt(this,rv,t),Yt(this,z5,n)),ds(this,HS,O3e).call(this))}toggle(t=!1){ye(this,bS)&&(!t&&ye(this,Ej)&&(clearTimeout(ye(this,Ej)),Yt(this,Ej,null)),ye(this,bS).disabled=!t)}shown(){ye(this,rw)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:ye(this,HS,NQ)}})}destroy(){var t,n;(t=ye(this,bS))==null||t.remove(),Yt(this,bS,null),Yt(this,mH,null),Yt(this,B5,null),(n=ye(this,$5))==null||n.remove(),Yt(this,$5,null)}};rv=new WeakMap,z5=new WeakMap,bS=new WeakMap,mH=new WeakMap,B5=new WeakMap,Ej=new WeakMap,fH=new WeakMap,$5=new WeakMap,rw=new WeakMap,qA=new WeakMap,$8=new WeakMap,U5=new WeakMap,HP=new WeakMap,HS=new WeakSet,NQ=function(){return ye(this,rv)&&"added"||ye(this,rv)===null&&this.guessedText&&"review"||"missing"},O3e=async function(){var a,i,l;const t=ye(this,bS);if(!t)return;if(ye(this,U5)){if(t.classList.toggle("done",!!ye(this,rv)),t.setAttribute("data-l10n-id",ye(t_,HP)[ye(this,HS,NQ)]),(a=ye(this,mH))==null||a.setAttribute("data-l10n-id",ye(t_,HP)[`${ye(this,HS,NQ)}-label`]),!ye(this,rv)){(i=ye(this,B5))==null||i.remove();return}}else{if(!ye(this,rv)&&!ye(this,z5)){t.classList.remove("done"),(l=ye(this,B5))==null||l.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let n=ye(this,B5);if(!n){Yt(this,B5,n=document.createElement("span")),n.className="tooltip",n.setAttribute("role","tooltip"),n.id=`alt-text-tooltip-${ye(this,rw).id}`;const o=100,c=ye(this,rw)._uiManager._signal;c.addEventListener("abort",()=>{clearTimeout(ye(this,Ej)),Yt(this,Ej,null)},{once:!0}),t.addEventListener("mouseenter",()=>{Yt(this,Ej,setTimeout(()=>{Yt(this,Ej,null),ye(this,B5).classList.add("show"),ye(this,rw)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:c}),t.addEventListener("mouseleave",()=>{var d;ye(this,Ej)&&(clearTimeout(ye(this,Ej)),Yt(this,Ej,null)),(d=ye(this,B5))==null||d.classList.remove("show")},{signal:c})}ye(this,z5)?n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(n.removeAttribute("data-l10n-id"),n.textContent=ye(this,rv)),n.parentNode||t.append(n);const r=ye(this,rw).getImageForAltText();r==null||r.setAttribute("aria-describedby",n.id)},ys(t_,HP,null),_r(t_,"_l10n",null);let hPe=t_;var U8,_S,xg,pH,q8,Xv,V8,GP,cre,H8,WP,dre,G8,VA,q5,gH,xH,xN,ure,lIe,Vd,NZe,hre,kZe,SZe,Tss,Mss,CZe,AZe,EZe,Pss,TZe,Iss,Lss,Rss,MZe,kQ;const pm=class pm{constructor(t){ys(this,Vd);ys(this,U8,null);ys(this,_S,null);ys(this,xg,null);ys(this,pH,!1);ys(this,q8,!1);ys(this,Xv,null);ys(this,V8,null);ys(this,GP,null);ys(this,cre,"");ys(this,H8,!1);ys(this,WP,null);ys(this,dre,!1);ys(this,G8,!1);ys(this,VA,!1);ys(this,q5,null);ys(this,gH,0);ys(this,xH,0);ys(this,xN,null);_r(this,"_editToolbar",null);_r(this,"_initialOptions",Object.create(null));_r(this,"_initialData",null);_r(this,"_isVisible",!0);_r(this,"_uiManager",null);_r(this,"_focusEventsAllowed",!0);ys(this,ure,!1);ys(this,lIe,pm._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=pm.prototype._resizeWithKeyboard,n=mB.TRANSLATE_SMALL,r=mB.TRANSLATE_BIG;return eh(this,"_resizerKeyboardManager",new Hie([[["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"],pm.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return eh(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const n=new UKn({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(pm._l10n??(pm._l10n=t),pm._l10nResizer||(pm._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"})),pm._borderLineWidth!==-1)return;const r=getComputedStyle(document.documentElement);pm._borderLineWidth=parseFloat(r.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,n){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,n){Np("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return ye(this,ure)}set _isDraggable(t){var n;Yt(this,ure,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,lIe)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):ds(this,Vd,kQ).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(ye(this,H8)?Yt(this,H8,!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){ds(this,Vd,NZe).call(this,this.parentDimensions,t,n)}translateInPage(t,n){ye(this,WP)||Yt(this,WP,[this.x,this.y]),ds(this,Vd,NZe).call(this,this.pageDimensions,t,n),this.div.scrollIntoView({block:"nearest"})}drag(t,n){ye(this,WP)||Yt(this,WP,[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,WP)&&(ye(this,WP)[0]!==this.x||ye(this,WP)[1]!==this.y)}getBaseTranslation(){const[t,n]=this.parentDimensions,{_borderLineWidth:r}=pm,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 ds(r=pm,hre,kZe).call(r,t,n,this.parentRotation)}pageTranslationToScreen(t,n){var r;return ds(r=pm,hre,kZe).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,q8)||(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,q8)&&n.endsWith("%");if(a&&i)return;const[l,o]=this.parentDimensions;a||(t.width=`${(100*parseFloat(r)/l).toFixed(2)}%`),!ye(this,q8)&&!i&&(t.height=`${(100*parseFloat(n)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=ye(this,xg))==null||t.finish()}async addEditToolbar(){return this._editToolbar||ye(this,G8)?this._editToolbar:(this._editToolbar=new fZe(this),this.div.append(this._editToolbar.render()),ye(this,xg)&&await this._editToolbar.addAltText(ye(this,xg)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=ye(this,xg))==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,xg)||(hPe.initialize(pm._l10n),Yt(this,xg,new hPe(this)),ye(this,U8)&&(ye(this,xg).data=ye(this,U8),Yt(this,U8,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=ye(this,xg))==null?void 0:t.data}set altTextData(t){ye(this,xg)&&(ye(this,xg).data=t)}get guessedAltText(){var t;return(t=ye(this,xg))==null?void 0:t.guessedText}async setGuessedAltText(t){var n;await((n=ye(this,xg))==null?void 0:n.setGuessedText(t))}serializeAltText(t){var n;return(n=ye(this,xg))==null?void 0:n.serialize(t)}hasAltText(){return!!ye(this,xg)&&!ye(this,xg).isEmpty()}hasAltTextData(){var t;return((t=ye(this,xg))==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,pH)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),ds(this,Vd,TZe).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),uPe(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:n}=k_.platform;if(t.button!==0||t.ctrlKey&&n){t.preventDefault();return}if(Yt(this,H8,!0),this._isDraggable){ds(this,Vd,Pss).call(this,t);return}ds(this,Vd,EZe).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){ye(this,q5)&&clearTimeout(ye(this,q5)),Yt(this,q5,setTimeout(()=>{var t;Yt(this,q5,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(){Yt(this,G8,!0)}disableEditMode(){Yt(this,G8,!1)}isInEditMode(){return ye(this,G8)}shouldGetKeyboardEvents(){return ye(this,VA)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){ds(this,Vd,TZe).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){Np("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,Yt(a,U8,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,GP))==null||t.abort(),Yt(this,GP,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),ye(this,q5)&&(clearTimeout(ye(this,q5)),Yt(this,q5,null)),ds(this,Vd,kQ).call(this),this.removeEditToolbar(),ye(this,xN)){for(const n of ye(this,xN).values())clearTimeout(n);Yt(this,xN,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(ds(this,Vd,Tss).call(this),ye(this,Xv).classList.remove("hidden"),uPe(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),Yt(this,V8,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const n=ye(this,Xv).children;if(!ye(this,_S)){Yt(this,_S,Array.from(n));const l=ds(this,Vd,Iss).bind(this),o=ds(this,Vd,Lss).bind(this),c=this._uiManager._signal;for(const d of ye(this,_S)){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",ds(this,Vd,Rss).bind(this,u),{signal:c}),d.setAttribute("data-l10n-id",pm._l10nResizer[u])}}const r=ye(this,_S)[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,_S).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,xg))==null||r.toggleAltTextBadge(!1)}unselect(){var t,n,r,a,i;(t=ye(this,Xv))==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,xg))==null||i.toggleAltTextBadge(!0)}updateParams(t,n){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return ye(this,dre)}set isEditing(t){Yt(this,dre,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,n){Yt(this,q8,!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,xN)||Yt(this,xN,new Map);const{action:r}=t;let a=ye(this,xN).get(r);a&&clearTimeout(a),a=setTimeout(()=>{this._reportTelemetry(t),ye(this,xN).delete(r),ye(this,xN).size===0&&Yt(this,xN,null)},pm._telemetryTimeout),ye(this,xN).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),Yt(this,pH,!1)}disable(){this.div&&(this.div.tabIndex=-1),Yt(this,pH,!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()}};U8=new WeakMap,_S=new WeakMap,xg=new WeakMap,pH=new WeakMap,q8=new WeakMap,Xv=new WeakMap,V8=new WeakMap,GP=new WeakMap,cre=new WeakMap,H8=new WeakMap,WP=new WeakMap,dre=new WeakMap,G8=new WeakMap,VA=new WeakMap,q5=new WeakMap,gH=new WeakMap,xH=new WeakMap,xN=new WeakMap,ure=new WeakMap,lIe=new WeakMap,Vd=new WeakSet,NZe=function([t,n],r,a){[r,a]=this.screenToPageTranslation(r,a),this.x+=r/t,this.y+=a/n,this.fixAndSetPosition()},hre=new WeakSet,kZe=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]}},SZe=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]}},Tss=function(){if(ye(this,Xv))return;Yt(this,Xv,document.createElement("div")),ye(this,Xv).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,Xv).append(a),a.classList.add("resizer",r),a.setAttribute("data-resizer-name",r),a.addEventListener("pointerdown",ds(this,Vd,Mss).bind(this,r),{signal:n}),a.addEventListener("contextmenu",fk,{signal:n}),a.tabIndex=-1}this.div.prepend(ye(this,Xv))},Mss=function(t,n){var g;n.preventDefault();const{isMac:r}=k_.platform;if(n.button!==0||n.ctrlKey&&r)return;(g=ye(this,xg))==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",ds(this,Vd,AZe).bind(this,t),{passive:!0,capture:!0,signal:l}),window.addEventListener("contextmenu",fk,{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,xg))==null||x.toggle(!0),this._isDraggable=a,this.parent.div.style.cursor=h,this.div.style.cursor=m,ds(this,Vd,CZe).call(this,o,c,d,u)};window.addEventListener("pointerup",f,{signal:l}),window.addEventListener("blur",f,{signal:l})},CZe=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})},AZe=function(t,n){const[r,a]=this.parentDimensions,i=this.x,l=this.y,o=this.width,c=this.height,d=pm.MIN_SIZE/r,u=pm.MIN_SIZE/a,h=X=>Math.round(X*1e4)/1e4,m=ds(this,Vd,SZe).call(this,this.rotation),f=(X,ae)=>[m[0]*X+m[2]*ae,m[1]*X+m[3]*ae],g=ds(this,Vd,SZe).call(this,360-this.rotation),x=(X,ae)=>[g[0]*X+g[2]*ae,g[1]*X+g[3]*ae];let v,y,b=!1,w=!1;switch(t){case"topLeft":b=!0,v=(X,ae)=>[0,0],y=(X,ae)=>[X,ae];break;case"topMiddle":v=(X,ae)=>[X/2,0],y=(X,ae)=>[X/2,ae];break;case"topRight":b=!0,v=(X,ae)=>[X,0],y=(X,ae)=>[0,ae];break;case"middleRight":w=!0,v=(X,ae)=>[X,ae/2],y=(X,ae)=>[0,ae/2];break;case"bottomRight":b=!0,v=(X,ae)=>[X,ae],y=(X,ae)=>[0,0];break;case"bottomMiddle":v=(X,ae)=>[X/2,ae],y=(X,ae)=>[X/2,0];break;case"bottomLeft":b=!0,v=(X,ae)=>[0,ae],y=(X,ae)=>[X,0];break;case"middleLeft":w=!0,v=(X,ae)=>[0,ae/2],y=(X,ae)=>[X,ae/2];break}const S=v(o,c),A=y(o,c);let E=f(...A);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(A[0]-S[0]-O,A[1]-S[1]-U)/X,1/o,1/c),d/o,u/c)}else w?R=Math.max(d,Math.min(1,Math.abs(A[0]-S[0]-O)))/o:D=Math.max(u,Math.min(1,Math.abs(A[1]-S[1]-U)))/c;const W=h(o*R),V=h(c*D);E=f(...y(W,V));const G=I-E[0],Z=P-E[1];this.width=W,this.height=V,this.x=G,this.y=Z,this.setDims(r*W,a*V),this.fixAndSetPosition()},EZe=function(t){const{isMac:n}=k_.platform;t.ctrlKey&&!n||t.shiftKey||t.metaKey&&n?this.parent.toggleSelected(this):this.parent.setSelected(this)},Pss=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"),Yt(this,gH,t.clientX),Yt(this,xH,t.clientY);const l=o=>{const{clientX:c,clientY:d}=o,[u,h]=this.screenToPageTranslation(c-ye(this,gH),d-ye(this,xH));Yt(this,gH,c),Yt(this,xH,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"),Yt(this,H8,!1),this._uiManager.endDragSession()||ds(this,Vd,EZe).call(this,t)};window.addEventListener("pointerup",i,{signal:a}),window.addEventListener("blur",i,{signal:a})},TZe=function(){if(ye(this,GP)||!this.div)return;Yt(this,GP,new AbortController);const t=this._uiManager.combinedSignal(ye(this,GP));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},Iss=function(t){pm._resizerKeyboardManager.exec(this,t)},Lss=function(t){var n;ye(this,VA)&&((n=t.relatedTarget)==null?void 0:n.parentNode)!==ye(this,Xv)&&ds(this,Vd,kQ).call(this)},Rss=function(t){Yt(this,cre,ye(this,VA)?t:"")},MZe=function(t){if(ye(this,_S))for(const n of ye(this,_S))n.tabIndex=t},kQ=function(){if(Yt(this,VA,!1),ds(this,Vd,MZe).call(this,-1),ye(this,V8)){const{savedX:t,savedY:n,savedWidth:r,savedHeight:a}=ye(this,V8);ds(this,Vd,CZe).call(this,t,n,r,a),Yt(this,V8,null)}},ys(pm,hre),_r(pm,"_l10n",null),_r(pm,"_l10nResizer",null),_r(pm,"_borderLineWidth",-1),_r(pm,"_colorManager",new xZe),_r(pm,"_zIndex",1),_r(pm,"_telemetryTimeout",1e3);let Cm=pm;class UKn extends Cm{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const K4t=3285377520,iN=4294901760,a5=65535;class Dss{constructor(t){this.h1=t?t&4294967295:K4t,this.h2=t?t&4294967295:K4t}update(t){let n,r;if(typeof t=="string"){n=new Uint8Array(t.length*2),r=0;for(let x=0,v=t.length;x>>8,n[r++]=y&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&a5,g=m&a5;for(let x=0;x>>17,o=o*m&iN|o*g&a5,d^=o,d=d<<13|d>>>19,d=d*5+3864292196):(c=l[x],c=c*h&iN|c*f&a5,c=c<<15|c>>>17,c=c*m&iN|c*g&a5,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&iN|o*f&a5,o=o<<15|o>>>17,o=o*m&iN|o*g&a5,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&iN|t*36045&a5,n=n*4283543511&iN|((n<<16|t>>>16)*2950163797&iN)>>>16,t^=n>>>1,t=t*444984403&iN|t*60499&a5,n=n*3301882366&iN|((n<<16|t>>>16)*3120437893&iN)>>>16,t^=n>>>1,(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}}const PZe=Object.freeze({map:null,hash:"",transfer:void 0});var W8,K8,av,cIe,Fss;class Cot{constructor(){ys(this,cIe);ys(this,W8,!1);ys(this,K8,null);ys(this,av,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,n){const r=ye(this,av).get(t);return r===void 0?n:Object.assign(n,r)}getRawValue(t){return ye(this,av).get(t)}remove(t){if(ye(this,av).delete(t),ye(this,av).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const n of ye(this,av).values())if(n instanceof Cm)return;this.onAnnotationEditor(null)}}setValue(t,n){const r=ye(this,av).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,av).set(t,n);a&&ds(this,cIe,Fss).call(this),n instanceof Cm&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(n.constructor._type)}has(t){return ye(this,av).has(t)}getAll(){return ye(this,av).size>0?_ot(ye(this,av)):null}setAll(t){for(const[n,r]of Object.entries(t))this.setValue(n,r)}get size(){return ye(this,av).size}resetModified(){ye(this,W8)&&(Yt(this,W8,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new Oss(this)}get serializable(){if(ye(this,av).size===0)return PZe;const t=new Map,n=new Dss,r=[],a=Object.create(null);let i=!1;for(const[l,o]of ye(this,av)){const c=o instanceof Cm?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}:PZe}get editorStats(){let t=null;const n=new Map;for(const r of ye(this,av).values()){if(!(r instanceof Cm))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(){Yt(this,K8,null)}get modifiedIds(){if(ye(this,K8))return ye(this,K8);const t=[];for(const n of ye(this,av).values())!(n instanceof Cm)||!n.annotationElementId||!n.serialize()||t.push(n.annotationElementId);return Yt(this,K8,{ids:new Set(t),hash:t.join(",")})}}W8=new WeakMap,K8=new WeakMap,av=new WeakMap,cIe=new WeakSet,Fss=function(){ye(this,W8)||(Yt(this,W8,!0),typeof this.onSetModified=="function"&&this.onSetModified())};var mre;class Oss extends Cot{constructor(n){super();ys(this,mre);const{map:r,hash:a,transfer:i}=n.serializable,l=structuredClone(r,i?{transfer:i}:null);Yt(this,mre,{map:l,hash:a,transfer:i})}get print(){Np("Should not call PrintAnnotationStorage.print")}get serializable(){return ye(this,mre)}get modifiedIds(){return eh(this,"modifiedIds",{ids:new Set,hash:""})}}mre=new WeakMap;var yH;class qKn{constructor({ownerDocument:t=globalThis.document,styleElement:n=null}){ys(this,yH,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,yH).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:n}){if(!(!t||ye(this,yH).has(t.loadedName))){if(_0(!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,yH).add(r),n==null||n(t)}catch{tu(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(l)}return}Np("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 tu(`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 eh(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(f1||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),eh(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function n(){for(_0(!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 eh(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,n){function r(S,A){return S.charCodeAt(A)<<24|S.charCodeAt(A+1)<<16|S.charCodeAt(A+2)<<8|S.charCodeAt(A+3)&255}function a(S,A,E,I){const P=S.substring(0,A),R=S.substring(A+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,A){if(++d>30){tu("Load test font never loaded."),A();return}if(c.font="30px "+S,c.fillText(".",0,20),c.getImageData(0,0,1,1).data[3]>0){A();return}setTimeout(u.bind(null,S,A))}const h=`lt${Date.now()}${this.loadTestFontId++}`;let m=this._loadTestFont;m=a(m,976,h.length,h);const g=16,x=1482184792;let v=r(m,g);for(i=0,l=h.length-3;i{w.remove(),n.complete()})}}yH=new WeakMap;class VKn{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,${IKn(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){tu(`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 oA.MOVE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.moveTo(o,c)),i+=2}break;case oA.LINE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.lineTo(o,c)),i+=2}break;case oA.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 oA.RESTORE:a.push(o=>o.restore());break;case oA.SAVE:a.push(o=>o.save());break;case oA.SCALE:_0(a.length===2,"Scale command is only valid at the third position.");break;case oA.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 oA.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){Np("Abstract method `_fetch` called.")}}class $ss extends Bss{async _fetch(t){const n=await RDe(t,this.isCompressed?"arraybuffer":"text");return n instanceof ArrayBuffer?new Uint8Array(n):LDe(n)}}class Uss{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 Y8,Z8,V5,HA,n1,dIe,X8,jo,Jb,_U,wU,z3e,jU,qss,IZe,NU,SQ,CQ,LZe,AQ;class GKn extends Uss{constructor({docId:n,ownerDocument:r=globalThis.document}){super();ys(this,jo);ys(this,Y8);ys(this,Z8);ys(this,V5);ys(this,HA);ys(this,n1);ys(this,dIe);ys(this,X8,0);Yt(this,HA,n),Yt(this,n1,r)}addFilter(n){if(!n)return"none";let r=ye(this,jo,Jb).get(n);if(r)return r;const[a,i,l]=ds(this,jo,z3e).call(this,n),o=n.length===1?a:`${a}${i}${l}`;if(r=ye(this,jo,Jb).get(o),r)return ye(this,jo,Jb).set(n,r),r;const c=`g_${ye(this,HA)}_transfer_map_${Z0(this,X8)._++}`,d=ds(this,jo,jU).call(this,c);ye(this,jo,Jb).set(n,d),ye(this,jo,Jb).set(o,d);const u=ds(this,jo,NU).call(this,c);return ds(this,jo,CQ).call(this,a,i,l,u),d}addHCMFilter(n,r){var g;const a=`${n}-${r}`,i="base";let l=ye(this,jo,_U).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,_U).set(i,l)),!n||!r))return l.url;const o=ds(this,jo,AQ).call(this,n);n=ol.makeHexColor(...o);const c=ds(this,jo,AQ).call(this,r);if(r=ol.makeHexColor(...c),ye(this,jo,wU).style.color="",n==="#000000"&&r==="#ffffff"||n===r)return l.url;const d=new Array(256);for(let x=0;x<=255;x++){const v=x/255;d[x]=v<=.03928?v/12.92:((v+.055)/1.055)**2.4}const u=d.join(","),h=`g_${ye(this,HA)}_hcm_filter`,m=l.filter=ds(this,jo,NU).call(this,h);ds(this,jo,CQ).call(this,u,u,u,m),ds(this,jo,IZe).call(this,m);const f=(x,v)=>{const y=o[x]/255,b=c[x]/255,w=new Array(v+1);for(let S=0;S<=v;S++)w[S]=y+S/v*(b-y);return w.join(",")};return ds(this,jo,CQ).call(this,f(0,5),f(1,5),f(2,5),m),l.url=ds(this,jo,jU).call(this,h),l.url}addAlphaFilter(n){let r=ye(this,jo,Jb).get(n);if(r)return r;const[a]=ds(this,jo,z3e).call(this,[n]),i=`alpha_${a}`;if(r=ye(this,jo,Jb).get(i),r)return ye(this,jo,Jb).set(n,r),r;const l=`g_${ye(this,HA)}_alpha_map_${Z0(this,X8)._++}`,o=ds(this,jo,jU).call(this,l);ye(this,jo,Jb).set(n,o),ye(this,jo,Jb).set(i,o);const c=ds(this,jo,NU).call(this,l);return ds(this,jo,LZe).call(this,a,c),o}addLuminosityFilter(n){let r=ye(this,jo,Jb).get(n||"luminosity");if(r)return r;let a,i;if(n?([a]=ds(this,jo,z3e).call(this,[n]),i=`luminosity_${a}`):i="luminosity",r=ye(this,jo,Jb).get(i),r)return ye(this,jo,Jb).set(n,r),r;const l=`g_${ye(this,HA)}_luminosity_map_${Z0(this,X8)._++}`,o=ds(this,jo,jU).call(this,l);ye(this,jo,Jb).set(n,o),ye(this,jo,Jb).set(i,o);const c=ds(this,jo,NU).call(this,l);return ds(this,jo,qss).call(this,c),n&&ds(this,jo,LZe).call(this,a,c),o}addHighlightHCMFilter(n,r,a,i,l){var b;const o=`${r}-${a}-${i}-${l}`;let c=ye(this,jo,_U).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,_U).set(n,c)),!r||!a))return c.url;const[d,u]=[r,a].map(ds(this,jo,AQ).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(ds(this,jo,AQ).bind(this));m{const E=new Array(256),I=(m-h)/A,P=w/255,R=(S-w)/(255*A);let D=0;for(let O=0;O<=A;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(",")},v=`g_${ye(this,HA)}_hcm_${n}_filter`,y=c.filter=ds(this,jo,NU).call(this,v);return ds(this,jo,IZe).call(this,y),ds(this,jo,CQ).call(this,x(f[0],g[0],5),x(f[1],g[1],5),x(f[2],g[2],5),y),c.url=ds(this,jo,jU).call(this,v),c.url}destroy(n=!1){n&&ye(this,jo,_U).size!==0||(ye(this,V5)&&(ye(this,V5).parentNode.parentNode.remove(),Yt(this,V5,null)),ye(this,Z8)&&(ye(this,Z8).clear(),Yt(this,Z8,null)),Yt(this,X8,0))}}Y8=new WeakMap,Z8=new WeakMap,V5=new WeakMap,HA=new WeakMap,n1=new WeakMap,dIe=new WeakMap,X8=new WeakMap,jo=new WeakSet,Jb=function(){return ye(this,Z8)||Yt(this,Z8,new Map)},_U=function(){return ye(this,dIe)||Yt(this,dIe,new Map)},wU=function(){if(!ye(this,V5)){const n=ye(this,n1).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,n1).createElementNS(bA,"svg");a.setAttribute("width",0),a.setAttribute("height",0),Yt(this,V5,ye(this,n1).createElementNS(bA,"defs")),n.append(a),a.append(ye(this,V5)),ye(this,n1).body.append(n)}return ye(this,V5)},z3e=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(",")]},jU=function(n){if(ye(this,Y8)===void 0){Yt(this,Y8,"");const r=ye(this,n1).URL;r!==ye(this,n1).baseURI&&(DDe(r)?tu('#createUrl: ignore "data:"-URL for performance reasons.'):Yt(this,Y8,r.split("#",1)[0]))}return`url(${ye(this,Y8)}#${n})`},qss=function(n){const r=ye(this,n1).createElementNS(bA,"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)},IZe=function(n){const r=ye(this,n1).createElementNS(bA,"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)},NU=function(n){const r=ye(this,n1).createElementNS(bA,"filter");return r.setAttribute("color-interpolation-filters","sRGB"),r.setAttribute("id",n),ye(this,jo,wU).append(r),r},SQ=function(n,r,a){const i=ye(this,n1).createElementNS(bA,r);i.setAttribute("type","discrete"),i.setAttribute("tableValues",a),n.append(i)},CQ=function(n,r,a,i){const l=ye(this,n1).createElementNS(bA,"feComponentTransfer");i.append(l),ds(this,jo,SQ).call(this,l,"feFuncR",n),ds(this,jo,SQ).call(this,l,"feFuncG",r),ds(this,jo,SQ).call(this,l,"feFuncB",a)},LZe=function(n,r){const a=ye(this,n1).createElementNS(bA,"feComponentTransfer");r.append(a),ds(this,jo,SQ).call(this,a,"feFuncA",n)},AQ=function(n){return ye(this,jo,wU).style.color=n,Sot(getComputedStyle(ye(this,jo,wU)).getPropertyValue("color"))};class Vss{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){Np("Abstract method `_fetch` called.")}}class Hss extends Vss{async _fetch(t){const n=await RDe(t,"arraybuffer");return new Uint8Array(n)}}if(f1){var RZe=Promise.withResolvers(),ete=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=>{ete=t,RZe.resolve()},t=>{tu(`loadPackages: ${t}`),ete=new Map,RZe.resolve()})}class BL{static get promise(){return RZe.promise}static get(t){return ete==null?void 0:ete.get(t)}}async function Gss(s){const n=await BL.get("fs").promises.readFile(s);return new Uint8Array(n)}class WKn extends Uss{}class KKn extends zss{_createCanvas(t,n){return BL.get("canvas").createCanvas(t,n)}}class YKn extends Bss{async _fetch(t){return Gss(t)}}class ZKn extends Vss{async _fetch(t){return Gss(t)}}const c_={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function DZe(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 Aot{getPattern(){Np("Abstract method `getPattern` called.")}}class XKn extends Aot{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===c_.STROKE||a===c_.FILL){const l=n.current.getClippedPathBoundingBox(a,bg(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),DZe(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 DZe(t,this._bbox),i=this._createGradient(t);return i}}function A$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,v=(c[r+1]+t.offsetY)*t.scaleY,y=(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],A=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,Z,X,ae,le,re,te;for(let J=U;J<=W;J++){if(Jb?be=1:v===b?be=0:be=(v-J)/(v-b),V=x-(x-y)*be,G=E-(E-R)*be,Z=I-(I-D)*be,X=P-(P-O)*be}let ce;Jb?ce=1:ce=(g-J)/(g-b),ae=f-(f-y)*ce,le=w-(w-R)*ce,re=S-(S-D)*ce,te=A-(A-O)*ce;const ve=Math.round(Math.min(V,ae)),fe=Math.round(Math.max(V,ae));let ue=h*J+ve*4;for(let be=ve;be<=fe;be++)ce=(V-be)/(V-ae),ce<0?ce=0:ce>1&&(ce=1),u[ue++]=G-(G-le)*ce|0,u[ue++]=Z-(Z-re)*ce|0,u[ue++]=X-(X-te)*ce|0,u[ue++]=255}}function QKn(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?A=d:I=!0;const U=this.getSizeAndScale(S,this.ctx.canvas.width,b),W=this.getSizeAndScale(A,this.ctx.canvas.height,w),V=t.cachedCanvases.getCanvas("pattern",U.size,W.size),G=V.context,Z=o.createCanvasGraphics(G);if(Z.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(Z,a,l),G.translate(-U.scale*u,-W.scale*h),Z.transform(U.scale,0,0,W.scale,0,0),G.save(),this.clipBbox(Z,u,h,m,f),Z.baseTransform=bg(Z.ctx),Z.executeOperatorList(r),Z.endDrawing(),G.restore(),E||I){const X=V.canvas;E&&(S=c),I&&(A=d);const ae=this.getSizeAndScale(S,this.ctx.canvas.width,b),le=this.getSizeAndScale(A,this.ctx.canvas.height,w),re=ae.size,te=le.size,J=t.cachedCanvases.getCanvas("pattern-workaround",re,te),ce=J.context,ve=E?Math.floor(g/c):0,fe=I?Math.floor(x/d):0;for(let ue=0;ue<=ve;ue++)for(let be=0;be<=fe;be++)ce.drawImage(X,re*ue,te*be,re,te,0,0,re,te);return{canvas:J.canvas,scaleX:ae.scale,scaleY:le.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(uIe.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(bg(t.ctx),[n,r,a,i]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,n,r){const a=t.ctx,i=t.current;switch(n){case Y4t.COLORED:const l=this.ctx;a.fillStyle=l.fillStyle,a.strokeStyle=l.strokeStyle,i.fillColor=l.fillStyle,i.strokeColor=l.strokeStyle;break;case Y4t.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 SKn(`Unsupported paint type: ${n}`)}}getPattern(t,n,r,a){let i=r;a!==c_.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}};_r(uIe,"MAX_PATTERN_SIZE",3e3);let FZe=uIe;function sYn({src:s,srcPos:t=0,dest:n,width:r,height:a,nonBlackColor:i=4294967295,inverseDecode:l=!1}){const o=k_.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 aYn{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 Sue(s,t,n,r,a,i,l,o,c,d){const[u,h,m,f,g,x]=bg(s);if(h===0&&m===0){const b=l*u+g,w=Math.round(b),S=o*f+x,A=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)-A)||1;return s.setTransform(Math.sign(u),0,0,Math.sign(f),w,A),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,A=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)-A)||1;return s.setTransform(0,Math.sign(h),Math.sign(m),0,w,A),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 v=Math.hypot(u,h),y=Math.hypot(m,f);return[v*c,y*d]}function iYn(s){const{width:t,height:n}=s;if(t>J4t||n>J4t)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 y of s.data){let b=128;for(;b>0;)h[m++]=y&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[y]&&(l[d+c]=a[y],++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 y=o*i;const b=y+t;for(;y>4,l[y]&=S>>2|S<<2),x.lineTo(y%i,y/i|0),l[y]||--f}while(w!==y);--o}return h=null,l=null,function(y){y.save(),y.scale(1/t,-1/n),y.translate(0,-n),y.fill(x),y.beginPath(),y.restore()}}class e3t{constructor(t,n){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=css,this.textMatrixScale=1,this.fontMatrix=cZe,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=Qb.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=c_.FILL,n=null){const r=[this.minX,this.minY,this.maxX,this.maxY];if(t===c_.STROKE){n||Np("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=c_.FILL,n=null){return ol.intersect(this.clipBox,this.getPathBoundingBox(t,n))}}function t3t(s,t){if(typeof ImageData<"u"&&t instanceof ImageData){s.putImageData(t,0,0);return}const n=t.height,r=t.width,a=n%lw,i=(n-a)/lw,l=a===0?i:i+1,o=s.createImageData(r,lw);let c=0,d;const u=t.data,h=o.data;let m,f,g,x;if(t.kind===P3e.GRAYSCALE_1BPP){const v=u.byteLength,y=new Uint32Array(h.buffer,0,h.byteLength>>2),b=y.length,w=r+7>>3,S=4294967295,A=k_.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*lw)}else throw new Error(`bad image kind: ${t.kind}`)}function s3t(s,t){if(t.bitmap){s.drawImage(t.bitmap,0,0);return}const n=t.height,r=t.width,a=n%lw,i=(n-a)/lw,l=a===0?i:i+1,o=s.createImageData(r,lw);let c=0;const d=t.data,u=o.data;for(let h=0;hQ4t&&typeof r=="function",u=d?Date.now()+nYn: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!==fS.dependency)this[g].apply(this,i[o]);else for(const x of i[o]){const v=x.startsWith("g_")?m:f;if(!v.has(x))return v.get(x,r),o}if(o++,o===c)return o;if(d&&++h>Q4t){if(Date.now()>u)return r(),o;h=0}}}endDrawing(){ds(this,WL,OZe).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(),ds(this,WL,zZe).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=bg(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),s3t(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,v]=ol.getAxialAlignedBoundingBox([0,0,r,a],m),y=Math.round(x-f)||1,b=Math.round(v-g)||1,w=this.cachedCanvases.getCanvas("fillCanvas",y,b),S=w.context,A=f,E=g;S.translate(-A,-E),S.transform(...m),u||(u=this._scaleImage(h.canvas,lA(S)),u=u.img,c&&l&&c.set(d,u)),S.imageSmoothingEnabled=n3t(bg(S),t.interpolate),Sue(S,u,0,0,u.width,u.height,0,0,r,a),S.globalCompositeOperation="source-in";const I=ol.transform(lA(S),[1,0,0,1,-A,-E]);return S.fillStyle=l?i.getPattern(n,this,I,c_.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(A),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=oYn[t]}setLineJoin(t){this.ctx.lineJoin=lYn[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(...bg(this.suspendedCtx)),lX(this.suspendedCtx,i),rYn(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(),lX(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 v=ol.makeHexColor(...l);if(f<0||g<0||f+r>m.width||g+a>m.height){const y=this.cachedCanvases.getCanvas("maskExtension",r,a),b=y.context;b.drawImage(m,-f,-g),b.globalCompositeOperation="destination-atop",b.fillStyle=v,b.fillRect(0,0,r,a),b.globalCompositeOperation="source-over",m=y.canvas,f=g=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const y=new Path2D;y.rect(f,g,r,a),t.clip(y),t.globalCompositeOperation="destination-atop",t.fillStyle=v,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?(lX(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(),lX(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=bg(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;fX4t&&(d=X4t),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&Qb.FILL_STROKE_MASK,h=!!(c&Qb.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===Qb.FILL||u===Qb.FILL_STROKE)&&i.fill(),(u===Qb.STROKE||u===Qb.FILL_STROKE)&&i.stroke(),i.restore()):((u===Qb.FILL||u===Qb.FILL_STROKE)&&i.fillText(t,n,r),(u===Qb.STROKE||u===Qb.FILL_STROKE)&&i.strokeText(t,n,r)),h&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:bg(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 eh(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],v=n.textRenderingMode===Qb.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 y;if(n.patternFill){i.save();const E=n.fillColor.getPattern(i,this,lA(i),c_.FILL);y=bg(i),i.restore(),i.fillStyle=E}let b=n.lineWidth;const w=n.textMatrixScale;if(w===0||b===0){const E=n.textRenderingMode&Qb.FILL_STROKE_MASK;(E===Qb.STROKE||E===Qb.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,A;for(A=0;A0){const G=i.measureText(R).width*1e3/a*l;if(Wnew Wct(l,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};n=new FZe(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=tYn(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,lA(n),c_.SHADING);const a=lA(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(){Np("Should not call beginInlineImage")}beginImageData(){Np("Should not call beginImageData")}paintFormXObjectBegin(t,n){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=bg(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(bg(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||PDe("TODO: Support non-isolated groups."),t.knockout&&tu("Knockout groups not supported.");const r=bg(n);if(t.matrix&&n.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let a=ol.getAxialAlignedBoundingBox(t.bbox,bg(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()),lX(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=bg(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(ds(this,WL,OZe).call(this),Cue(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(bg(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),Cue(this.ctx)}else Cue(this.ctx),this.endPath(),this.ctx.rect(n[0],n[1],l,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new e3t(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...r),this.transform(...a)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),ds(this,WL,zZe).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=iYn(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=bg(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}};WL=new WeakSet,OZe=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)},zZe=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 FV=Wct;for(const s in fS)FV.prototype[s]!==void 0&&(FV.prototype[fS[s]]=FV.prototype[s]);var pre,gre;class hE{static get workerPort(){return ye(this,pre)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");Yt(this,pre,t)}static get workerSrc(){return ye(this,gre)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");Yt(this,gre,t)}}pre=new WeakMap,gre=new WeakMap,ys(hE,pre,null),ys(hE,gre,"");const Aue={DATA:1,ERROR:2},jy={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function yj(s){switch(s instanceof Error||typeof s=="object"&&s!==null||Np('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),s.name){case"AbortException":return new d9(s.message);case"MissingPDFException":return new c9(s.message);case"PasswordException":return new dZe(s.message,s.code);case"UnexpectedResponseException":return new IDe(s.message,s.status);case"UnknownErrorException":return new uZe(s.message,s.details);default:return new uZe(s.message,s.toString())}}var vH,ik,Wss,Kss,Yss,B3e;class EQ{constructor(t,n,r){ys(this,ik);ys(this,vH,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",ds(this,ik,Wss).bind(this),{signal:ye(this,vH).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:jy.PULL,streamId:i,desiredSize:d.desiredSize}),u.promise},cancel:d=>{_0(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:jy.CANCEL,streamId:i,reason:yj(d)}),u.promise}},r)}destroy(){var t;(t=ye(this,vH))==null||t.abort(),Yt(this,vH,null)}}vH=new WeakMap,ik=new WeakSet,Wss=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){ds(this,ik,Yss).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===Aue.DATA)a.resolve(t.data);else if(t.callback===Aue.ERROR)a.reject(yj(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:Aue.DATA,callbackId:t.callbackId,data:l})},function(l){i.postMessage({sourceName:r,targetName:a,callback:Aue.ERROR,callbackId:t.callbackId,reason:yj(l)})});return}if(t.streamId){ds(this,ik,Kss).call(this,t);return}n(t.data)},Kss=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:jy.ENQUEUE,streamId:n,chunk:d},h)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:jy.CLOSE,streamId:n}),delete l.streamSinks[n])},error(d){_0(d instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:jy.ERROR,streamId:n,reason:yj(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:jy.START_COMPLETE,streamId:n,success:!0})},function(d){i.postMessage({sourceName:r,targetName:a,stream:jy.START_COMPLETE,streamId:n,reason:yj(d)})})},Yss=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 jy.START_COMPLETE:t.success?l.startCall.resolve():l.startCall.reject(yj(t.reason));break;case jy.PULL_COMPLETE:t.success?l.pullCall.resolve():l.pullCall.reject(yj(t.reason));break;case jy.PULL:if(!o){i.postMessage({sourceName:r,targetName:a,stream:jy.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:jy.PULL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:jy.PULL_COMPLETE,streamId:n,reason:yj(c)})});break;case jy.ENQUEUE:if(_0(l,"enqueue should have stream controller"),l.isClosed)break;l.controller.enqueue(t.chunk);break;case jy.CLOSE:if(_0(l,"close should have stream controller"),l.isClosed)break;l.isClosed=!0,l.controller.close(),ds(this,ik,B3e).call(this,l,n);break;case jy.ERROR:_0(l,"error should have stream controller"),l.controller.error(yj(t.reason)),ds(this,ik,B3e).call(this,l,n);break;case jy.CANCEL_COMPLETE:t.success?l.cancelCall.resolve():l.cancelCall.reject(yj(t.reason)),ds(this,ik,B3e).call(this,l,n);break;case jy.CANCEL:if(!o)break;new Promise(function(c){var d;c((d=o.onCancel)==null?void 0:d.call(o,yj(t.reason)))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:jy.CANCEL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:jy.CANCEL_COMPLETE,streamId:n,reason:yj(c)})}),o.sinkCapability.reject(yj(t.reason)),o.isCancelled=!0,delete this.streamSinks[n];break;default:throw new Error("Unexpected stream case")}},B3e=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 Q8,xre;class dYn{constructor({parsedData:t,rawData:n}){ys(this,Q8);ys(this,xre);Yt(this,Q8,t),Yt(this,xre,n)}getRaw(){return ye(this,xre)}get(t){return ye(this,Q8).get(t)??null}getAll(){return _ot(ye(this,Q8))}has(t){return ye(this,Q8).has(t)}}Q8=new WeakMap,xre=new WeakMap;const kU=Symbol("INTERNAL");var yre,vre,bre,bH;class uYn{constructor(t,{name:n,intent:r,usage:a,rbGroups:i}){ys(this,yre,!1);ys(this,vre,!1);ys(this,bre,!1);ys(this,bH,!0);Yt(this,yre,!!(t&Fj.DISPLAY)),Yt(this,vre,!!(t&Fj.PRINT)),this.name=n,this.intent=r,this.usage=a,this.rbGroups=i}get visible(){if(ye(this,bre))return ye(this,bH);if(!ye(this,bH))return!1;const{print:t,view:n}=this.usage;return ye(this,yre)?(n==null?void 0:n.viewState)!=="OFF":ye(this,vre)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,n,r=!1){t!==kU&&Np("Internal method `_setVisible` called."),Yt(this,bre,r),Yt(this,bH,n)}}yre=new WeakMap,vre=new WeakMap,bre=new WeakMap,bH=new WeakMap;var KP,km,_H,wH,_re,BZe;class hYn{constructor(t,n=Fj.DISPLAY){ys(this,_re);ys(this,KP,null);ys(this,km,new Map);ys(this,_H,null);ys(this,wH,null);if(this.renderingIntent=n,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,Yt(this,wH,t.order);for(const r of t.groups)ye(this,km).set(r.id,new uYn(n,r));if(t.baseState==="OFF")for(const r of ye(this,km).values())r._setVisible(kU,!1);for(const r of t.on)ye(this,km).get(r)._setVisible(kU,!0);for(const r of t.off)ye(this,km).get(r)._setVisible(kU,!1);Yt(this,_H,this.getHash())}}isVisible(t){if(ye(this,km).size===0)return!0;if(!t)return PDe("Optional content group not defined."),!0;if(t.type==="OCG")return ye(this,km).has(t.id)?ye(this,km).get(t.id).visible:(tu(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return ds(this,_re,BZe).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const n of t.ids){if(!ye(this,km).has(n))return tu(`Optional content group not found: ${n}`),!0;if(ye(this,km).get(n).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const n of t.ids){if(!ye(this,km).has(n))return tu(`Optional content group not found: ${n}`),!0;if(!ye(this,km).get(n).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const n of t.ids){if(!ye(this,km).has(n))return tu(`Optional content group not found: ${n}`),!0;if(!ye(this,km).get(n).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const n of t.ids){if(!ye(this,km).has(n))return tu(`Optional content group not found: ${n}`),!0;if(ye(this,km).get(n).visible)return!1}return!0}return tu(`Unknown optional content policy ${t.policy}.`),!0}return tu(`Unknown group type ${t.type}.`),!0}setVisibility(t,n=!0,r=!0){var i;const a=ye(this,km).get(t);if(!a){tu(`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,km).get(o))==null||i._setVisible(kU,!1,!0));a._setVisible(kU,!!n,!0),Yt(this,KP,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,km).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}}Yt(this,KP,null)}get hasInitialVisibility(){return ye(this,_H)===null||this.getHash()===ye(this,_H)}getOrder(){return ye(this,km).size?ye(this,wH)?ye(this,wH).slice():[...ye(this,km).keys()]:null}getGroups(){return ye(this,km).size>0?_ot(ye(this,km)):null}getGroup(t){return ye(this,km).get(t)||null}getHash(){if(ye(this,KP)!==null)return ye(this,KP);const t=new Dss;for(const[n,r]of ye(this,km))t.update(`${n}:${r.visible}`);return Yt(this,KP,t.hexdigest())}}KP=new WeakMap,km=new WeakMap,_H=new WeakMap,wH=new WeakMap,_re=new WeakSet,BZe=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)});_0(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(){_0(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new fYn(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=new pYn(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 fYn{constructor(t,n,r=!1,a=null){this._stream=t,this._done=r||!1,this._filename=Not(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 pYn{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 gYn(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=LDe(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,v,y]=m;if(x=parseInt(x,10),x in h){if(x===0)break;continue}h[x]=[v,y]}const g=[];for(let x=0;x{if(!Zss(i.status))throw FDe(i.status,a);this._reader=i.body.getReader(),this._headersCapability.resolve();const l=i.headers,{allowRangeRequests:o,suggestedLength:c}=Tot({responseHeaders:l,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=c||this._contentLength,this._filename=Mot(l),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new d9("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:Qss(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}class yYn{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,Xss(i,this._withCredentials,this._abortController)).then(o=>{if(!Zss(o.status))throw FDe(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:Qss(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}const E$e=200,T$e=206;function vYn(s){const t=s.response;return typeof t!="string"?t:LDe(t).buffer}class bYn{constructor({url:t,httpHeaders:n,withCredentials:r}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=Eot(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=T$e):a.expectedStatus=E$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||E$e;if(!(i===E$e&&r.expectedStatus===T$e)&&i!==r.expectedStatus){(d=r.onError)==null||d.call(r,a.status);return}const o=vYn(a);if(i===T$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 _Yn{constructor(t){this._source=t,this._manager=new bYn(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 _0(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new wYn(this._manager,this._source),this._fullRequestReader}getRangeReader(t,n){const r=new jYn(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 wYn{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}=Tot({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});a&&(this._isRangeSupported=!0),this._contentLength=i||this._contentLength,this._filename=Mot(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=FDe(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 jYn{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=FDe(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 NYn=/^[a-z][a-z0-9\-+.]+:/i;function kYn(s){if(NYn.test(s))return new URL(s);const t=BL.get("url");return new URL(t.pathToFileURL(s))}function Jss(s,t,n){return s.protocol==="http:"?BL.get("http").request(s,{headers:t},n):BL.get("https").request(s,{headers:t},n)}class SYn{constructor(t){this.source=t,this.url=kYn(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=Eot(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 _0(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new EYn(this):new CYn(this),this._fullRequestReader}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=this.isFsUrl?new TYn(this,t,n):new AYn(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 ens{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 d9("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class tns{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 CYn extends ens{constructor(t){super(t);const n=Object.fromEntries(t.headers),r=a=>{if(a.statusCode===404){const c=new c9(`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}=Tot({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=l,this._contentLength=o||this._contentLength,this._filename=Mot(i)};this._request=Jss(this._url,n,r),this._request.on("error",a=>{this._storedError=a,this._headersCapability.reject(a)}),this._request.end()}}class AYn extends tns{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 c9(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(l)};this._request=Jss(this._url,a,i),this._request.on("error",l=>{this._storedError=l}),this._request.end()}}class EYn extends ens{constructor(t){super(t);const n=BL.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 c9(`Missing PDF "${this._url}".`)),this._storedError=r,this._headersCapability.reject(r)})}}class TYn extends tns{constructor(t,n,r){super(t);const a=BL.get("fs");this._setReadableStream(a.createReadStream(this._url,{start:n,end:r-1}))}}const MYn=1e5,J_=30,PYn=.8;var bIt,YP,aw,wre,jre,J8,GA,Nre,kre,ez,jH,NH,ZP,kH,Sre,SH,tz,Cre,Are,sz,nz,Ere,XP,CH,_T,sns,nns,$Ze,w2,$3e,UZe,rns,ans;const a0=class a0{constructor({textContentSource:t,container:n,viewport:r}){ys(this,_T);ys(this,YP,Promise.withResolvers());ys(this,aw,null);ys(this,wre,!1);ys(this,jre,!!((bIt=globalThis.FontInspector)!=null&&bIt.enabled));ys(this,J8,null);ys(this,GA,null);ys(this,Nre,0);ys(this,kre,0);ys(this,ez,null);ys(this,jH,null);ys(this,NH,0);ys(this,ZP,0);ys(this,kH,Object.create(null));ys(this,Sre,[]);ys(this,SH,null);ys(this,tz,[]);ys(this,Cre,new WeakMap);ys(this,Are,null);var c;if(t instanceof ReadableStream)Yt(this,SH,t);else if(typeof t=="object")Yt(this,SH,new ReadableStream({start(d){d.enqueue(t),d.close()}}));else throw new Error('No "textContentSource" parameter specified.');Yt(this,aw,Yt(this,jH,n)),Yt(this,ZP,r.scale*(globalThis.devicePixelRatio||1)),Yt(this,NH,r.rotation),Yt(this,GA,{div:null,properties:null,ctx:null});const{pageWidth:a,pageHeight:i,pageX:l,pageY:o}=r.rawDims;Yt(this,Are,[1,0,0,-1,-l,o+i]),Yt(this,kre,a),Yt(this,Nre,i),ds(c=a0,w2,rns).call(c),hB(n,r),ye(this,YP).promise.finally(()=>{ye(a0,CH).delete(this),Yt(this,GA,null),Yt(this,kH,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:n}=k_.platform;return eh(this,"fontFamilyMap",new Map([["sans-serif",`${t&&n?"Calibri, ":""}sans-serif`],["monospace",`${t&&n?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{ye(this,ez).read().then(({value:n,done:r})=>{if(r){ye(this,YP).resolve();return}ye(this,J8)??Yt(this,J8,n.lang),Object.assign(ye(this,kH),n.styles),ds(this,_T,sns).call(this,n.items),t()},ye(this,YP).reject)};return Yt(this,ez,ye(this,SH).getReader()),ye(a0,CH).add(this),t(),ye(this,YP).promise}update({viewport:t,onBefore:n=null}){var i;const r=t.scale*(globalThis.devicePixelRatio||1),a=t.rotation;if(a!==ye(this,NH)&&(n==null||n(),Yt(this,NH,a),hB(ye(this,jH),{rotation:a})),r!==ye(this,ZP)){n==null||n(),Yt(this,ZP,r);const l={div:null,properties:null,ctx:ds(i=a0,w2,$3e).call(i,ye(this,J8))};for(const o of ye(this,tz))l.properties=ye(this,Cre).get(o),l.div=o,ds(this,_T,$Ze).call(this,l)}}cancel(){var n;const t=new d9("TextLayer task cancelled.");(n=ye(this,ez))==null||n.cancel(t).catch(()=>{}),Yt(this,ez,null),ye(this,YP).reject(t)}get textDivs(){return ye(this,tz)}get textContentItemsStr(){return ye(this,Sre)}static cleanup(){if(!(ye(this,CH).size>0)){ye(this,sz).clear();for(const{canvas:t}of ye(this,nz).values())t.remove();ye(this,nz).clear()}}};YP=new WeakMap,aw=new WeakMap,wre=new WeakMap,jre=new WeakMap,J8=new WeakMap,GA=new WeakMap,Nre=new WeakMap,kre=new WeakMap,ez=new WeakMap,jH=new WeakMap,NH=new WeakMap,ZP=new WeakMap,kH=new WeakMap,Sre=new WeakMap,SH=new WeakMap,tz=new WeakMap,Cre=new WeakMap,Are=new WeakMap,sz=new WeakMap,nz=new WeakMap,Ere=new WeakMap,XP=new WeakMap,CH=new WeakMap,_T=new WeakSet,sns=function(t){var a,i;if(ye(this,wre))return;(i=ye(this,GA)).ctx??(i.ctx=ds(a=a0,w2,$3e).call(a,ye(this,J8)));const n=ye(this,tz),r=ye(this,Sre);for(const l of t){if(n.length>MYn){tu("Ignoring additional textDivs for performance reasons."),Yt(this,wre,!0);return}if(l.str===void 0){if(l.type==="beginMarkedContentProps"||l.type==="beginMarkedContent"){const o=ye(this,aw);Yt(this,aw,document.createElement("span")),ye(this,aw).classList.add("markedContent"),l.id!==null&&ye(this,aw).setAttribute("id",`${l.id}`),o.append(ye(this,aw))}else l.type==="endMarkedContent"&&Yt(this,aw,ye(this,aw).parentNode);continue}r.push(l.str),ds(this,_T,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,tz).push(n);const a=ol.transform(ye(this,Are),t.transform);let i=Math.atan2(a[1],a[0]);const l=ye(this,kH)[t.fontName];l.vertical&&(i+=Math.PI/2);let o=ye(this,jre)&&l.fontSubstitution||l.fontFamily;o=a0.fontFamilyMap.get(o)||o;const c=Math.hypot(a[2],a[3]),d=c*ds(x=a0,w2,ans).call(x,o,ye(this,J8));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,aw)===ye(this,jH)?(f.left=`${(100*u/ye(this,kre)).toFixed(2)}%`,f.top=`${(100*h/ye(this,Nre)).toFixed(2)}%`):(f.left=`${m}${u.toFixed(2)}px)`,f.top=`${m}${h.toFixed(2)}px)`),f.fontSize=`${m}${(ye(a0,XP)*c).toFixed(2)}px)`,f.fontFamily=o,r.fontSize=c,n.setAttribute("role","presentation"),n.textContent=t.str,n.dir=t.dir,ye(this,jre)&&(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 v=Math.abs(t.transform[0]),y=Math.abs(t.transform[3]);v!==y&&Math.max(v,y)/Math.min(v,y)>1.5&&(g=!0)}if(g&&(r.canvasWidth=l.vertical?t.height:t.width),ye(this,Cre).set(n,r),ye(this,GA).div=n,ye(this,GA).properties=r,ds(this,_T,$Ze).call(this,ye(this,GA)),r.hasText&&ye(this,aw).append(n),r.hasEOL){const v=document.createElement("br");v.setAttribute("role","presentation"),ye(this,aw).append(v)}},$Ze=function(t){var o;const{div:n,properties:r,ctx:a}=t,{style:i}=n;let l="";if(ye(a0,XP)>1&&(l=`scale(${1/ye(a0,XP)})`),r.canvasWidth!==0&&r.hasText){const{fontFamily:c}=i,{canvasWidth:d,fontSize:u}=r;ds(o=a0,w2,UZe).call(o,a,u*ye(this,ZP),c);const{width:h}=a.measureText(n.textContent);h>0&&(l=`scaleX(${d*ye(this,ZP)/h}) ${l}`)}r.angle!==0&&(l=`rotate(${r.angle}deg) ${l}`),l.length>0&&(i.transform=l)},w2=new WeakSet,$3e=function(t=null){let n=ye(this,nz).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,nz).set(t,n),ye(this,Ere).set(n,{size:0,family:""})}return n},UZe=function(t,n,r){const a=ye(this,Ere).get(t);n===a.size&&r===a.family||(t.font=`${n}px ${r}`,a.size=n,a.family=r)},rns=function(){if(ye(this,XP)!==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),Yt(this,XP,t.getBoundingClientRect().height),t.remove()},ans=function(t,n){const r=ye(this,sz).get(t);if(r)return r;const a=ds(this,w2,$3e).call(this,n);a.canvas.width=a.canvas.height=J_,ds(this,w2,UZe).call(this,a,J_,t);const i=a.measureText("");let l=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(l){const u=l/(l+o);return ye(this,sz).set(t,u),a.canvas.width=a.canvas.height=0,u}a.strokeStyle="red",a.clearRect(0,0,J_,J_),a.strokeText("g",0,0);let c=a.getImageData(0,0,J_,J_).data;o=0;for(let u=c.length-1-3;u>=0;u-=4)if(c[u]>0){o=Math.ceil(u/4/J_);break}a.clearRect(0,0,J_,J_),a.strokeText("A",0,J_),c=a.getImageData(0,0,J_,J_).data,l=0;for(let u=0,h=c.length;u0){l=J_-Math.floor(u/4/J_);break}a.canvas.width=a.canvas.height=0;const d=l?l/(l+o):PYn;return ye(this,sz).set(t,d),d},ys(a0,w2),ys(a0,sz,new Map),ys(a0,nz,new Map),ys(a0,Ere,new WeakMap),ys(a0,XP,null),ys(a0,CH,new Set);let pne=a0;class gne{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(gne.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 IYn=65536,LYn=100,RYn=5e3,DYn=f1?KKn:HKn,FYn=f1?YKn:$ss,OYn=f1?WKn:GKn,zYn=f1?ZKn:Hss;function BYn(s={}){typeof s=="string"||s instanceof URL?s={url:s}:(s instanceof ArrayBuffer||ArrayBuffer.isView(s))&&(s={data:s});const t=new qZe,{docId:n}=t,r=s.url?$Yn(s.url):null,a=s.data?UYn(s.data):null,i=s.httpHeaders||null,l=s.withCredentials===!0,o=s.password??null,c=s.range instanceof ins?s.range:null,d=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:IYn;let u=s.worker instanceof OV?s.worker:null;const h=s.verbosity,m=typeof s.docBaseUrl=="string"&&!DDe(s.docBaseUrl)?s.docBaseUrl:null,f=typeof s.cMapUrl=="string"?s.cMapUrl:null,g=s.cMapPacked!==!1,x=s.CMapReaderFactory||FYn,v=typeof s.standardFontDataUrl=="string"?s.standardFontDataUrl:null,y=s.StandardFontDataFactory||zYn,b=s.stopAtErrors!==!0,w=Number.isInteger(s.maxImageSize)&&s.maxImageSize>-1?s.maxImageSize:-1,S=s.isEvalSupported!==!1,A=typeof s.isOffscreenCanvasSupported=="boolean"?s.isOffscreenCanvasSupported:!f1,E=typeof s.isChrome=="boolean"?s.isChrome:!k_.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),I=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,P=typeof s.disableFontFace=="boolean"?s.disableFontFace:f1,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,Z=s.CanvasFactory||DYn,X=s.FilterFactory||OYn,ae=s.enableHWA===!0,le=c?c.length:s.length??NaN,re=typeof s.useSystemFonts=="boolean"?s.useSystemFonts:!f1&&!P,te=typeof s.useWorkerFetch=="boolean"?s.useWorkerFetch:x===$ss&&y===Hss&&f&&v&&wQ(f,document.baseURI)&&wQ(v,document.baseURI);s.canvasFactory&&W4t("`canvasFactory`-instance option, please use `CanvasFactory` instead."),s.filterFactory&&W4t("`filterFactory`-instance option, please use `FilterFactory` instead.");const J=null;wKn(h);const ce={canvasFactory:new Z({ownerDocument:O,enableHWA:ae}),filterFactory:new X({docId:n,ownerDocument:O}),cMapReaderFactory:te?null:new x({baseUrl:f,isCompressed:g}),standardFontDataFactory:te?null:new y({baseUrl:v})};if(!u){const ue={verbosity:h,port:hE.workerPort};u=ue.port?OV.fromPort(ue):new OV(ue),t._worker=u}const ve={docId:n,apiVersion:"4.8.69",data:a,password:o,disableAutoFetch:V,rangeChunkSize:d,length:le,docBaseUrl:m,enableXfa:D,evaluatorOptions:{maxImageSize:w,disableFontFace:P,ignoreErrors:b,isEvalSupported:S,isOffscreenCanvasSupported:A,isChrome:E,canvasMaxAreaInBytes:I,fontExtraProperties:R,useSystemFonts:re,cMapUrl:te?f:null,standardFontDataUrl:te?v:null}},fe={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",ve,a?[a.buffer]:null);let be;if(c)be=new mYn(c,{disableRange:U,disableStream:W});else if(!a){if(!r)throw new Error("getDocument - no `url` parameter provided.");let Ee;f1?Ee=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&wQ(r)?a3t:SYn:Ee=wQ(r)?a3t:_Yn,be=new Ee({url:r,length:le,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 ke=new EQ(n,Ee,u.port),Ie=new GYn(ke,t,be,fe,ce);t._transport=Ie,ke.send("Ready",null)})}).catch(t._capability.reject),t}function $Yn(s){if(s instanceof URL)return s.href;try{return new URL(s,window.location).href}catch{if(f1&&typeof s=="string")return s}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function UYn(s){if(f1&&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 LDe(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 i3t(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 hIe;const mIe=class mIe{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Z0(mIe,hIe)._++}`,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)}};hIe=new WeakMap,ys(mIe,hIe,0);let qZe=mIe;class ins{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){Np("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class qYn{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 eh(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 QP,WA,FN,SU,U3e;class VYn{constructor(t,n,r,a=!1){ys(this,FN);ys(this,QP,null);ys(this,WA,!1);this._pageIndex=t,this._pageInfo=n,this._transport=r,this._stats=a?new G4t:null,this._pdfBug=a,this.commonObjs=r.commonObjs,this.objs=new ons,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 Vie({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 eh(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=CP.ENABLE,transform:i=null,background:l=null,optionalContentConfigPromise:o=null,annotationCanvasMap:c=null,pageColors:d=null,printAnnotationStorage:u=null,isEditing:h=!1}){var S,A;(S=this._stats)==null||S.time("Overall");const m=this._transport.getRenderingIntent(r,a,u,h),{renderingIntent:f,cacheKey:g}=m;Yt(this,WA,!1),ds(this,FN,U3e).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 v=!!(f&Fj.PRINT);x.displayReadyCapability||(x.displayReadyCapability=Promise.withResolvers(),x.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(A=this._stats)==null||A.time("Page Request"),this._pumpOperatorList(m));const y=E=>{var I;x.renderTasks.delete(b),(this._maybeCleanupAfterRender||v)&&Yt(this,WA,!0),ds(this,FN,SU).call(this,!v),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 HZe({callback:y,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:!v,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){y();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(y),w}getOperatorList({intent:t="display",annotationMode:n=CP.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=>gne.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(),Yt(this,WA,!1),ds(this,FN,U3e).call(this),Promise.all(t)}cleanup(t=!1){Yt(this,WA,!0);const n=ds(this,FN,SU).call(this,!1);return t&&n&&this._stats&&(this._stats=new G4t),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();ds(this,FN,SU).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 jot){let a=LYn;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 d9(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}}QP=new WeakMap,WA=new WeakMap,FN=new WeakSet,SU=function(t=!1){if(ds(this,FN,U3e).call(this),!ye(this,WA)||this.destroyed)return!1;if(t)return Yt(this,QP,setTimeout(()=>{Yt(this,QP,null),ds(this,FN,SU).call(this,!1)},RYn)),!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(),Yt(this,WA,!1),!0},U3e=function(){ye(this,QP)&&(clearTimeout(ye(this,QP)),Yt(this,QP,null))};var KA,fIe;class HYn{constructor(){ys(this,KA,new Map);ys(this,fIe,Promise.resolve())}postMessage(t,n){const r={data:structuredClone(t,n?{transfer:n}:null)};ye(this,fIe).then(()=>{for(const[a]of ye(this,KA))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){tu("LoopbackPort - cannot use an `aborted` signal.");return}const l=()=>this.removeEventListener(t,n);a=()=>i.removeEventListener("abort",l),i.addEventListener("abort",l)}ye(this,KA).set(n,a)}removeEventListener(t,n){const r=ye(this,KA).get(n);r==null||r(),ye(this,KA).delete(n)}terminate(){for(const[,t]of ye(this,KA))t==null||t();ye(this,KA).clear()}}KA=new WeakMap,fIe=new WeakMap;var pIe,rz,az,AH,q3e,EH,V3e;const Op=class Op{constructor({name:t=null,port:n=null,verbosity:r=jKn()}={}){ys(this,AH);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(Op,az))!=null&&a.has(n))throw new Error("Cannot use more than one PDFWorker per port.");(ye(Op,az)||Yt(Op,az,new WeakMap)).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return f1?Promise.all([BL.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 EQ("main","worker",t),this._messageHandler.on("ready",function(){}),ds(this,AH,q3e).call(this)}_initialize(){if(ye(Op,rz)||ye(Op,EH,V3e)){this._setupFakeWorker();return}let{workerSrc:t}=Op;try{Op._isSameOrigin(window.location.href,t)||(t=Op._createCDNWrapper(new URL(t,window.location).href));const n=new Worker(t,{type:"module"}),r=new EQ("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,ds(this,AH,q3e).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{PDe("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){ye(Op,rz)||(tu("Setting up fake worker."),Yt(Op,rz,!0)),Op._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const n=new HYn;this._port=n;const r=`fake${Z0(Op,pIe)._++}`,a=new EQ(r+"_worker",r,n);t.setup(a,n),this._messageHandler=new EQ(r,r+"_worker",n),ds(this,AH,q3e).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(Op,az))==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,az))==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 Op(t)}static get workerSrc(){if(hE.workerSrc)return hE.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return eh(this,"_setupFakeWorkerGlobal",(async()=>ye(this,EH,V3e)?ye(this,EH,V3e):(await import(this.workerSrc)).WorkerMessageHandler)())}};pIe=new WeakMap,rz=new WeakMap,az=new WeakMap,AH=new WeakSet,q3e=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},EH=new WeakSet,V3e=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},ys(Op,EH),ys(Op,pIe,0),ys(Op,rz,!1),ys(Op,az),f1&&(Yt(Op,rz,!0),hE.workerSrc||(hE.workerSrc="./pdf.worker.mjs")),Op._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},Op._createCDNWrapper=t=>{const n=`await import("${t}");`;return URL.createObjectURL(new Blob([n],{type:"text/javascript"}))};let OV=Op;var YA,H5,TH,MH,G5,iz,TQ;class GYn{constructor(t,n,r,a,i){ys(this,iz);ys(this,YA,new Map);ys(this,H5,new Map);ys(this,TH,new Map);ys(this,MH,new Map);ys(this,G5,null);this.messageHandler=t,this.loadingTask=n,this.commonObjs=new ons,this.fontLoader=new qKn({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 eh(this,"annotationStorage",new Cot)}getRenderingIntent(t,n=CP.ENABLE,r=null,a=!1,i=!1){let l=Fj.DISPLAY,o=PZe;switch(t){case"any":l=Fj.ANY;break;case"display":break;case"print":l=Fj.PRINT;break;default:tu(`getRenderingIntent - invalid intent: ${t}`)}const c=l&Fj.PRINT&&r instanceof Oss?r:this.annotationStorage;switch(n){case CP.DISABLE:l+=Fj.ANNOTATIONS_DISABLE;break;case CP.ENABLE:break;case CP.ENABLE_FORMS:l+=Fj.ANNOTATIONS_FORMS;break;case CP.ENABLE_STORAGE:l+=Fj.ANNOTATIONS_STORAGE,o=c.serializable;break;default:tu(`getRenderingIntent - invalid annotationMode: ${n}`)}a&&(l+=Fj.IS_EDITING),i&&(l+=Fj.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,G5))==null||r.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const a of ye(this,H5).values())t.push(a._destroy());ye(this,H5).clear(),ye(this,TH).clear(),ye(this,MH).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,YA).clear(),this.filterFactory.destroy(),pne.cleanup(),(a=this._networkStream)==null||a.cancelAllRequests(new d9("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)=>{_0(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}_0(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)=>{_0(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}_0(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 qYn(r,this))}),t.on("DocException",function(r){let a;switch(r.name){case"PasswordException":a=new dZe(r.message,r.code);break;case"InvalidPDFException":a=new dss(r.message);break;case"MissingPDFException":a=new c9(r.message);break;case"UnexpectedResponseException":a=new IDe(r.message,r.status);break;case"UnknownErrorException":a=new uZe(r.message,r.details);break;default:Np("DocException - expected a valid Error.")}n._capability.reject(a)}),t.on("PasswordRequest",r=>{if(Yt(this,G5,Promise.withResolvers()),n.onPassword){const a=i=>{i instanceof Error?ye(this,G5).reject(i):ye(this,G5).resolve({password:i})};try{n.onPassword(a,r.code)}catch(i){ye(this,G5).reject(i)}}else ye(this,G5).reject(new dZe(r.message,r.code));return ye(this,G5).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,H5).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;tu(`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 VKn(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;_0(m,"The imageRef must be defined.");for(const f of ye(this,H5).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,H5).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)>yKn&&(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&&tu("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,TH).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,MH).set(i.refStr,t);const l=new VYn(n,i,this,this._params.pdfBug);return ye(this,H5).set(n,l),l});return ye(this,TH).set(n,a),a}getPageIndex(t){return i3t(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 ds(this,iz,TQ).call(this,"GetFieldObjects")}hasJSActions(){return ds(this,iz,TQ).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 ds(this,iz,TQ).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 ds(this,iz,TQ).call(this,"GetOptionalContentConfig").then(n=>new hYn(n,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",n=ye(this,YA).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 dYn(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,YA).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,H5).values())if(!n.cleanup())throw new Error(`startCleanup: Page ${n.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),ye(this,YA).clear(),this.filterFactory.destroy(!0),pne.cleanup()}}cachedPageNumber(t){if(!i3t(t))return null;const n=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return ye(this,MH).get(n)??null}}YA=new WeakMap,H5=new WeakMap,TH=new WeakMap,MH=new WeakMap,G5=new WeakMap,iz=new WeakSet,TQ=function(t,n=null){const r=ye(this,YA).get(t);if(r)return r;const a=this.messageHandler.sendWithPromise(t,n);return ye(this,YA).set(t,a),a};const Eue=Symbol("INITIAL_DATA");var wS,Tre,VZe;class ons{constructor(){ys(this,Tre);ys(this,wS,Object.create(null))}get(t,n=null){if(n){const a=ds(this,Tre,VZe).call(this,t);return a.promise.then(()=>n(a.data)),null}const r=ye(this,wS)[t];if(!r||r.data===Eue)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return r.data}has(t){const n=ye(this,wS)[t];return!!n&&n.data!==Eue}resolve(t,n=null){const r=ds(this,Tre,VZe).call(this,t);r.data=n,r.resolve()}clear(){var t;for(const n in ye(this,wS)){const{data:r}=ye(this,wS)[n];(t=r==null?void 0:r.bitmap)==null||t.close()}Yt(this,wS,Object.create(null))}*[Symbol.iterator](){for(const t in ye(this,wS)){const{data:n}=ye(this,wS)[t];n!==Eue&&(yield[t,n])}}}wS=new WeakMap,Tre=new WeakSet,VZe=function(t){var n;return(n=ye(this,wS))[t]||(n[t]={...Promise.withResolvers(),data:Eue})};var JP;class WYn{constructor(t){ys(this,JP,null);Yt(this,JP,t),this.onContinue=null}get promise(){return ye(this,JP).capability.promise}cancel(t=0){ye(this,JP).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=ye(this,JP).operatorList;if(!t)return!1;const{annotationCanvasMap:n}=ye(this,JP);return t.form||t.canvas&&(n==null?void 0:n.size)>0}}JP=new WeakMap;var eI,oz;const XO=class XO{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}){ys(this,eI,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 WYn(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(XO,oz).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(XO,oz).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 FV(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,eI)&&(window.cancelAnimationFrame(ye(this,eI)),Yt(this,eI,null)),ye(XO,oz).delete(this._canvas),this.callback(t||new jot(`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?Yt(this,eI,window.requestAnimationFrame(()=>{Yt(this,eI,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(XO,oz).delete(this._canvas),this.callback())))}};eI=new WeakMap,oz=new WeakMap,ys(XO,oz,new WeakSet);let HZe=XO;const KYn="4.8.69",YYn="3634dab10";function o3t(s){return Math.floor(Math.max(0,Math.min(1,s))*255).toString(16).padStart(2,"0")}function cX(s){return Math.max(0,Math.min(255,255*s))}class l3t{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=cX(t),[t,t,t]}static G_HTML([t]){const n=o3t(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(cX)}static RGB_HTML(t){return`#${t.map(o3t).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[cX(1-Math.min(1,t+a)),cX(1-Math.min(1,r+a)),cX(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 ZYn{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){Np("Abstract method `_createSVG` called.")}}class Pot extends ZYn{_createSVG(t){return document.createElementNS(bA,t)}}class lns{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&&gne.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 v=f.children[++u.at(-1)[1]];if(v===null)continue;const{name:y}=v;if(y==="#text"){const w=document.createTextNode(v.value);d.push(w),x.append(w);continue}const b=(h=v==null?void 0:v.attributes)!=null&&h.xmlns?document.createElementNS(v.attributes.xmlns,y):document.createElement(y);if(x.append(b),v.attributes&&this.setAttributes({html:b,element:v,storage:n,intent:i,linkService:r}),((m=v.children)==null?void 0:m.length)>0)u.push([v,-1,b]);else if(v.value){const w=document.createTextNode(v.value);o&&gne.shouldBuildText(y)&&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 Gie=1e3,XYn=9,fB=new WeakSet;function HE(s){return{width:s[2]-s[0],height:s[3]-s[1]}}class QYn{static create(t){switch(t.data.annotationType){case r0.LINK:return new cns(t);case r0.TEXT:return new JYn(t);case r0.WIDGET:switch(t.data.fieldType){case"Tx":return new eZn(t);case"Btn":return t.data.radioButton?new hns(t):t.data.checkBox?new sZn(t):new nZn(t);case"Ch":return new rZn(t);case"Sig":return new tZn(t)}return new u9(t);case r0.POPUP:return new WZe(t);case r0.FREETEXT:return new xns(t);case r0.LINE:return new iZn(t);case r0.SQUARE:return new oZn(t);case r0.CIRCLE:return new lZn(t);case r0.POLYLINE:return new yns(t);case r0.CARET:return new dZn(t);case r0.INK:return new Iot(t);case r0.POLYGON:return new cZn(t);case r0.HIGHLIGHT:return new vns(t);case r0.UNDERLINE:return new uZn(t);case r0.SQUIGGLY:return new hZn(t);case r0.STRIKEOUT:return new mZn(t);case r0.STAMP:return new bns(t);case r0.FILEATTACHMENT:return new fZn(t);default:return new hy(t)}}}var lz,PH,IH,Mre,GZe;const Kct=class Kct{constructor(t,{isRenderable:n=!1,ignoreBorder:r=!1,createQuadrilaterals:a=!1}={}){ys(this,Mre);ys(this,lz,null);ys(this,PH,!1);ys(this,IH,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 Kct._hasPopupData(this.data)}updateEdited(t){var r;if(!this.container)return;ye(this,lz)||Yt(this,lz,{rect:this.data.rect.slice(0)});const{rect:n}=t;n&&ds(this,Mre,GZe).call(this,n),(r=ye(this,IH))==null||r.popup.updateEdited(t)}resetEdited(){var t;ye(this,lz)&&(ds(this,Mre,GZe).call(this,ye(this,lz).rect),(t=ye(this,IH))==null||t.popup.resetEdited(),Yt(this,lz,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 u9||(i.tabIndex=Gie);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 WZe){const{rotation:x}=n;return!n.hasOwnCanvas&&x!==0&&this.setRotation(x,i),i}const{width:o,height:c}=HE(n.rect);if(!t&&n.borderStyle.width>0){l.borderWidth=`${n.borderStyle.width}px`;const x=n.borderStyle.horizontalCornerRadius,v=n.borderStyle.verticalCornerRadius;if(x>0||v>0){const b=`calc(${x}px * var(--scale-factor)) / calc(${v}px * var(--scale-factor))`;l.borderRadius=b}else if(this instanceof hns){const b=`calc(${o}px * var(--scale-factor)) / calc(${c}px * var(--scale-factor))`;l.borderRadius=b}switch(n.borderStyle.style){case oX.SOLID:l.borderStyle="solid";break;case oX.DASHED:l.borderStyle="dashed";break;case oX.BEVELED:tu("Unimplemented border style: beveled");break;case oX.INSET:tu("Unimplemented border style: inset");break;case oX.UNDERLINE:l.borderBottomStyle="solid";break}const y=n.borderColor||null;y?(Yt(this,PH,!0),l.borderColor=ol.makeHexColor(y[0]|0,y[1]|0,y[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}=HE(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]=l3t[`${l}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[r]:l3t[`${l}_rgb`](o)})};return eh(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,v,y,b]=t.subarray(2,6);if(a===x&&i===v&&n===y&&r===b)return}const{style:l}=this.container;let o;if(ye(this,PH)){const{borderColor:x,borderWidth:v}=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,v=t.length;x`)}ye(this,PH)&&(o.push("')"),l.backgroundImage=o.join("")),this.container.append(h),this.container.style.clipPath=`url(#${g})`}_createPopup(){const{data:t}=this,n=Yt(this,IH,new WZe({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(){Np("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&&!fB.has(d)){tu(`_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&&fB.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})})}};lz=new WeakMap,PH=new WeakMap,IH=new WeakMap,Mre=new WeakSet,GZe=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}=HE(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 hy=Kct;var Vj,FO,dns,uns;class cns extends hy{constructor(n,r=null){super(n,{isRenderable:!0,ignoreBorder:!!(r!=null&&r.ignoreBorder),createQuadrilaterals:!0});ys(this,Vj);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?(ds(this,Vj,dns).call(this,a,n.attachment,n.attachmentDest),i=!0):n.setOCGState?(ds(this,Vj,uns).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==="")&&ds(this,Vj,FO).call(this)}_bindNamedAction(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeNamedAction(r),!1),ds(this,Vj,FO).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),ds(this,Vj,FO).call(this)}_bindResetFormAction(n,r){const a=n.onclick;if(a||(n.href=this.linkService.getAnchorUrl("")),ds(this,Vj,FO).call(this),!this._fieldObjects){tu('_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(!fB.has(g)){tu(`_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}}}Vj=new WeakSet,FO=function(){this.container.setAttribute("data-internal-link","")},dns=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},ds(this,Vj,FO).call(this)},uns=function(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeSetOCGState(r),!1),ds(this,Vj,FO).call(this)};class JYn extends hy{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 u9 extends hy{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 k_.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||XYn,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/(k$e*a))||1,h=d/u;l=Math.min(a,c(h/k$e))}else{const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o);l=Math.min(a,c(d/k$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 eZn extends u9{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),fB.add(r),r.setAttribute("data-element-id",n),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=Gie,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:v}=x.detail;u.formattedValue=v,v!=null&&x.target!==document.activeElement&&(x.target.value=v),t.setValue(n,{formattedValue:v})},selRange(x){x.target.setSelectionRange(...x.detail.selRange)},charLimit:x=>{var w;const{charLimit:v}=x.detail,{target:y}=x;if(v===0){y.removeAttribute("maxLength");return}y.setAttribute("maxLength",v);let b=u.userValue;!b||b.length<=v||(b=b.slice(0,v),y.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:y.selectionStart,selEnd:y.selectionEnd}}))}};this._dispatchEventFromSandbox(g,f)}),r.addEventListener("keydown",f=>{var v;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,(v=this.linkService.eventBus)==null||v.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,v;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&&((v=this.linkService.eventBus)==null||v.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 A;u.lastCommittedValue=null;const{data:g,target:x}=f,{value:v,selectionStart:y,selectionEnd:b}=x;let w=y,S=b;switch(f.inputType){case"deleteWordBackward":{const E=v.substring(0,y).match(/\w*[^\w]*$/);E&&(w-=E[0].length);break}case"deleteWordForward":{const E=v.substring(y).match(/^[^\w]*\w*/);E&&(S+=E[0].length);break}case"deleteContentBackward":y===b&&(w-=1);break;case"deleteContentForward":y===b&&(S+=1);break}f.preventDefault(),(A=this.linkService.eventBus)==null||A.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:v,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 tZn extends u9{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class sZn extends u9{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 fB.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=Gie,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 hns extends u9{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(fB.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=Gie,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 nZn extends cns{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 rZn extends u9{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");fB.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=Gie;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,v=>v.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,v=a.children[f],y=document.createElement("option");y.textContent=g,y.value=x,v?v.before(y):a.append(y),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:v}=g,y=document.createElement("option");y.textContent=x,y.value=v,a.append(y)}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 WZe extends hy{constructor(t){const{data:n,elements:r}=t;super(t,{isRenderable:hy._hasPopupData(n)}),this.elements=r,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new aZn({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=>`${wot}${r}`).join(",")),this.container}}var LH,gIe,xIe,RH,cz,lx,ZA,DH,Pre,Ire,FH,XA,jS,QA,Lre,JA,Rre,dz,uz,of,H3e,KZe,mns,fns,pns,gns,G3e,W3e,YZe;class aZn{constructor({container:t,color:n,elements:r,titleObj:a,modificationDate:i,contentsObj:l,richText:o,parent:c,rect:d,parentRect:u,open:h}){ys(this,of);ys(this,LH,ds(this,of,pns).bind(this));ys(this,gIe,ds(this,of,YZe).bind(this));ys(this,xIe,ds(this,of,W3e).bind(this));ys(this,RH,ds(this,of,G3e).bind(this));ys(this,cz,null);ys(this,lx,null);ys(this,ZA,null);ys(this,DH,null);ys(this,Pre,null);ys(this,Ire,null);ys(this,FH,null);ys(this,XA,!1);ys(this,jS,null);ys(this,QA,null);ys(this,Lre,null);ys(this,JA,null);ys(this,Rre,null);ys(this,dz,null);ys(this,uz,!1);var m;Yt(this,lx,t),Yt(this,Rre,a),Yt(this,ZA,l),Yt(this,JA,o),Yt(this,Ire,c),Yt(this,cz,n),Yt(this,Lre,d),Yt(this,FH,u),Yt(this,Pre,r),Yt(this,DH,kot.toDateObject(i)),this.trigger=r.flatMap(f=>f.getElementsToTriggerPopup());for(const f of this.trigger)f.addEventListener("click",ye(this,RH)),f.addEventListener("mouseenter",ye(this,xIe)),f.addEventListener("mouseleave",ye(this,gIe)),f.classList.add("popupTriggerArea");for(const f of r)(m=f.container)==null||m.addEventListener("keydown",ye(this,LH));ye(this,lx).hidden=!0,h&&ds(this,of,G3e).call(this)}render(){if(ye(this,jS))return;const t=Yt(this,jS,document.createElement("div"));if(t.className="popup",ye(this,cz)){const i=t.style.outlineColor=ol.makeHexColor(...ye(this,cz));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,cz).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,Rre),t.append(n),ye(this,DH)){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,DH).valueOf()})),n.append(i)}const a=ye(this,of,H3e);if(a)lns.render({xfaHtml:a,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const i=this._formatContents(ye(this,ZA));t.append(i)}ye(this,lx).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)&&ds(this,Ure,ZZe).call(this)}),!r.popupRef&&this.hasPopupData?this._createPopup():a.classList.add("popupTriggerArea"),n.append(a),n}getElementsToTriggerPopup(){return ye(this,$re)}addHighlightArea(){this.container.classList.add("highlightArea")}}$re=new WeakMap,Ure=new WeakSet,ZZe=function(){var n;(n=this.downloadManager)==null||n.openOrDownloadData(this.content,this.filename)};var qre,hz,mz,Vre,_B,_ns,XZe;class pZn{constructor({div:t,accessibilityManager:n,annotationCanvasMap:r,annotationEditorUIManager:a,page:i,viewport:l,structTreeLayer:o}){ys(this,_B);ys(this,qre,null);ys(this,hz,null);ys(this,mz,new Map);ys(this,Vre,null);this.div=t,Yt(this,qre,n),Yt(this,hz,r),Yt(this,Vre,o||null),this.page=i,this.viewport=l,this.zIndex=0,this._annotationEditorUIManager=a}hasEditableAnnotations(){return ye(this,mz).size>0}async render(t){var l;const{annotations:n}=t,r=this.div;hB(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 Pot,annotationStorage:t.annotationStorage||new Cot,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===r0.POPUP;if(c){const h=a.get(o.id);if(!h)continue;i.elements=h}else{const{width:h,height:m}=HE(o.rect);if(h<=0||m<=0)continue}i.data=o;const d=QYn.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 ds(this,_B,_ns).call(this,u,o.id),d._isEditable&&(ye(this,mz).set(d.data.id,d),(l=this._annotationEditorUIManager)==null||l.renderAnnotationElement(d))}ds(this,_B,XZe).call(this)}update({viewport:t}){const n=this.div;this.viewport=t,hB(n,{rotation:t.rotation}),ds(this,_B,XZe).call(this),n.hidden=!1}getEditableAnnotations(){return Array.from(ye(this,mz).values())}getEditableAnnotation(t){return ye(this,mz).get(t)}}qre=new WeakMap,hz=new WeakMap,mz=new WeakMap,Vre=new WeakMap,_B=new WeakSet,_ns=async function(t,n){var l,o;const r=t.firstChild||t,a=r.id=`${wot}${n}`,i=await((l=ye(this,Vre))==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,qre))==null||o.moveElementInDOM(this.div,t,r,!1)},XZe=function(){if(!ye(this,hz))return;const t=this.div;for(const[n,r]of ye(this,hz)){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,hz).clear()};const Tue=/\r\n?|\n/g;var NS,Tj,Hre,fz,Mj,qy,wns,jns,Nns,K3e,tT,Y3e,Z3e,kns,JZe,Sns;const $f=class $f extends Cm{constructor(n){super({...n,name:"freeTextEditor"});ys(this,qy);ys(this,NS);ys(this,Tj,"");ys(this,Hre,`${this.id}-editor`);ys(this,fz,null);ys(this,Mj);Yt(this,NS,n.color||$f._defaultColor||Cm._defaultLineColor),Yt(this,Mj,n.fontSize||$f._defaultFontSize)}static get _keyboardManager(){const n=$f.prototype,r=l=>l.isEmpty(),a=mB.TRANSLATE_SMALL,i=mB.TRANSLATE_BIG;return eh(this,"_keyboardManager",new Hie([[["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){Cm.initialize(n,r);const a=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(a.getPropertyValue("--freetext-padding"))}static updateDefaultParams(n,r){switch(n){case td.FREETEXT_SIZE:$f._defaultFontSize=r;break;case td.FREETEXT_COLOR:$f._defaultColor=r;break}}updateParams(n,r){switch(n){case td.FREETEXT_SIZE:ds(this,qy,wns).call(this,r);break;case td.FREETEXT_COLOR:ds(this,qy,jns).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[td.FREETEXT_SIZE,$f._defaultFontSize],[td.FREETEXT_COLOR,$f._defaultColor||Cm._defaultLineColor]]}get propertiesToUpdate(){return[[td.FREETEXT_SIZE,ye(this,Mj)],[td.FREETEXT_COLOR,ye(this,NS)]]}_translateEmpty(n,r){this._uiManager.translateSelectedEditors(n,r,!0)}getInitialTranslation(){const n=this.parentScale;return[-$f._internalPadding*n,-($f._internalPadding+ye(this,Mj))*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(Rd.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),Yt(this,fz,new AbortController);const n=this._uiManager.combinedSignal(ye(this,fz));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,Hre)),this._isDraggable=!0,(n=ye(this,fz))==null||n.abort(),Yt(this,fz,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,Tj),r=Yt(this,Tj,ds(this,qy,Nns).call(this).trimEnd());if(n===r)return;const a=i=>{if(Yt(this,Tj,i),!i){this.remove();return}ds(this,qy,Z3e).call(this),this._uiManager.rebuild(this),ds(this,qy,K3e).call(this)};this.addCommands({cmd:()=>{a(r)},undo:()=>{a(n)},mustExec:!1}),ds(this,qy,K3e).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){$f._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,Hre)),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,Mj)}px * var(--scale-factor))`,a.color=ye(this,NS),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),uPe(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);ds(this,qy,Z3e).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,v;const r=n.clipboardData||window.clipboardData,{types:a}=r;if(a.length===1&&a[0]==="text/plain")return;n.preventDefault();const i=ds(g=$f,tT,JZe).call(g,r.getData("text")||"").replaceAll(Tue,` `);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 y=c.parentElement;if(h.push(c.nodeValue.slice(d).replaceAll(Tue,"")),y!==this.editorDiv){let b=u;for(const w of this.editorDiv.childNodes){if(w===y){b=h;continue}b.push(ds(x=$f,tT,Y3e).call(x,w))}}u.push(c.nodeValue.slice(0,d).replaceAll(Tue,""))}else if(c===this.editorDiv){let y=u,b=0;for(const w of this.editorDiv.childNodes)b++===d&&(y=h),y.push(ds(v=$f,tT,Y3e).call(v,w))}Yt(this,Tj,`${u.join(` `)}${i}${h.join(` `)}`),ds(this,qy,Z3e).call(this);const m=new Range;let f=u.reduce((y,b)=>y+b.length,0);for(const{firstChild:y}of this.editorDiv.childNodes)if(y.nodeType===Node.TEXT_NODE){const b=y.nodeValue.length;if(f<=b){m.setStart(y,f),m.setEnd(y,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 xns){const{data:{defaultAppearanceData:{fontSize:c,fontColor:d},rect:u,rotation:h,id:m,popupRef:f},textContent:g,textPosition:x,parent:{page:{pageNumber:v}}}=n;if(!g||g.length===0)return null;i=n={annotationType:Rd.FREETEXT,color:Array.from(d),fontSize:c,value:g.join(` `),position:x,pageIndex:v-1,rect:u.slice(0),rotation:h,id:m,deleted:!1,popupRef:f}}const l=await super.deserialize(n,r,a);return Yt(l,Mj,n.fontSize),Yt(l,NS,ol.makeHexColor(...n.color)),Yt(l,Tj,ds(o=$f,tT,JZe).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=$f._internalPadding*this.parentScale,a=this.getRect(r,r),i=Cm._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:ye(this,NS)),l={annotationType:Rd.FREETEXT,color:i,fontSize:ye(this,Mj),value:ds(this,qy,kns).call(this),pageIndex:this.pageIndex,rect:a,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return n?l:this.annotationElementId&&!ds(this,qy,Sns).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,Mj)}px * var(--scale-factor))`,a.color=ye(this,NS),r.replaceChildren();for(const l of ye(this,Tj).split(` `)){const o=document.createElement("div");o.append(l?document.createTextNode(l):document.createElement("br")),r.append(o)}const i=$f._internalPadding*this.parentScale;return n.updateEdited({rect:this.getRect(i,i),popupContent:ye(this,Tj)}),r}resetAnnotationElement(n){super.resetAnnotationElement(n),n.resetEdited()}};NS=new WeakMap,Tj=new WeakMap,Hre=new WeakMap,fz=new WeakMap,Mj=new WeakMap,qy=new WeakSet,wns=function(n){const r=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-ye(this,Mj))*this.parentScale),Yt(this,Mj,i),ds(this,qy,K3e).call(this)},a=ye(this,Mj);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:td.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},jns=function(n){const r=i=>{Yt(this,NS,this.editorDiv.style.color=i)},a=ye(this,NS);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:td.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},Nns=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(ds(a=$f,tT,Y3e).call(a,i)),r=i);return n.join(` `)},K3e=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()},tT=new WeakSet,Y3e=function(n){return(n.nodeType===Node.TEXT_NODE?n.nodeValue:n.innerText).replaceAll(Tue,"")},Z3e=function(){if(this.editorDiv.replaceChildren(),!!ye(this,Tj))for(const n of ye(this,Tj).split(` `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),this.editorDiv.append(r)}},kns=function(){return ye(this,Tj).replaceAll(" "," ")},JZe=function(n){return n.replaceAll(" "," ")},Sns=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},ys($f,tT),_r($f,"_freeTextDefaultContent",""),_r($f,"_internalPadding",0),_r($f,"_defaultColor",null),_r($f,"_defaultFontSize",10),_r($f,"_type","freetext"),_r($f,"_editorType",Rd.FREETEXT);let QZe=$f;class Cns{toSVGPath(){Np("Abstract method `toSVGPath` must be implemented.")}get box(){Np("Abstract getter `box` must be implemented.")}serialize(t,n){Np("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){Np("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){Np("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}var Pj,kS,OH,zH,W5,uu,pz,gz,Gre,Wre,BH,$H,tI,Kre,yIe,vIe,S0,MQ,Ans,Ens,Tns,Mns,Pns,Ins;const TA=class TA{constructor({x:t,y:n},r,a,i,l,o=0){ys(this,S0);ys(this,Pj);ys(this,kS,[]);ys(this,OH);ys(this,zH);ys(this,W5,[]);ys(this,uu,new Float64Array(18));ys(this,pz);ys(this,gz);ys(this,Gre);ys(this,Wre);ys(this,BH);ys(this,$H);ys(this,tI,[]);Yt(this,Pj,r),Yt(this,$H,i*a),Yt(this,zH,l),ye(this,uu).set([NaN,NaN,NaN,NaN,t,n],6),Yt(this,OH,o),Yt(this,Wre,ye(TA,Kre)*a),Yt(this,Gre,ye(TA,vIe)*a),Yt(this,BH,a),ye(this,tI).push(t,n)}isEmpty(){return isNaN(ye(this,uu)[8])}add({x:t,y:n}){var R;Yt(this,pz,t),Yt(this,gz,n);const[r,a,i,l]=ye(this,Pj);let[o,c,d,u]=ye(this,uu).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 ds(this,S0,Ens).call(this,r),r.join(" ")}newFreeDrawOutline(t,n,r,a,i,l){return new Lns(t,n,r,a,i,l)}getOutlines(){var h;const t=ye(this,W5),n=ye(this,kS),r=ye(this,uu),[a,i,l,o]=ye(this,Pj),c=new Float64Array((((h=ye(this,tI))==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 ds(this,S0,Pns).call(this,d,u),this.newFreeDrawOutline(d,c,ye(this,Pj),ye(this,BH),ye(this,OH),ye(this,zH))}};Pj=new WeakMap,kS=new WeakMap,OH=new WeakMap,zH=new WeakMap,W5=new WeakMap,uu=new WeakMap,pz=new WeakMap,gz=new WeakMap,Gre=new WeakMap,Wre=new WeakMap,BH=new WeakMap,$H=new WeakMap,tI=new WeakMap,Kre=new WeakMap,yIe=new WeakMap,vIe=new WeakMap,S0=new WeakSet,MQ=function(){const t=ye(this,uu).subarray(4,6),n=ye(this,uu).subarray(16,18),[r,a,i,l]=ye(this,Pj);return[(ye(this,pz)+(t[0]-n[0])/2-r)/i,(ye(this,gz)+(t[1]-n[1])/2-a)/l,(ye(this,pz)+(n[0]-t[0])/2-r)/i,(ye(this,gz)+(n[1]-t[1])/2-a)/l]},Ans=function(){const[t,n,r,a]=ye(this,Pj),[i,l,o,c]=ds(this,S0,MQ).call(this);return`M${(ye(this,uu)[2]-t)/r} ${(ye(this,uu)[3]-n)/a} L${(ye(this,uu)[4]-t)/r} ${(ye(this,uu)[5]-n)/a} L${i} ${l} L${o} ${c} L${(ye(this,uu)[16]-t)/r} ${(ye(this,uu)[17]-n)/a} L${(ye(this,uu)[14]-t)/r} ${(ye(this,uu)[15]-n)/a} Z`},Ens=function(t){const n=ye(this,kS);t.push(`L${n[4]} ${n[5]} Z`)},Tns=function(t){const[n,r,a,i]=ye(this,Pj),l=ye(this,uu).subarray(4,6),o=ye(this,uu).subarray(16,18),[c,d,u,h]=ds(this,S0,MQ).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}`)},Mns=function(t){const n=ye(this,uu),[r,a,i,l]=ye(this,Pj),[o,c,d,u]=ds(this,S0,MQ).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,Pj),ye(this,BH),ye(this,OH),ye(this,zH))},Pns=function(t,n){const r=ye(this,kS);return t.set([NaN,NaN,NaN,NaN,r[4],r[5]],n),n+=6},Ins=function(t,n){const r=ye(this,uu).subarray(4,6),a=ye(this,uu).subarray(16,18),[i,l,o,c]=ye(this,Pj),[d,u,h,m]=ds(this,S0,MQ).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},ys(TA,Kre,8),ys(TA,yIe,2),ys(TA,vIe,ye(TA,Kre)+ye(TA,yIe));let mPe=TA;var UH,xz,eE,Yre,Ij,Zre,Wx,_w,PQ,IQ,Rns;class Lns extends Cns{constructor(n,r,a,i,l,o){super();ys(this,_w);ys(this,UH);ys(this,xz,null);ys(this,eE);ys(this,Yre);ys(this,Ij);ys(this,Zre);ys(this,Wx);Yt(this,Wx,n),Yt(this,Ij,r),Yt(this,UH,a),Yt(this,Zre,i),Yt(this,eE,l),Yt(this,Yre,o),ds(this,_w,Rns).call(this,o);const{x:c,y:d,width:u,height:h}=ye(this,xz);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,sI))n[3]?(t.push(...ds(this,E_,eXe).call(this,n)),ds(this,E_,Fns).call(this,n)):(ds(this,E_,Ons).call(this,n),t.push(...ds(this,E_,eXe).call(this,n)));return ds(this,E_,Dns).call(this,t)}}Xre=new WeakMap,sI=new WeakMap,SS=new WeakMap,E_=new WeakSet,Dns=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 gZn(a,ye(this,Xre))},X3e=function(t){const n=ye(this,SS);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,SS)[a];if(i!==t)break;if(i===t&&l===n){ye(this,SS).splice(a,1);return}}},eXe=function(t){const[n,r,a]=t,i=[[n,r,a]],l=ds(this,E_,X3e).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 Qre,qH;class gZn extends Cns{constructor(n,r){super();ys(this,Qre);ys(this,qH);Yt(this,qH,n),Yt(this,Qre,r)}toSVGPath(){const n=[];for(const r of ye(this,qH)){let[a,i]=r;n.push(`M${a} ${i}`);for(let l=2;l-1?(Yt(this,iw,!0),ds(this,jd,Q3e).call(this,n),ds(this,jd,zO).call(this)):ye(this,tE)&&(Yt(this,WH,n.anchorNode),Yt(this,nae,n.anchorOffset),Yt(this,rae,n.focusNode),Yt(this,aae,n.focusOffset),ds(this,jd,aXe).call(this),ds(this,jd,zO).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const n=Xh.prototype;return eh(this,"_keyboardManager",new Hie([[["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,iw)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:ye(this,vN),methodOfCreation:ye(this,iae)}}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;Cm.initialize(n,r),Xh._defaultColor||(Xh._defaultColor=((a=r.highlightColors)==null?void 0:a.values().next().value)||"#fff066")}static updateDefaultParams(n,r){switch(n){case td.HIGHLIGHT_DEFAULT_COLOR:Xh._defaultColor=r;break;case td.HIGHLIGHT_THICKNESS:Xh._defaultThickness=r;break}}translateInPage(n,r){}get toolbarPosition(){return ye(this,YH)}updateParams(n,r){switch(n){case td.HIGHLIGHT_COLOR:ds(this,jd,Bns).call(this,r);break;case td.HIGHLIGHT_THICKNESS:ds(this,jd,$ns).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[td.HIGHLIGHT_DEFAULT_COLOR,Xh._defaultColor],[td.HIGHLIGHT_THICKNESS,Xh._defaultThickness]]}get propertiesToUpdate(){return[[td.HIGHLIGHT_COLOR,this.color||Xh._defaultColor],[td.HIGHLIGHT_THICKNESS,ye(this,vN)||Xh._defaultThickness],[td.HIGHLIGHT_FREE,ye(this,iw)]]}async addEditToolbar(){const n=await super.addEditToolbar();return n?(this._uiManager.highlightColors&&(Yt(this,KH,new fPe({editor:this})),n.addColorPicker(ye(this,KH))),n):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(ds(this,jd,LQ).call(this))}getBaseTranslation(){return[0,0]}getRect(n,r){return super.getRect(n,r,ds(this,jd,LQ).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){ds(this,jd,iXe).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(ds(this,jd,zO).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(n){var a;let r=!1;this.parent&&!n?ds(this,jd,iXe).call(this):n&&(ds(this,jd,zO).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,iw)?(n=(n-this.rotation+360)%360,a=ds(i=Xh,ON,CU).call(i,ye(this,ES).box,n)):a=ds(l=Xh,ON,CU).call(l,this,n),r.rotate(ye(this,r1),n),r.rotate(ye(this,c0),n),r.updateBox(ye(this,r1),a),r.updateBox(ye(this,c0),ds(o=Xh,ON,CU).call(o,ye(this,yN).box,n))}render(){if(this.div)return this.div;const n=super.render();ye(this,ZH)&&(n.setAttribute("aria-label",ye(this,ZH)),n.setAttribute("role","mark")),ye(this,iw)?n.classList.add("free"):this.div.addEventListener("keydown",ds(this,jd,qns).bind(this),{signal:this._uiManager._signal});const r=Yt(this,bz,document.createElement("div"));n.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=ye(this,vz);const[a,i]=this.parentDimensions;return this.setDims(this.width*a,this.height*i),uPe(this,ye(this,bz),["pointerover","pointerleave"]),this.enableEditing(),n}pointerover(){this.isSelected||this.parent.drawLayer.addClass(ye(this,c0),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(ye(this,c0),"hovered")}_moveCaret(n){switch(this.parent.unselect(this),n){case 0:case 2:ds(this,jd,J3e).call(this,!0);break;case 1:case 3:ds(this,jd,J3e).call(this,!1);break}}select(){var n,r;super.select(),ye(this,c0)&&((n=this.parent)==null||n.drawLayer.removeClass(ye(this,c0),"hovered"),(r=this.parent)==null||r.drawLayer.addClass(ye(this,c0),"selected"))}unselect(){var n;super.unselect(),ye(this,c0)&&((n=this.parent)==null||n.drawLayer.removeClass(ye(this,c0),"selected"),ye(this,iw)||ds(this,jd,J3e).call(this,!1))}get _mustFixPosition(){return!ye(this,iw)}show(n=this._isVisible){super.show(n),this.parent&&(this.parent.drawLayer.show(ye(this,r1),n),this.parent.drawLayer.show(ye(this,c0),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(),ds(this,ON,Wns).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",fk,{signal:m}),a.addEventListener("pointermove",ds(this,ON,Gns).bind(this,n),{signal:m}),this._freeHighlight=new tXe({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,v,y,b;let i=null;if(n instanceof vns){const{data:{quadPoints:w,rect:S,rotation:A,id:E,color:I,opacity:P,popupRef:R},parent:{page:{pageNumber:D}}}=n;i=n={annotationType:Rd.HIGHLIGHT,color:Array.from(I),opacity:P,quadPoints:w,boxes:null,pageIndex:D-1,rect:S.slice(0),rotation:A,id:E,deleted:!1,popupRef:R}}else if(n instanceof Iot){const{data:{inkLists:w,rect:S,rotation:A,id:E,color:I,borderStyle:{rawWidth:P},popupRef:R},parent:{page:{pageNumber:D}}}=n;i=n={annotationType:Rd.HIGHLIGHT,color:Array.from(I),thickness:P,inkLists:w,boxes:null,pageIndex:D-1,rect:S.slice(0),rotation:A,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),Yt(u,sE,d||1),c&&Yt(u,vN,n.thickness),u.annotationElementId=n.id||null,u._initialData=i;const[h,m]=u.pageDimensions,[f,g]=u.pageTranslation;if(o){const w=Yt(u,tE,[]);for(let S=0;S=0)Yt(this,r1,r),Yt(this,vz,a),this.parent.drawLayer.finalizeLine(r,n),Yt(this,c0,this.parent.drawLayer.drawOutline(ye(this,yN)));else if(this.parent){const f=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(ye(this,r1),n),this.parent.drawLayer.updateBox(ye(this,r1),ds(h=Xh,ON,CU).call(h,ye(this,ES).box,(f-this.rotation+360)%360)),this.parent.drawLayer.updateLine(ye(this,c0),ye(this,yN)),this.parent.drawLayer.updateBox(ye(this,c0),ds(m=Xh,ON,CU).call(m,ye(this,yN).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,yN).box;Yt(this,YH,[(u[0]-l)/c,(u[1]-o)/d])},Bns=function(n){const r=(l,o)=>{var c,d,u;this.color=l,(c=this.parent)==null||c.drawLayer.changeColor(ye(this,r1),l),(d=ye(this,KH))==null||d.updateColor(l),Yt(this,sE,o),(u=this.parent)==null||u.drawLayer.changeOpacity(ye(this,r1),o)},a=this.color,i=ye(this,sE);this.addCommands({cmd:r.bind(this,n,Xh._defaultOpacity),undo:r.bind(this,a,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:td.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(n)},!0)},$ns=function(n){const r=ye(this,vN),a=i=>{Yt(this,vN,i),ds(this,jd,Uns).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:td.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:n},!0)},Uns=function(n){if(!ye(this,iw))return;ds(this,jd,Q3e).call(this,{highlightOutlines:ye(this,ES).getNewOutline(n/2)}),this.fixAndSetPosition();const[r,a]=this.parentDimensions;this.setDims(this.width*r,this.height*a)},iXe=function(){ye(this,r1)===null||!this.parent||(this.parent.drawLayer.remove(ye(this,r1)),Yt(this,r1,null),this.parent.drawLayer.remove(ye(this,c0)),Yt(this,c0,null))},zO=function(n=this.parent){ye(this,r1)===null&&({id:Z0(this,r1)._,clipPathId:Z0(this,vz)._}=n.drawLayer.draw(ye(this,ES),this.color,ye(this,sE)),Yt(this,c0,n.drawLayer.drawOutline(ye(this,yN))),ye(this,bz)&&(ye(this,bz).style.clipPath=ye(this,vz)))},ON=new WeakSet,CU=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}},qns=function(n){Xh._keyboardManager.exec(this,n)},J3e=function(n){if(!ye(this,WH))return;const r=window.getSelection();n?r.setPosition(ye(this,WH),ye(this,nae)):r.setPosition(ye(this,rae),ye(this,aae))},LQ=function(){return ye(this,iw)?this.rotation:0},Vns=function(){if(ye(this,iw))return null;const[n,r]=this.pageDimensions,[a,i]=this.pageTranslation,l=ye(this,tE),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},Hns=function(n){return ye(this,ES).serialize(n,ds(this,jd,LQ).call(this))},Gns=function(n,r){this._freeHighlight.add(r)&&n.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},Wns=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=""},Kns=function(n){const{color:r}=this._initialData;return n.color.some((a,i)=>a!==r[i])},ys(Xh,ON),_r(Xh,"_defaultColor",null),_r(Xh,"_defaultOpacity",1),_r(Xh,"_defaultThickness",12),_r(Xh,"_type","highlight"),_r(Xh,"_editorType",Rd.HIGHLIGHT),_r(Xh,"_freeHighlightId",-1),_r(Xh,"_freeHighlight",null),_r(Xh,"_freeHighlightClipId","");let pPe=Xh;var _z,wz,K5,nE,bN,jz,Nz,kz,rE,XH,Sz,Cz,rI,Gi,Yns,Zns,Xns,Qns,lXe,Jns,cXe,ers,trs,srs,nrs,rrs,BO,dXe,uXe,hXe,eAe,tAe,AU,mXe,sAe,wT,ars,fXe,irs,ors,pXe,nAe,RQ;const pg=class pg extends Cm{constructor(n){super({...n,name:"inkEditor"});ys(this,Gi);ys(this,_z,0);ys(this,wz,0);ys(this,K5,null);ys(this,nE,new Path2D);ys(this,bN,!1);ys(this,jz,null);ys(this,Nz,!1);ys(this,kz,!1);ys(this,rE,null);ys(this,XH,null);ys(this,Sz,0);ys(this,Cz,0);ys(this,rI,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){Cm.initialize(n,r)}static updateDefaultParams(n,r){switch(n){case td.INK_THICKNESS:pg._defaultThickness=r;break;case td.INK_COLOR:pg._defaultColor=r;break;case td.INK_OPACITY:pg._defaultOpacity=r/100;break}}updateParams(n,r){switch(n){case td.INK_THICKNESS:ds(this,Gi,Yns).call(this,r);break;case td.INK_COLOR:ds(this,Gi,Zns).call(this,r);break;case td.INK_OPACITY:ds(this,Gi,Xns).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[td.INK_THICKNESS,pg._defaultThickness],[td.INK_COLOR,pg._defaultColor||Cm._defaultLineColor],[td.INK_OPACITY,Math.round(pg._defaultOpacity*100)]]}get propertiesToUpdate(){return[[td.INK_THICKNESS,this.thickness||pg._defaultThickness],[td.INK_COLOR,this.color||pg._defaultColor||Cm._defaultLineColor],[td.INK_OPACITY,Math.round(100*(this.opacity??pg._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(ds(this,Gi,eAe).call(this),ds(this,Gi,tAe).call(this)),this.isAttachedToDOM||(this.parent.add(this),ds(this,Gi,AU).call(this)),ds(this,Gi,RQ).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,K5)&&(clearTimeout(ye(this,K5)),Yt(this,K5,null)),(n=ye(this,rE))==null||n.disconnect(),Yt(this,rE,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,bN)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,ds(this,Gi,dXe).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),ds(this,Gi,uXe).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,bN)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),Yt(this,bN,!0),this.div.classList.add("disabled"),ds(this,Gi,RQ).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,bN)||(this.setInForeground(),n.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),ds(this,Gi,Jns).call(this,n.offsetX,n.offsetY))}canvasPointermove(n){n.preventDefault(),ds(this,Gi,cXe).call(this,n.offsetX,n.offsetY)}canvasPointerup(n){n.preventDefault(),ds(this,Gi,hXe).call(this,n)}canvasPointerleave(n){ds(this,Gi,hXe).call(this,n)}get isResizable(){return!this.isEmpty()&&ye(this,bN)}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]=ds(this,Gi,Qns).call(this);if(this.setAt(a,i,0,0),this.setDims(l,o),ds(this,Gi,eAe).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),Yt(this,kz,!0),ds(this,Gi,AU).call(this),this.setDims(this.width*c,this.height*d),ds(this,Gi,BO).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return ds(this,Gi,tAe).call(this),this.div}setDimensions(n,r){const a=Math.round(n),i=Math.round(r);if(ye(this,Sz)===a&&ye(this,Cz)===i)return;Yt(this,Sz,a),Yt(this,Cz,i),this.canvas.style.visibility="hidden";const[l,o]=this.parentDimensions;this.width=n/l,this.height=r/o,this.fixAndSetPosition(),ye(this,bN)&&ds(this,Gi,mXe).call(this,n,r),ds(this,Gi,AU).call(this),ds(this,Gi,BO).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(n,r,a){var v,y,b;if(n instanceof Iot)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;Yt(i,bN,!0),Yt(i,Sz,Math.round(c)),Yt(i,Cz,Math.round(d));const{paths:m,rect:f,rotation:g}=n;for(let{bezier:w}of m){w=ds(v=pg,wT,irs).call(v,w,f,g);const S=[];i.paths.push(S);let A=u*(w[0]-h),E=u*(w[1]-h);for(let P=2,R=w.length;P{this.thickness=i,ds(this,Gi,RQ).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:td.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},Zns=function(n){const r=i=>{this.color=i,ds(this,Gi,BO).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:td.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},Xns=function(n){const r=i=>{this.opacity=i,ds(this,Gi,BO).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:td.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},Qns=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]}},lXe=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}${zKn(a)}`},Jns=function(n,r){this.canvas.addEventListener("contextmenu",fk,{signal:this._uiManager._signal}),ds(this,Gi,uXe).call(this),Yt(this,jz,new AbortController);const a=this._uiManager.combinedSignal(ye(this,jz));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,kz)||(Yt(this,kz,!0),ds(this,Gi,AU).call(this),this.thickness||(this.thickness=pg._defaultThickness),this.color||(this.color=pg._defaultColor||Cm._defaultLineColor),this.opacity??(this.opacity=pg._defaultOpacity)),this.currentPath.push([n,r]),Yt(this,Nz,!1),ds(this,Gi,lXe).call(this),Yt(this,rI,()=>{ds(this,Gi,srs).call(this),ye(this,rI)&&window.requestAnimationFrame(ye(this,rI))}),window.requestAnimationFrame(ye(this,rI))},cXe=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,nE);if(l.push([n,r]),Yt(this,Nz,!0),l.length<=2){o.moveTo(...l[0]),o.lineTo(n,r);return}l.length===3&&(Yt(this,nE,o=new Path2D),o.moveTo(...l[0])),ds(this,Gi,nrs).call(this,o,...l.at(-3),...l.at(-2),n,r)},ers=function(){if(this.currentPath.length===0)return;const n=this.currentPath.at(-1);ye(this,nE).lineTo(...n)},trs=function(n,r){Yt(this,rI,null),n=Math.min(Math.max(n,0),this.canvas.width),r=Math.min(Math.max(r,0),this.canvas.height),ds(this,Gi,cXe).call(this,n,r),ds(this,Gi,ers).call(this);let a;if(this.currentPath.length!==1)a=ds(this,Gi,rrs).call(this);else{const d=[n,r];a=[[d,d.slice(),d.slice(),d]]}const i=ye(this,nE),l=this.currentPath;this.currentPath=[],Yt(this,nE,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||(ds(this,Gi,eAe).call(this),ds(this,Gi,tAe).call(this)),ds(this,Gi,RQ).call(this))};this.addCommands({cmd:o,undo:c,mustExec:!0})},srs=function(){if(!ye(this,Nz))return;Yt(this,Nz,!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,nE)),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)},rrs=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{Yt(this,K5,null),this.canvas.removeEventListener("contextmenu",fk)},10)),ds(this,Gi,trs).call(this,n.offsetX,n.offsetY),this.addToAnnotationStorage(),this.setInBackground()},eAe=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")},tAe=function(){Yt(this,rE,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&this.setDimensions(r.width,r.height)})),ye(this,rE).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=ye(this,rE))==null||n.disconnect(),Yt(this,rE,null)},{once:!0})},AU=function(){if(!ye(this,kz))return;const[n,r]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*n),this.canvas.height=Math.ceil(this.height*r),ds(this,Gi,sAe).call(this)},mXe=function(n,r){const a=ds(this,Gi,nAe).call(this),i=(n-a)/ye(this,wz),l=(r-a)/ye(this,_z);this.scaleFactor=Math.min(i,l)},sAe=function(){const n=ds(this,Gi,nAe).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+n,this.translationY*this.scaleFactor+n)},wT=new WeakSet,ars=function(n){const r=new Path2D;for(let a=0,i=n.length;a`image/${r}`))}static get supportedTypesStr(){return eh(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(n){return this.supportedTypes.includes(n)}static paste(n,r){r.pasteEditor(Rd.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,Qv)&&(Yt(this,yg,null),this._uiManager.imageManager.deleteId(ye(this,Qv)),(n=ye(this,Y5))==null||n.remove(),Yt(this,Y5,null),(r=ye(this,iE))==null||r.disconnect(),Yt(this,iE,null),ye(this,Z5)&&(clearTimeout(ye(this,Z5)),Yt(this,Z5,null))),super.remove()}rebuild(){if(!this.parent){ye(this,Qv)&&ds(this,Fu,rAe).call(this);return}super.rebuild(),this.div!==null&&(ye(this,Qv)&&ye(this,Y5)===null&&ds(this,Fu,rAe).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(ye(this,aI)||ye(this,yg)||ye(this,aE)||ye(this,iI)||ye(this,Qv))}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,yg)?ds(this,Fu,xXe).call(this):ds(this,Fu,rAe).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,yg),o=new mZe;let c=ye(this,yg),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,Lj)||(c=ds(this,Fu,aAe).call(this,g,x));const v=h.getContext("2d");v.filter=this._uiManager.hcmFilter;let y="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":(f=window.matchMedia)!=null&&f.call(window,"(prefers-color-scheme: dark)").matches&&(y="#8f8f9d",b="#42414d");const w=15,S=w*o.sx,A=w*o.sy,E=new OffscreenCanvas(S*2,A*2),I=E.getContext("2d");I.fillStyle=y,I.fillRect(0,0,S*2,A*2),I.fillStyle=b,I.fillRect(0,0,S,A),I.fillRect(S,A,S,A),v.fillStyle=v.createPattern(E,"repeat"),v.fillRect(0,0,g,x),v.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,Lj)||(c=ds(this,Fu,aAe).call(this,g,x))}const y=new OffscreenCanvas(g,x).getContext("2d",{willReadFrequently:!0});y.drawImage(c,0,0,c.width,c.height,0,0,g,x),m={width:g,height:x,data:y.getImageData(0,0,g,x).data}}return{canvas:h,width:d,height:u,imageData:m}}getImageForAltText(){return ye(this,Y5)}static async deserialize(n,r,a){var x;let i=null;if(n instanceof bns){const{data:{rect:v,rotation:y,id:b,structParent:w,popupRef:S},container:A,parent:{page:{pageNumber:E}}}=n,I=A.querySelector("canvas"),P=a.imageManager.getFromCanvas(A.id,I);I.remove();const R=((x=await r._structTree.getAriaAttributes(`${wot}${b}`))==null?void 0:x.get("aria-label"))||"";i=n={annotationType:Rd.STAMP,bitmapId:P.id,bitmap:P.bitmap,pageIndex:E-1,rect:v.slice(0),rotation:y,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)?(Yt(l,Qv,u),c&&Yt(l,yg,c)):Yt(l,aE,d),Yt(l,Lj,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,Yt(l,JH,!!i),l}serialize(n=!1,r=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const a={annotationType:Rd.STAMP,bitmapId:ye(this,Qv),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:ye(this,Lj),structTreeParentId:this._structTreeParentId};if(n)return a.bitmapUrl=ds(this,Fu,iAe).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=ds(this,Fu,drs).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,Lj)?(a.rect[2]-a.rect[0])*(a.rect[3]-a.rect[1]):null;if(!r.stamps.has(ye(this,Qv)))r.stamps.set(ye(this,Qv),{area:o,serialized:a}),a.bitmap=ds(this,Fu,iAe).call(this,!1);else if(ye(this,Lj)){const c=r.stamps.get(ye(this,Qv));o>c.area&&(c.area=o,c.serialized.bitmap.close(),c.serialized.bitmap=ds(this,Fu,iAe).call(this,!1))}return a}renderAnnotationElement(n){return n.updateEdited({rect:this.getRect(0,0)}),null}};yg=new WeakMap,Qv=new WeakMap,aI=new WeakMap,aE=new WeakMap,iI=new WeakMap,QH=new WeakMap,Y5=new WeakMap,iE=new WeakMap,Z5=new WeakMap,Lj=new WeakMap,JH=new WeakMap,Fu=new WeakSet,DQ=function(n,r=!1){if(!n){this.remove();return}Yt(this,yg,n.bitmap),r||(Yt(this,Qv,n.id),Yt(this,Lj,n.isSvg)),n.file&&Yt(this,QH,n.file.name),ds(this,Fu,xXe).call(this)},FQ=function(){if(Yt(this,aI,null),this._uiManager.enableWaiting(!1),!!ye(this,Y5)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&ye(this,yg)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&ye(this,yg)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},rAe=function(){if(ye(this,Qv)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(ye(this,Qv)).then(a=>ds(this,Fu,DQ).call(this,a,!0)).finally(()=>ds(this,Fu,FQ).call(this));return}if(ye(this,aE)){const a=ye(this,aE);Yt(this,aE,null),this._uiManager.enableWaiting(!0),Yt(this,aI,this._uiManager.imageManager.getFromUrl(a).then(i=>ds(this,Fu,DQ).call(this,i)).finally(()=>ds(this,Fu,FQ).call(this)));return}if(ye(this,iI)){const a=ye(this,iI);Yt(this,iI,null),this._uiManager.enableWaiting(!0),Yt(this,aI,this._uiManager.imageManager.getFromFile(a).then(i=>ds(this,Fu,DQ).call(this,i)).finally(()=>ds(this,Fu,FQ).call(this)));return}const n=document.createElement("input");n.type="file",n.accept=vte.supportedTypesStr;const r=this._uiManager._signal;Yt(this,aI,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}}),ds(this,Fu,DQ).call(this,i)}a()},{signal:r}),n.addEventListener("cancel",()=>{this.remove(),a()},{signal:r})}).finally(()=>ds(this,Fu,FQ).call(this))),n.click()},xXe=function(){const{div:n}=this;let{width:r,height:a}=ye(this,yg);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=Yt(this,Y5,document.createElement("canvas"));u.setAttribute("role","img"),this.addContainer(u),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(n.hidden=!1),ds(this,Fu,yXe).call(this,r,a),ds(this,Fu,crs).call(this),ye(this,JH)||(this.parent.addUndoableEditor(this),Yt(this,JH,!0)),this._reportTelemetry({action:"inserted_image"}),ye(this,QH)&&u.setAttribute("aria-label",ye(this,QH))},lrs=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,Z5)!==null&&clearTimeout(ye(this,Z5)),Yt(this,Z5,setTimeout(()=>{Yt(this,Z5,null),ds(this,Fu,yXe).call(this,n,r)},200))},aAe=function(n,r){const{width:a,height:i}=ye(this,yg);let l=a,o=i,c=ye(this,yg);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},yXe=function(n,r){const a=new mZe,i=Math.ceil(n*a.sx),l=Math.ceil(r*a.sy),o=ye(this,Y5);if(!o||o.width===i&&o.height===l)return;o.width=i,o.height=l;const c=ye(this,Lj)?ye(this,yg):ds(this,Fu,aAe).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)},iAe=function(n){if(n){if(ye(this,Lj)){const i=this._uiManager.imageManager.getSvgUrl(ye(this,Qv));if(i)return i}const r=document.createElement("canvas");return{width:r.width,height:r.height}=ye(this,yg),r.getContext("2d").drawImage(ye(this,yg),0,0),r.toDataURL()}if(ye(this,Lj)){const[r,a]=this.pageDimensions,i=Math.round(this.width*r*zL.PDF_TO_CSS_UNITS),l=Math.round(this.height*a*zL.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(i,l);return o.getContext("2d").drawImage(ye(this,yg),0,0,ye(this,yg).width,ye(this,yg).height,0,0,i,l),o.transferToImageBitmap()}return structuredClone(ye(this,yg))},crs=function(){this._uiManager._signal&&(Yt(this,iE,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&ds(this,Fu,lrs).call(this,r.width,r.height)})),ye(this,iE).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=ye(this,iE))==null||n.disconnect(),Yt(this,iE,null)},{once:!0}))},drs=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}},_r(vte,"_type","stamp"),_r(vte,"_editorType",Rd.STAMP);let gXe=vte;var Az,eG,X5,oI,oE,Rj,lI,tG,sG,a1,lE,Ll,cI,jb,urs,bXe,_Xe,wXe,oAe;const hS=class hS{constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:a,accessibilityManager:i,annotationLayer:l,drawLayer:o,textLayer:c,viewport:d,l10n:u}){ys(this,jb);ys(this,Az);ys(this,eG,!1);ys(this,X5,null);ys(this,oI,null);ys(this,oE,null);ys(this,Rj,new Map);ys(this,lI,!1);ys(this,tG,!1);ys(this,sG,!1);ys(this,a1,null);ys(this,lE,null);ys(this,Ll);const h=[...ye(hS,cI).values()];if(!hS._initialized){hS._initialized=!0;for(const m of h)m.initialize(u,t)}t.registerEditorTypes(h),Yt(this,Ll,t),this.pageIndex=n,this.div=r,Yt(this,Az,i),Yt(this,X5,l),this.viewport=d,Yt(this,a1,c),this.drawLayer=o,this._structTree=a,ye(this,Ll).addLayer(this)}get isEmpty(){return ye(this,Rj).size===0}get isInvisible(){return this.isEmpty&&ye(this,Ll).getMode()===Rd.NONE}updateToolbar(t){ye(this,Ll).updateToolbar(t)}updateMode(t=ye(this,Ll).getMode()){switch(ds(this,jb,oAe).call(this),t){case Rd.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case Rd.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case Rd.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(hS,cI).values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(t){var n;return t===((n=ye(this,a1))==null?void 0:n.div)}addInkEditorIfNeeded(t){if(ye(this,Ll).getMode()!==Rd.INK)return;if(!t){for(const r of ye(this,Rj).values())if(r.isEmpty()){r.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){ye(this,Ll).setEditingState(t)}addCommands(t){ye(this,Ll).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,X5))==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,Rj).values())r.enableEditing(),r.show(!0),r.annotationElementId&&(ye(this,Ll).removeChangedExistingAnnotation(r),t.add(r.annotationElementId));if(!ye(this,X5))return;const n=ye(this,X5).getEditableAnnotations();for(const r of n){if(r.hide(),ye(this,Ll).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;Yt(this,sG,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,n=new Map;for(const i of ye(this,Rj).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,X5)){const i=ye(this,X5).getEditableAnnotations();for(const l of i){const{id:o}=l.data;if(ye(this,Ll).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,Ll).addChangedExistingAnnotation(c),c.renderAnnotationElement(l)&&c.show(!1)),l.show()}}ds(this,jb,oAe).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const i of ye(hS,cI).values())r.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),Yt(this,sG,!1)}getEditableAnnotation(t){var n;return((n=ye(this,X5))==null?void 0:n.getEditableAnnotation(t))||null}setActiveEditor(t){ye(this,Ll).getActive()!==t&&ye(this,Ll).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=ye(this,a1))!=null&&t.div&&!ye(this,lE)){Yt(this,lE,new AbortController);const n=ye(this,Ll).combinedSignal(ye(this,lE));ye(this,a1).div.addEventListener("pointerdown",ds(this,jb,urs).bind(this),{signal:n}),ye(this,a1).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=ye(this,a1))!=null&&t.div&&ye(this,lE)&&(ye(this,lE).abort(),Yt(this,lE,null),ye(this,a1).div.classList.remove("highlighting"))}enableClick(){if(ye(this,oI))return;Yt(this,oI,new AbortController);const t=ye(this,Ll).combinedSignal(ye(this,oI));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,oI))==null||t.abort(),Yt(this,oI,null)}attach(t){ye(this,Rj).set(t.id,t);const{annotationElementId:n}=t;n&&ye(this,Ll).isDeletedAnnotationElement(n)&&ye(this,Ll).removeDeletedAnnotationElement(t)}detach(t){var n;ye(this,Rj).delete(t.id),(n=ye(this,Az))==null||n.removePointerInTextLayer(t.contentDiv),!ye(this,sG)&&t.annotationElementId&&ye(this,Ll).addDeletedAnnotationElement(t)}remove(t){this.detach(t),ye(this,Ll).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,ye(this,tG)||this.addInkEditorIfNeeded(!1)}changeParent(t){var n;t.parent!==this&&(t.parent&&t.annotationElementId&&(ye(this,Ll).addDeletedAnnotationElement(t.annotationElementId),Cm.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,Ll).addEditor(t),this.attach(t),!t.isAttachedToDOM){const n=t.render();this.div.append(n),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),ye(this,Ll).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var r;if(!t.isAttachedToDOM)return;const{activeElement:n}=document;t.div.contains(n)&&!ye(this,oE)&&(t._focusEventsAllowed=!1,Yt(this,oE,setTimeout(()=>{Yt(this,oE,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:ye(this,Ll)._signal}),n.focus())},0))),t._structTreeParentId=(r=ye(this,Az))==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,Ll).getId()}combinedSignal(t){return ye(this,Ll).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=ye(this,jb,bXe))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,n){ye(this,Ll).updateToolbar(t),ye(this,Ll).updateMode(t);const{offsetX:r,offsetY:a}=ds(this,jb,wXe).call(this),i=this.getNextId(),l=ds(this,jb,_Xe).call(this,{parent:this,id:i,x:r,y:a,uiManager:ye(this,Ll),isCentered:!0,...n});l&&this.add(l)}async deserialize(t){var n;return await((n=ye(hS,cI).get(t.annotationType??t.annotationEditorType))==null?void 0:n.deserialize(t,this,ye(this,Ll)))||null}createAndAddNewEditor(t,n,r={}){const a=this.getNextId(),i=ds(this,jb,_Xe).call(this,{parent:this,id:a,x:t.offsetX,y:t.offsetY,uiManager:ye(this,Ll),isCentered:n,...r});return i&&this.add(i),i}addNewEditor(){this.createAndAddNewEditor(ds(this,jb,wXe).call(this),!0)}setSelected(t){ye(this,Ll).setSelected(t)}toggleSelected(t){ye(this,Ll).toggleSelected(t)}unselect(t){ye(this,Ll).unselect(t)}pointerup(t){const{isMac:n}=k_.platform;if(!(t.button!==0||t.ctrlKey&&n)&&t.target===this.div&&ye(this,lI)){if(Yt(this,lI,!1),!ye(this,eG)){Yt(this,eG,!0);return}if(ye(this,Ll).getMode()===Rd.STAMP){ye(this,Ll).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(ye(this,Ll).getMode()===Rd.HIGHLIGHT&&this.enableTextSelection(),ye(this,lI)){Yt(this,lI,!1);return}const{isMac:n}=k_.platform;if(t.button!==0||t.ctrlKey&&n||t.target!==this.div)return;Yt(this,lI,!0);const r=ye(this,Ll).getActive();Yt(this,eG,!r||r.isEmpty())}findNewParent(t,n,r){const a=ye(this,Ll).findParent(n,r);return a===null||a===this?!1:(a.changeParent(t),!0)}destroy(){var t,n;((t=ye(this,Ll).getActive())==null?void 0:t.parent)===this&&(ye(this,Ll).commitOrRemove(),ye(this,Ll).setActiveEditor(null)),ye(this,oE)&&(clearTimeout(ye(this,oE)),Yt(this,oE,null));for(const r of ye(this,Rj).values())(n=ye(this,Az))==null||n.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,ye(this,Rj).clear(),ye(this,Ll).removeLayer(this)}render({viewport:t}){this.viewport=t,hB(this.div,t);for(const n of ye(this,Ll).getEditors(this.pageIndex))this.add(n),n.rebuild();this.updateMode()}update({viewport:t}){ye(this,Ll).commitOrRemove(),ds(this,jb,oAe).call(this);const n=this.viewport.rotation,r=t.rotation;if(this.viewport=t,hB(this.div,{rotation:r}),n!==r)for(const a of ye(this,Rj).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,Ll).viewParameters.realScale}};Az=new WeakMap,eG=new WeakMap,X5=new WeakMap,oI=new WeakMap,oE=new WeakMap,Rj=new WeakMap,lI=new WeakMap,tG=new WeakMap,sG=new WeakMap,a1=new WeakMap,lE=new WeakMap,Ll=new WeakMap,cI=new WeakMap,jb=new WeakSet,urs=function(t){ye(this,Ll).unselectAll();const{target:n}=t;if(n===ye(this,a1).div||(n.getAttribute("role")==="img"||n.classList.contains("endOfContent"))&&ye(this,a1).div.contains(n)){const{isMac:r}=k_.platform;if(t.button!==0||t.ctrlKey&&r)return;ye(this,Ll).showAllEditors("highlight",!0,!0),ye(this,a1).div.classList.add("free"),this.toggleDrawing(),pPe.startHighlighting(this,ye(this,Ll).direction==="ltr",{target:ye(this,a1).div,x:t.x,y:t.y}),ye(this,a1).div.addEventListener("pointerup",()=>{ye(this,a1).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:ye(this,Ll)._signal}),t.preventDefault()}},bXe=function(){return ye(hS,cI).get(ye(this,Ll).getMode())},_Xe=function(t){const n=ye(this,jb,bXe);return n?new n.prototype.constructor(t):null},wXe=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}},oAe=function(){Yt(this,tG,!0);for(const t of ye(this,Rj).values())t.isEmpty()&&t.remove();Yt(this,tG,!1)},_r(hS,"_initialized",!1),ys(hS,cI,new Map([QZe,oXe,gXe,pPe].map(t=>[t._editorType,t])));let vXe=hS;var Q5,oae,Cy,cE,lae,NXe,wB,kXe,hrs;const Yv=class Yv{constructor({pageIndex:t}){ys(this,wB);ys(this,Q5,null);ys(this,oae,0);ys(this,Cy,new Map);ys(this,cE,new Map);this.pageIndex=t}setParent(t){if(!ye(this,Q5)){Yt(this,Q5,t);return}if(ye(this,Q5)!==t){if(ye(this,Cy).size>0)for(const n of ye(this,Cy).values())n.remove(),t.append(n);Yt(this,Q5,t)}}static get _svgFactory(){return eh(this,"_svgFactory",new Pot)}draw(t,n,r,a=!1){const i=Z0(this,oae)._++,l=ds(this,wB,kXe).call(this,t.box);l.classList.add(...t.classNamesForDrawing);const o=Yv._svgFactory.createElement("defs");l.append(o);const c=Yv._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,cE).set(i,c);const u=ds(this,wB,hrs).call(this,o,d),h=Yv._svgFactory.createElement("use");return l.append(h),l.setAttribute("fill",n),l.setAttribute("fill-opacity",r),h.setAttribute("href",`#${d}`),ye(this,Cy).set(i,l),{id:i,clipPathId:`url(#${u})`}}drawOutline(t){const n=Z0(this,oae)._++,r=ds(this,wB,kXe).call(this,t.box);r.classList.add(...t.classNamesForOutlining);const a=Yv._svgFactory.createElement("defs");r.append(a);const i=Yv._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=Yv._svgFactory.createElement("mask");a.append(u),o=`mask_p${this.pageIndex}_${n}`,u.setAttribute("id",o),u.setAttribute("maskUnits","objectBoundingBox");const h=Yv._svgFactory.createElement("rect");u.append(h),h.setAttribute("width","1"),h.setAttribute("height","1"),h.setAttribute("fill","white");const m=Yv._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=Yv._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,Cy).set(n,r),n}finalizeLine(t,n){const r=ye(this,cE).get(t);ye(this,cE).delete(t),this.updateBox(t,n.box),r.setAttribute("d",n.toSVGPath())}updateLine(t,n){ye(this,Cy).get(t).firstChild.firstChild.setAttribute("d",n.toSVGPath())}updatePath(t,n){ye(this,cE).get(t).setAttribute("d",n.toSVGPath())}updateBox(t,n){var r;ds(r=Yv,lae,NXe).call(r,ye(this,Cy).get(t),n)}show(t,n){ye(this,Cy).get(t).classList.toggle("hidden",!n)}rotate(t,n){ye(this,Cy).get(t).setAttribute("data-main-rotation",n)}changeColor(t,n){ye(this,Cy).get(t).setAttribute("fill",n)}changeOpacity(t,n){ye(this,Cy).get(t).setAttribute("fill-opacity",n)}addClass(t,n){ye(this,Cy).get(t).classList.add(n)}removeClass(t,n){ye(this,Cy).get(t).classList.remove(n)}getSVGRoot(t){return ye(this,Cy).get(t)}remove(t){ye(this,cE).delete(t),ye(this,Q5)!==null&&(ye(this,Cy).get(t).remove(),ye(this,Cy).delete(t))}destroy(){Yt(this,Q5,null);for(const t of ye(this,Cy).values())t.remove();ye(this,Cy).clear(),ye(this,cE).clear()}};Q5=new WeakMap,oae=new WeakMap,Cy=new WeakMap,cE=new WeakMap,lae=new WeakSet,NXe=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}%`},wB=new WeakSet,kXe=function(t){var r;const n=Yv._svgFactory.create(1,1,!0);return ye(this,Q5).append(n),n.setAttribute("aria-hidden",!0),ds(r=Yv,lae,NXe).call(r,n,t),n},hrs=function(t,n){const r=Yv._svgFactory.createElement("clipPath");t.append(r);const a=`clip_${n}`;r.setAttribute("id",a),r.setAttribute("clipPathUnits","objectBoundingBox");const i=Yv._svgFactory.createElement("use");return r.append(i),i.setAttribute("href",`#${n}`),i.classList.add("clip"),a},ys(Yv,lae);let jXe=Yv;cd.AbortException;cd.AnnotationEditorLayer;cd.AnnotationEditorParamsType;cd.AnnotationEditorType;cd.AnnotationEditorUIManager;cd.AnnotationLayer;cd.AnnotationMode;cd.ColorPicker;cd.DOMSVGFactory;cd.DrawLayer;cd.FeatureTest;var Lot=cd.GlobalWorkerOptions;cd.ImageKind;cd.InvalidPDFException;cd.MissingPDFException;cd.OPS;cd.OutputScale;cd.PDFDataRangeTransport;cd.PDFDateString;cd.PDFWorker;cd.PasswordResponses;cd.PermissionFlag;cd.PixelsPerInch;cd.RenderingCancelledException;cd.TextLayer;cd.UnexpectedResponseException;cd.Util;cd.VerbosityLevel;cd.XfaLayer;cd.build;cd.createValidAbsoluteUrl;cd.fetchData;var gPe=cd.getDocument;cd.getFilenameFromUrl;cd.getPdfFilenameFromUrl;cd.getXfaPageViewport;cd.isDataScheme;cd.isPdfFile;cd.noContextMenu;cd.normalizeUnicode;cd.setLayerDimensions;cd.shadow;cd.version;const Rot="/assets/pdf.worker.min-GB3t0DcA.mjs";Lot.workerSrc=Rot;const yZn=({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 gPe({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 v=x.getContext("2d");v&&(c.appendChild(x),await f.render({canvasContext:v,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(Ct,{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 h9({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}=_s(),d=j.useRef(null),[u,h]=j.useState(!1),m=async f=>{if(!(!f||!c)){if(!f.type.startsWith("image/")){ne.error("Please choose an image file");return}if(f.size>20*1024*1024){ne.error("That photo is larger than 20 MB");return}h(!0);try{const g=await pKn(c.id,f,r);n(g),ne.success("Photo uploaded")}catch(g){ne.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(Hc,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(kv,{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(mr,{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 vZn({value:s,onChange:t}){return e.jsxs(je,{children:[e.jsxs(St,{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(Yn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Et,{className:"text-base",children:"Co-listing agent"})]}),e.jsx(jn,{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(Le,{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(h9,{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 bZn({value:s,onChange:t}){return e.jsxs(je,{children:[e.jsxs(St,{className:"pb-3",children:[e.jsx(Et,{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(Le,{className:"grid gap-2 sm:grid-cols-2",children:lZe.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(ma,{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 _Zn={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}]},wZn=["cover","welcome","agent","overview","closing"];function jZn({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(je,{children:[e.jsxs(St,{className:"pb-3",children:[e.jsx(Et,{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(Le,{children:e.jsx(BB,{type:"multiple",className:"w-full",children:wZn.filter(i=>i==="cover"||!n.has(i)).map(i=>{const l=tts(s,i);return e.jsxs(c6,{value:i,children:[e.jsx(d6,{className:"text-sm",children:FVn[i]}),e.jsxs(u6,{className:"space-y-3 pt-1",children:[_Zn[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:WYe[i][o.key],onChange:c=>r(i,o.key,c.target.value)}):e.jsx(pe,{value:l[o.key]||"",placeholder:WYe[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(Sx,{className:"h-3.5 w-3.5"})," Reset to default wording"]})]})]},i)})})})]})}function NZn({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,uot(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(je,{children:[e.jsxs(St,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(o2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Et,{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(Le,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:s$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(cn,{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(Vc,{}),e.jsx(BB,{type:"multiple",className:"w-full",children:n.map((o,c)=>{var d,u,h;return e.jsxs(c6,{value:o.id,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{checked:o.enabled,onCheckedChange:m=>r(o.id,{enabled:m})}),e.jsx(d6,{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=s$e.find(m=>m.layout===o.layout))==null?void 0:u.name),e.jsx($e,{variant:"secondary",className:"text-[10px]",children:(h=s$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(Lg,{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(qn,{className:"h-3.5 w-3.5"})})]}),e.jsxs(u6,{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(jn,{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(h9,{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(qn,{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(cn,{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(qn,{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(cn,{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(qn,{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(cn,{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 kZn({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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Save as a reusable template"}),e.jsx(Er,{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(Nr,{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(Ct,{className:"h-4 w-4 animate-spin"})," Save template"]})]})]})})}const d3t=["welcome","agent","overview","closing"],SZn=()=>{const{id:s}=Wi(),t=Zn(),{user:n}=_s(),{data:r}=w6e(),{data:a,isLoading:i,refetch:l}=RVn(s),{update:o}=ets(),{save:c}=Jes(),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(ZYe(null)),[x,v]=j.useState(sts),[y,b]=j.useState([]),[w,S]=j.useState(KYe),[A,E]=j.useState(YYe),[I,P]=j.useState(null),[R,D]=j.useState(null),[O,U]=j.useState(!1),[W,V]=j.useState(!1),[G,Z]=j.useState(null),[X,ae]=j.useState(!1),[le,re]=j.useState(!1),[te,J]=j.useState(!1),[ce,ve]=j.useState(!1),[fe,ue]=j.useState(!0),[be,Ee]=j.useState(!1),ke=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 Qe=a.agent_snapshot;m({...r,...Qe||{}}),g(ZYe(a.services)),v(nts(a.co_agent)),b(ats(a.custom_pages)),S(a.page_settings&&Object.keys(a.page_settings).length?a.page_settings:KYe),E(a.photo_focal||YYe),P(a.property_photo_path)},[a,r,d]),j.useEffect(()=>{let Qe=!1;return I?cPe(I).then(at=>{Qe||D(at)}):D(null),()=>{Qe=!0}},[I]);const Ie=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:y,services:f,page_settings:w,photo_focal:A,property_photo_path:I},[a,d,h,x,y,f,w,A,I]),Fe=Qe=>u(at=>at&&{...at,...Qe}),Ne=Qe=>m(at=>at&&{...at,...Qe}),Be=Qe=>(w.hidden||[]).includes(Qe),Se=(Qe,at)=>S(rt=>{const Ke=new Set(rt.hidden||[]);return at?Ke.delete(Qe):Ke.add(Qe),{...rt,hidden:Array.from(Ke)}}),Ae=f.filter(Qe=>Qe.enabled),Ce=1+d3t.filter(Qe=>!Be(Qe)&&Qe!=="overview").length+(Be("overview")?0:1)+Ae.filter(Qe=>Qe.key!=="communication").length+y.filter(Qe=>Qe.enabled).length,qe=async(Qe=!1)=>{if(Ie){ve(!0);try{await o.mutateAsync({id:Ie.id,title:Ie.title||"Untitled Presentation",property_address_line1:Ie.property_address_line1,city:Ie.city,state:Ie.state,postal_code:Ie.postal_code,list_price:Ie.list_price,beds:Ie.beds,baths:Ie.baths,sqft:Ie.sqft,agent_snapshot:Ie.agent_snapshot,co_agent:Ie.co_agent,custom_pages:Ie.custom_pages,services:Ie.services,page_settings:Ie.page_settings,photo_focal:Ie.photo_focal,property_photo_path:Ie.property_photo_path}),Qe||ne.success("Presentation saved")}finally{ve(!1)}}},ze=async Qe=>{if(!(!n||!s)){if(!Qe.type.startsWith("image/")){ne.error("Please choose a JPG or PNG photo");return}if(Qe.size>25*1024*1024){ne.error("That photo is larger than 25 MB");return}U(!0);try{const at=await fKn(n.id,s,Qe);P(at);const rt=await cPe(at);D(rt?`${rt}${rt.includes("?")?"&":"?"}v=${Date.now()}`:null),await o.mutateAsync({id:s,property_photo_path:at}),ne.success("Photo uploaded")}catch(at){ne.error((at==null?void 0:at.message)||"Upload failed")}finally{U(!1)}}},Ve=async()=>{if(Ie){ae(!0);try{const Qe=await rss(dPe(Ie,r,R),Ie.template_id,I);Z(Qe)}catch(Qe){ne.error((Qe==null?void 0:Qe.message)||"Could not build the preview")}finally{ae(!1)}}};j.useEffect(()=>{if(!fe||!Ie)return;const Qe=setTimeout(()=>{Ve()},900);return()=>clearTimeout(Qe)},[fe,Ie]);const ht=async()=>{if(!(!Ie||!n)){if(!Ie.property_photo_path){ne.error("Add the primary exterior photo before generating the PDF");return}re(!0);try{await qe(!0);const Qe=await ass(dPe(Ie,r,R),Ie.template_id,"print",I);await iss(n.id,Ie.id,Qe),await l(),ne.success("Presentation downloaded")}catch(Qe){ne.error((Qe==null?void 0:Qe.message)||"Could not build the PDF")}finally{re(!1)}}};return i||!d||!a?e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-10 w-64"}),e.jsx(xn,{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(Va,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(pe,{value:d.title,onChange:Qe=>Fe({title:Qe.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(Ct,{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(OI,{className:"h-4 w-4"})," Save as template"]}),e.jsxs($,{variant:"outline",onClick:Ve,disabled:X,className:"gap-2",children:[X?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Ta,{className:"h-4 w-4"})," Preview"]}),e.jsxs($,{variant:"outline",onClick:async()=>{await qe(!0),J(!0)},className:"gap-2",children:[e.jsx(pn,{className:"h-4 w-4"})," Email"]}),e.jsxs($,{onClick:ht,disabled:le,className:"gap-2",children:[le?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(ji,{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(pa,{defaultValue:"property",className:"space-y-4",children:[e.jsxs(ga,{className:"grid w-full grid-cols-4",children:[e.jsx(Xt,{value:"property",children:"Property"}),e.jsx(Xt,{value:"branding",children:"Branding"}),e.jsx(Xt,{value:"plan",children:"Plan"}),e.jsx(Xt,{value:"pages",children:"Pages"})]}),e.jsxs(Qt,{value:"property",className:"space-y-4",children:[e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-base",children:"Property address"})}),e.jsxs(Le,{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:Qe=>Fe({addressLine1:Qe.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:Qe=>Fe({city:Qe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"State"}),e.jsx(pe,{value:d.state,onChange:Qe=>Fe({state:Qe.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"ZIP"}),e.jsx(pe,{value:d.postalCode,onChange:Qe=>Fe({postalCode:Qe.target.value})})]}),e.jsx(Vc,{}),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:Qe=>Fe({listPrice:Qe.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:Qe=>Fe({sqft:Qe.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:Qe=>Fe({beds:Qe.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:Qe=>Fe({baths:Qe.target.value.replace(/[^0-9.]/g,"")})})]})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"text-base",children:["Primary exterior photo ",e.jsx("span",{className:"text-destructive",children:"*"})]})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsx("div",{role:"button",tabIndex:0,onClick:()=>{var Qe;return(Qe=ke.current)==null?void 0:Qe.click()},onKeyDown:Qe=>{var at;return Qe.key==="Enter"&&((at=ke.current)==null?void 0:at.click())},onDragOver:Qe=>{Qe.preventDefault(),V(!0)},onDragLeave:()=>V(!1),onDrop:Qe=>{var rt;Qe.preventDefault(),V(!1);const at=(rt=Qe.dataTransfer.files)==null?void 0:rt[0];at&&ze(at)},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:`${A.x*100}% ${A.y*100}%`}}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-muted-foreground",children:[O?e.jsx(Ct,{className:"h-6 w-6 animate-spin"}):e.jsx(kv,{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:ke,type:"file",accept:"image/*",className:"hidden",onChange:Qe=>{var rt;const at=(rt=Qe.target.files)==null?void 0:rt[0];at&&ze(at),Qe.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(BJ,{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(bx,{value:[A.x*100],min:0,max:100,step:1,onValueChange:([Qe])=>E(at=>({...at,x:Qe/100}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Vertical"}),e.jsx(bx,{value:[A.y*100],min:0,max:100,step:1,onValueChange:([Qe])=>E(at=>({...at,y:Qe/100}))})]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>{var Qe;return(Qe=ke.current)==null?void 0:Qe.click()},disabled:O,children:[e.jsx(co,{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(Qt,{value:"branding",className:"space-y-4",children:[e.jsx(bZn,{value:w.theme||TWn,onChange:Qe=>S(at=>({...at,theme:Qe}))}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Et,{className:"text-base",children:"Your details"}),e.jsx($e,{variant:"secondary",className:"text-[10px]",children:"Loaded from your LevelUp profile"})]})}),e.jsx(Le,{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:Qe=>Ne({name:Qe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:h.tagline||"",onChange:Qe=>Ne({tagline:Qe.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:Qe=>Ne({phone:Qe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:h.email||"",onChange:Qe=>Ne({email:Qe.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Website"}),e.jsx(pe,{value:h.website||"",onChange:Qe=>Ne({website:Qe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage"}),e.jsx(pe,{value:h.brokerageName||"",onChange:Qe=>Ne({brokerageName:Qe.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:Qe=>Ne({licenseNumber:Qe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"License state"}),e.jsx(pe,{value:h.licenseState||"",onChange:Qe=>Ne({licenseState:Qe.target.value})})]})]}),e.jsx(Vc,{}),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:Qe=>Ne({brandColor:Qe.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(pe,{value:h.brandColor,onChange:Qe=>Ne({brandColor:Qe.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:Qe=>Ne({accentColor:Qe.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(pe,{value:h.accentColor,onChange:Qe=>Ne({accentColor:Qe.target.value})})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Headshot URL"}),e.jsx(pe,{value:h.headshotUrl||"",onChange:Qe=>Ne({headshotUrl:Qe.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:Qe=>Ne({brokerageLogoUrl:Qe.target.value})})]}),r&&e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>m({...r}),children:[e.jsx(co,{className:"h-4 w-4"})," Reset to my LevelUp profile"]})]})})]}),e.jsx(vZn,{value:x,onChange:Qe=>v(at=>({...at,...Qe}))})]}),e.jsx(Qt,{value:"plan",className:"space-y-4",children:e.jsxs(je,{children:[e.jsxs(St,{className:"pb-3",children:[e.jsx(Et,{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(Le,{children:e.jsx(BB,{type:"multiple",className:"w-full",children:f.slice().sort((Qe,at)=>Qe.order-at.order).map(Qe=>{var at;return e.jsxs(c6,{value:Qe.key,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(jn,{checked:Qe.enabled,onCheckedChange:rt=>g(Ke=>Ke.map(Je=>Je.key===Qe.key?{...Je,enabled:rt}:Je))}),e.jsx(d6,{className:"flex-1 text-left text-sm",children:Qe.title})]}),e.jsxs(u6,{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:Qe.title,onChange:rt=>g(Ke=>Ke.map(Je=>Je.key===Qe.key?{...Je,title:rt.target.value}:Je))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{rows:4,value:Qe.body,onChange:rt=>g(Ke=>Ke.map(Je=>Je.key===Qe.key?{...Je,body:rt.target.value}:Je))})]}),!!((at=Qe.options)!=null&&at.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"}),Qe.options.map(rt=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ai,{className:"mt-0.5",checked:rt.enabled,onCheckedChange:Ke=>g(Je=>Je.map(ft=>{var gt;return ft.key===Qe.key?{...ft,options:(gt=ft.options)==null?void 0:gt.map(es=>es.key===rt.key?{...es,enabled:!!Ke}:es)}:ft}))}),e.jsx("span",{className:"leading-snug",children:rt.label})]},rt.key))]})]})]},Qe.key)})})})]})}),e.jsxs(Qt,{value:"pages",className:"space-y-4",children:[e.jsxs(je,{children:[e.jsxs(St,{className:"pb-3",children:[e.jsx(Et,{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(Le,{className:"space-y-3",children:[d3t.map(Qe=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx("span",{className:"text-sm",children:zVn[Qe]}),e.jsx(jn,{checked:!Be(Qe),onCheckedChange:at=>Se(Qe,at)})]},Qe)),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"}),!Be("welcome")&&e.jsx("li",{children:"Marketing commitment"}),!Be("agent")&&e.jsx("li",{children:"About your agent"}),y.filter(Qe=>Qe.enabled&&Qe.placement!=="end").sort((Qe,at)=>Qe.order-at.order).map(Qe=>e.jsx("li",{children:Qe.headline||"Custom page"},Qe.id)),!Be("overview")&&e.jsx("li",{children:"Marketing plan overview"}),Ae.filter(Qe=>Qe.key!=="communication").map(Qe=>e.jsx("li",{children:Qe.title},Qe.key)),y.filter(Qe=>Qe.enabled&&Qe.placement==="end").sort((Qe,at)=>Qe.order-at.order).map(Qe=>e.jsx("li",{children:Qe.headline||"Custom page"},Qe.id)),!Be("closing")&&e.jsx("li",{children:"Communication & closing commitment"})]})]})]})]}),e.jsx(jZn,{pages:w,onChange:S}),e.jsxs(je,{children:[e.jsxs(St,{className:"pb-3",children:[e.jsx(Et,{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(Le,{children:e.jsx($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>b(Qe=>[...Qe,{...uot("testimonials",Qe.length),placement:"end"}]),children:`Add a "What they're saying" page`})})]}),e.jsx(NZn,{pages:y,onChange:b})]})]}),e.jsxs(je,{className:"min-h-[70vh] overflow-hidden",children:[e.jsxs(St,{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(Et,{className:"text-base",children:"Live preview"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(jn,{checked:fe,onCheckedChange:ue}),"Auto-update"]})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:Ve,disabled:X,className:"gap-2",children:[X?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(co,{className:"h-4 w-4"}),"Refresh"]})]}),e.jsx(Le,{className:"h-[calc(70vh-60px)] p-0",children:G?e.jsx(yZn,{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(Ta,{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:Ve,disabled:X,className:"gap-2",children:[X?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Ta,{className:"h-4 w-4"}),"Generate preview"]})]})})]})]})]}),e.jsx(kZn,{open:be,onOpenChange:Ee,defaultName:d.title,saving:c.isPending,onSave:async(Qe,at)=>{await c.mutateAsync({name:Qe,description:at||null,template_id:a.template_id,agent_snapshot:h||{},co_agent:x,custom_pages:y,services:f,page_settings:w})}}),e.jsx(lss,{open:te,onOpenChange:J,row:Ie,brand:r,photoUrl:R})]})};function CZn(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 mrs="popby_geocode_cache_v1";function AZn(){try{return JSON.parse(localStorage.getItem(mrs)||"{}")}catch{return{}}}function EZn(s){try{localStorage.setItem(mrs,JSON.stringify(s))}catch{}}function TZn({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=AZn(),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 A=g.filter(E=>!([E.address,E.city,E.state,E.zip].filter(Boolean).join("|").toLowerCase()in w));if(A.length!==0)return f(!0),(async()=>{const E=[...A],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[Z,X]=G.features[0].center;w[U]={lat:X,lng:Z},S.set(D.id,{lat:X,lng:Z})}else w[U]=null}catch{}}};await Promise.all([I(),I(),I(),I()]),b||(EZn(w),h(new Map(S)),f(!1))})(),()=>{b=!0}},[c,n,g]);const v=j.useMemo(()=>{if(!n)return[];const b=[];return g.forEach(w=>{const S=u.get(w.id);if(!S)return;const A=CZn(n.lat,n.lng,S.lat,S.lng);A<=l&&b.push({...w,distanceMiles:A,lat:S.lat,lng:S.lng})}),b.sort((w,S)=>w.distanceMiles-S.distanceMiles)},[n,g,u,l]),y=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(je,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(St,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Oq,{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(co,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Oq,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Le,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(ui,{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(vl,{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&&v.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(xn,{className:"h-14 w-full"}),e.jsx(xn,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!m&&v.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."]}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs($e,{variant:"secondary",className:"font-medium",children:[v.length," nearby"]}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(co,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:v.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($e,{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($e,{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:()=>y(b),className:"h-9 w-9",title:"Directions",children:e.jsx($J,{className:"h-4 w-4"})}),e.jsxs($,{size:"sm",onClick:()=>t(b),children:[e.jsx(dl,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},b.id))})]})]})]})}const MZn="0dde5abb-0005-4c8c-a471-30d0cbc9e280",PZn=[{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 IZn(){const s=Zn(),t=xQt(),{data:n}=CBn(),{data:r}=Uw(),{data:a}=cit(),{data:i}=sDe(90),{data:l}=L_(),o=PBn(),c=TBn(),d=EBn(),u=MBn(),{data:h=[],isLoading:m}=st({queryKey:["popby-templates"],queryFn:async()=>{const{data:G,error:Z}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",MZn).order("publish_date",{ascending:!1});if(Z)throw Z;const{data:X}=await q.from("template_likes").select("template_id"),{data:ae}=await q.from("template_comments").select("template_id"),le=new Map;X==null||X.forEach(te=>{le.set(te.template_id,(le.get(te.template_id)||0)+1)});const re=new Map;return ae==null||ae.forEach(te=>{re.set(te.template_id,(re.get(te.template_id)||0)+1)}),(G||[]).map(te=>({...te,likesCount:le.get(te.id)||0,commentsCount:re.get(te.id)||0}))}}),f=G=>{const Z=l==null?void 0:l.find(X=>X.id===G);return Z?`${Z.first_name} ${Z.last_name||""}`.trim():"Unknown"},g=G=>{if(!G)return null;const Z=n==null?void 0:n.find(X=>X.id===G);return(Z==null?void 0:Z.name)||null},[x,v]=j.useState(null),[y,b]=j.useState(!1),[w,S]=j.useState(!1),[A,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),v(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,Z)=>{await u.mutateAsync({relationship_type_id:G,frequency_days:parseInt(Z)})},V=G=>{var X;const Z=a==null?void 0:a.find(ae=>ae.relationship_type_id===G);return((X=Z==null?void 0:Z.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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{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(ui,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs($,{variant:"outline",onClick:()=>S(!0),children:[e.jsx(Nd,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs($,{variant:"outline",onClick:()=>E(!0),children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(pa,{defaultValue:"due",children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"due",children:"Due for Popby"}),e.jsx(Xt,{value:"activity",children:"Recent Activity"}),e.jsx(Xt,{value:"library",children:"Popby Library"}),e.jsx(Xt,{value:"templates",children:"Popby Templates"})]}),e.jsxs(Qt,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(TZn,{contacts:t||[],onLogPopby:G=>{v(G),b(!0)}}),!t||t.length===0?e.jsx(je,{children:e.jsxs(Le,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(dl,{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(je,{className:"hover:shadow-md transition-shadow",children:e.jsx(Le,{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($e,{variant:"destructive",className:"text-xs",children:[G.daysOverdue,"+ days overdue"]}),G.daysSinceLastPopby===null&&e.jsx($e,{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:[tX(G).hasAddress&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ui,{className:"h-3 w-3"}),tX(G).city||tX(G).line,tX(G).isSecondary&&e.jsxs("span",{className:"text-xs",children:["(",tX(G).label,")"]})]}),G.tags&&G.tags.length>0&&e.jsx("span",{children:G.tags.map(Z=>{var X;return(X=Z.relationship_type)==null?void 0:X.name}).join(", ")})]}),G.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",Js(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:()=>{v(G),b(!0)},children:[e.jsx(Wl,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},G.id))})]}),e.jsx(Qt,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(je,{children:e.jsxs(Le,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(ca,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Le,{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(dl,{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($e,{variant:"secondary",className:"text-xs",children:g(G.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Js(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(Qt,{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(je,{children:e.jsx(Le,{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(dl,{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($e,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},G.id)),e.jsx(je,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>E(!0),children:e.jsx(Le,{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(cn,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(Qt,{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,Z)=>e.jsx(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx(xn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(xn,{className:"h-5 w-3/4 mb-2"}),e.jsx(xn,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(xn,{className:"h-5 w-16"}),e.jsx(xn,{className:"h-5 w-20"})]})]})},Z))}),!m&&h.length===0&&e.jsx(je,{children:e.jsxs(Le,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(ym,{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(je,{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(Le,{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:Fte(G.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx($e,{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($y,{className:"h-3.5 w-3.5"}),G.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ah,{className:"h-3.5 w-3.5"}),G.commentsCount]})]}),e.jsxs($,{size:"sm",className:"w-full gap-2",onClick:Z=>{Z.stopPropagation(),s(`/templates/${G.id}`)},children:[e.jsx(Ir,{className:"h-4 w-4"}),"View Template"]})]})]},G.id))})]})]}),e.jsx(Os,{open:y,onOpenChange:b,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsxs($s,{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(Z=>({...Z,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(Z=>({...Z,notes:G.target.value}))})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx($,{onClick:O,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(Os,{open:w,onOpenChange:S,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{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:Z=>W(G.id,Z),children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:PZn.map(Z=>e.jsx(Ge,{value:Z.value,children:Z.label},Z.value))})]})]},G.id))]}),e.jsx(Nr,{children:e.jsx($,{onClick:()=>S(!1),children:"Done"})})]})}),e.jsx(Os,{open:A,onOpenChange:E,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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(Z=>({...Z,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(Z=>({...Z,description:G.target.value}))})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx($,{onClick:U,disabled:!R.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const LZn=F2({property_address:yl().min(1,"Property address is required"),city:yl().optional(),state:yl().optional(),zip:yl().optional(),transaction_type:ltt(["buyer","seller"]),close_date:yl().min(1,"Close date is required"),sale_price:hee().min(0,"Sale price must be positive"),commission_amount:hee().optional(),lead_source_id:yl().optional(),client_type_id:yl().optional(),contact_id:yl().optional(),notes:yl().optional(),is_win:_Ts()});function frs({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=N6e(),m=_Ws(),{data:f}=OB(),{data:g}=Uw(),{data:x}=L_(),v=x6e(),y=snt(),{data:b}=k6e(),w=(b==null?void 0:b.show_commission)??!0,S=yLe({resolver:vLe(LZn),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 A=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 v.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 y.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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(Us,{children:e.jsx($s,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(go,{className:"max-h-[70vh] pr-4",children:e.jsx(jLe,{...S,children:e.jsxs("form",{onSubmit:S.handleSubmit(A),className:"space-y-4",children:[e.jsx(_g,{control:S.control,name:"property_address",render:({field:R})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Property Address *"}),e.jsx(Up,{children:e.jsx(pe,{placeholder:"123 Main St",...R})}),e.jsx(m_,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(_g,{control:S.control,name:"city",render:({field:R})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"City"}),e.jsx(Up,{children:e.jsx(pe,{placeholder:"City",...R})})]})}),e.jsx(_g,{control:S.control,name:"state",render:({field:R})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"State"}),e.jsx(Up,{children:e.jsx(pe,{placeholder:"TX",...R})})]})}),e.jsx(_g,{control:S.control,name:"zip",render:({field:R})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Zip"}),e.jsx(Up,{children:e.jsx(pe,{placeholder:"75001",...R})})]})})]}),e.jsx(_g,{control:S.control,name:"transaction_type",render:({field:R})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Transaction Type *"}),e.jsxs(ms,{onValueChange:R.onChange,value:R.value,children:[e.jsx(Up,{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(m_,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(_g,{control:S.control,name:"close_date",render:({field:R})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Close Date *"}),e.jsx(Up,{children:e.jsx(pe,{type:"date",...R})}),e.jsx(m_,{})]})}),e.jsx(_g,{control:S.control,name:"sale_price",render:({field:R})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Sale Price *"}),e.jsx(Up,{children:e.jsx(pe,{type:"number",placeholder:"0",...R,onChange:D=>R.onChange(Number(D.target.value))})}),e.jsx(m_,{})]})})]}),w&&e.jsx(_g,{control:S.control,name:"commission_amount",render:({field:R})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Commission"}),e.jsx(Up,{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(_g,{control:S.control,name:"lead_source_id",render:({field:R})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Lead Source"}),e.jsxs(ms,{onValueChange:R.onChange,value:R.value||"",children:[e.jsx(Up,{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(cn,{className:"h-4 w-4"})})]}),e.jsx(_g,{control:S.control,name:"client_type_id",render:({field:R})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Client Type"}),e.jsxs(ms,{onValueChange:R.onChange,value:R.value||"",children:[e.jsx(Up,{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(_g,{control:S.control,name:"contact_id",render:({field:R})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Client Contact"}),e.jsxs(Gd,{open:r,onOpenChange:a,children:[e.jsx(Wd,{asChild:!0,children:e.jsx(Up,{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(kw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(Dd,{className:"w-full p-0",align:"start",children:[e.jsxs(N2,{children:[e.jsx(k2,{placeholder:"Search contacts..."}),e.jsxs(S2,{children:[e.jsx(C2,{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(cn,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(Rw,{children:x==null?void 0:x.map(D=>e.jsxs(h1,{value:`${D.first_name} ${D.last_name||""}`,onSelect:()=>{R.onChange(D.id),a(!1)},children:[e.jsx(ma,{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()||v.isPending,children:"Add Contact"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(_g,{control:S.control,name:"notes",render:({field:R})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Notes"}),e.jsx(Up,{children:e.jsx(Rs,{placeholder:"Any notes about this transaction...",...R})})]})}),e.jsx(_g,{control:S.control,name:"is_win",render:({field:R})=>e.jsxs(Bp,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx($p,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(Up,{children:e.jsx(jn,{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 Dot({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,v]=j.useState("all"),[y,b]=j.useState(!1),w=wWs(),S=N6e(),{data:A}=OB(),{data:E}=Uw(),I=RK(),P=O=>{const{id:U,created_at:W,updated_at:V,lead_source:G,client_type:Z,contact:X,...ae}=O;S.mutate(ae)},R=()=>{o&&(w.mutate(o),c(null))},D=s.filter(O=>{var X,ae,le,re;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()))||((re=(le=O.contact)==null?void 0:le.last_name)==null?void 0:re.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,Z=!y||O.is_win;return U&&W&&V&&G&&Z});return n?e.jsx(je,{children:e.jsx(Le,{className:"p-6 space-y-4",children:[1,2,3].map(O=>e.jsx(xn,{className:"h-16 w-full"},O))})}):e.jsxs(e.Fragment,{children:[e.jsxs(je,{children:[e.jsx(St,{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(Et,{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"}),A==null?void 0:A.map(O=>e.jsx(Ge,{value:O.id,children:O.name},O.id))]})]}),e.jsxs($,{variant:y?"default":"outline",size:"sm",onClick:()=>b(!y),children:[e.jsx(Im,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Le,{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(je,{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(Im,{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($e,{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: "}),dgt(O.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),Xm(O.sale_price)]}),t&&O.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),Xm(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(bp,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>P(O),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(O.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})]},O.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:D.map(O=>{var U;return e.jsxs(An,{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(Im,{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($e,{variant:O.transaction_type==="buyer"?"default":"secondary",children:O.transaction_type})}),e.jsx(wt,{children:dgt(O.close_date)}),e.jsx(wt,{children:Xm(O.sale_price)}),t&&e.jsx(wt,{children:O.commission_amount?Xm(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(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Cu,{align:"end",children:[e.jsxs(ja,{onClick:()=>l(O),children:[e.jsx(bp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ja,{onClick:()=>P(O),children:[e.jsx(Za,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(ja,{onClick:()=>c(O.id),className:"text-destructive",children:[e.jsx(qn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},O.id)})})]})})})]}),e.jsx(frs,{open:!!i,onOpenChange:O=>!O&&l(null),transaction:i||void 0}),e.jsx(fc,{open:!!o,onOpenChange:O=>!O&&c(null),children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Delete Transaction?"}),e.jsx(ic,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:R,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function prs({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),v=l>0?x/l:0,y=i/12*100,b=g>=y?"ahead":g>=y*.8?"on-track":"behind";return{percent:g,remaining:x,pace:v,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($e,{className:"bg-green-500 text-white",children:[e.jsx(Zl,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs($e,{variant:"secondary",children:[e.jsx(YN,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs($e,{variant:"destructive",children:[e.jsx(tC,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ph,{className:"h-5 w-5 text-primary"}),e.jsxs(Et,{children:[n," Goals Progress"]})]})}),e.jsx(Le,{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:[Xm(t.totalVolume,!0)," of ",Xm(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 ",Xm(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:[Xm(t.totalCommission,!0)," of ",Xm(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 ",Xm(u.pace,!0),"/month"]})]})]})})]})}const RZn={light:"",dark:".dark"},grs=j.createContext(null);function xrs(){const s=j.useContext(grs);if(!s)throw new Error("useChart must be used within a ");return s}const yrs=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(grs.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(DZn,{id:o,config:r}),e.jsx(j_,{children:n})]})})});yrs.displayName="Chart";const DZn=({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(RZn).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},vrs=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}=xrs(),x=j.useMemo(()=>{var A;if(a||!(t!=null&&t.length))return null;const[y]=t,b=`${m||y.dataKey||y.name||"value"}`,w=SXe(g,y,b),S=!m&&typeof l=="string"?((A=g[l])==null?void 0:A.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 v=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:[v?null:x,e.jsx("div",{className:"grid gap-1.5",children:t.map((y,b)=>{const w=`${h||y.name||y.dataKey||"value"}`,S=SXe(g,y,w),A=u||y.payload.fill||y.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&&(y==null?void 0:y.value)!==void 0&&y.name?d(y.value,y.name,y,b,y.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":v&&r==="dashed"}),style:{"--color-bg":A,"--color-border":A}}),e.jsxs("div",{className:Pt("flex flex-1 justify-between leading-none",v?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[v?x:null,e.jsx("span",{className:"text-muted-foreground",children:(S==null?void 0:S.label)||y.name})]}),y.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:y.value.toLocaleString()})]})]})},y.dataKey)})})]})});vrs.displayName="ChartTooltip";const FZn=j.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=xrs();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=SXe(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});FZn.displayName="ChartLegend";function SXe(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 Mue=["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 Fot({stats:s,year:t}){const n=s.transactionsByMonth.some(a=>a.count>0),r=s.leadSourceBreakdown.length>0;return!n&&!r?e.jsx(je,{children:e.jsx(Le,{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(je,{className:"overflow-hidden",children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Le,{className:"overflow-hidden",children:e.jsx(yrs,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(j_,{width:"100%",height:"100%",children:e.jsxs(PK,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(pT,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Cb,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(Ab,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(kg,{content:e.jsx(vrs,{})}),e.jsx(Dw,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),r&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Le,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(j_,{width:"100%",height:"100%",children:e.jsxs(yXt,{children:[e.jsx(m3,{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(KB,{fill:Mue[i%Mue.length]},`cell-${i}`))}),e.jsx(kg,{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:Mue[i%Mue.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function OZn(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=wtt(t,r,new Date);if($He(a))return Js(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if($He(r))return Js(r,"yyyy-MM-dd")}catch{}return null}const zZn=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function BZn({open:s,onOpenChange:t}){const[n,r]=j.useState([]),[a,i]=j.useState(!1),[l,o]=j.useState(0),{data:c}=OB(),{data:d}=Uw(),u=N6e(),h=()=>{const y=zZn.join(","),b=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),w=`${y} ${b}`,S=new Blob([w],{type:"text/csv"}),A=URL.createObjectURL(S),E=document.createElement("a");E.href=A,E.download="transaction-import-template.csv",E.click(),URL.revokeObjectURL(A)},m=y=>{const b=y.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,A)=>{var X,ae,le,re;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=(le=R("commission_amount"))==null?void 0:le.replace(/[$,]/g,""),W=(re=R("is_win"))==null?void 0:re.toLowerCase(),V=R("close_date"),G=OZn(V);let Z;return R("property_address")?["buyer","seller"].includes(D)?G?(!O||isNaN(Number(O)))&&(Z="Invalid sale price"):Z=`Invalid date format: "${V}" - use MM/DD/YYYY or YYYY-MM-DD`:Z='Transaction type must be "buyer" or "seller"':Z="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:Z}})},f=y=>{var S;const b=(S=y.target.files)==null?void 0:S[0];if(!b)return;const w=new FileReader;w.onload=A=>{var P;const E=(P=A.target)==null?void 0:P.result,I=m(E);r(I)},w.readAsText(b)},g=async()=>{const y=n.filter(S=>!S.error);if(y.length===0){ne.error("No valid transactions to import");return}i(!0),o(0);let b=0,w=0;for(let S=0;SP.name.toLowerCase()===A.lead_source_name.toLowerCase()),I=d==null?void 0:d.find(P=>P.name.toLowerCase()===A.client_type_name.toLowerCase());await u.mutateAsync({property_address:A.property_address,city:A.city||null,state:A.state||null,zip:A.zip||null,transaction_type:A.transaction_type,close_date:A.close_date,sale_price:A.sale_price,commission_amount:A.commission_amount,lead_source_id:(E==null?void 0:E.id)||null,client_type_id:(I==null?void 0:I.id)||null,contact_id:null,notes:A.notes||null,is_win:A.is_win}),b++}catch(E){w++,console.error("Failed to import transaction:",E)}o(Math.round((S+1)/y.length*100))}i(!1),b>0&&ne.success(`Imported ${b} transaction${b>1?"s":""}`),w>0&&ne.error(`Failed to import ${w} transaction${w>1?"s":""}`),r([]),t(!1)},x=n.filter(y=>!y.error).length,v=n.filter(y=>y.error).length;return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Import Transactions"}),e.jsx(Er,{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(ji,{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($e,{variant:"outline",children:[n.length," rows found"]}),x>0&&e.jsxs($e,{className:"bg-green-500 text-white",children:[e.jsx(ma,{className:"h-3 w-3 mr-1"}),x," valid"]}),v>0&&e.jsxs($e,{variant:"destructive",children:[e.jsx(vl,{className:"h-3 w-3 mr-1"}),v," errors"]})]}),e.jsx(go,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[n.slice(0,10).map((y,b)=>e.jsxs("div",{className:`p-2 rounded text-sm ${y.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:y.property_address||"(no address)"}),e.jsx($e,{variant:y.transaction_type==="buyer"?"default":"secondary",children:y.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[y.close_date," • $",y.sale_price.toLocaleString()]}),y.error&&e.jsx(Nse,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(kse,{className:"text-xs",children:y.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 $Zn=F2({transactions_goal:hee().min(0).optional(),volume_goal:hee().min(0).optional(),gci_goal:hee().min(0).optional()});function UZn({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=jWs(),{data:i}=k6e(),l=(i==null?void 0:i.show_commission)??!0,o=yLe({resolver:vLe($Zn),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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsxs($s,{children:[n," Goals"]}),e.jsx(Er,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(jLe,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(_g,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Transactions Goal"}),e.jsx(Up,{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(H4e,{children:"Total number of deals you want to close"}),e.jsx(m_,{})]})}),e.jsx(_g,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"Volume Goal ($)"}),e.jsx(Up,{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(H4e,{children:"Total sales volume you want to achieve"}),e.jsx(m_,{})]})}),l&&e.jsx(_g,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(Bp,{children:[e.jsx($p,{children:"GCI Goal ($)"}),e.jsx(Up,{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(H4e,{children:"Gross commission income target"}),e.jsx(m_,{})]})}),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 Oot({transactions:s,isLoading:t}){const n=j.useRef(null),r=j.useRef(null),a=j.useRef([]),i=j.useRef(null),{isAdmin:l}=_s(),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(0),[f,g]=j.useState(!1),x=s.filter(y=>y.latitude!=null&&y.longitude!=null),v=s.filter(y=>y.latitude==null||y.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||v.length===0||f)return;(async()=>{var w;g(!0);let b=0;for(const S of v){const A=[S.property_address,S.city,S.state,S.zip].filter(Boolean).join(", ");if(A)try{const I=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(A)}.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;_u.accessToken=o;const y=s.filter(S=>S.latitude!=null&&S.longitude!=null);let b=[-98.5795,39.8283],w=4;if(y.length>0){const S=y.reduce((E,I)=>E+I.longitude,0)/y.length,A=y.reduce((E,I)=>E+I.latitude,0)/y.length;b=[S,A],w=y.length===1?12:10}return r.current=new _u.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:w,center:b}),r.current.addControl(new _u.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 y=s.filter(w=>w.latitude!=null&&w.longitude!=null);if(y.forEach(w=>{var R;const S=w.transaction_type==="buyer",A=S?"#3B82F6":"#10B981",E=document.createElement("div");E.className="cursor-pointer",E.innerHTML=`
${S?'':''}
`;const I=new _u.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: ${kh(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 _u.Marker(E).setLngLat([w.longitude,w.latitude]).setPopup(I).addTo(r.current);a.current.push(P)}),y.length>1){const w=new _u.LngLatBounds;y.forEach(S=>w.extend([S.longitude,S.latitude])),r.current.fitBounds(w,{padding:60,maxZoom:13})}else y.length===1&&r.current.flyTo({center:[y[0].longitude,y[0].latitude],zoom:12})},[s,o,f]),d||t?e.jsx(je,{children:e.jsx(Le,{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(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(ui,{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(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(vl,{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 brs=()=>{const{data:s}=Ow();return st({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"})},qZn=s=>{const{data:t}=Ow(),{data:n}=brs();return st({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 VZn(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 HZn(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function GZn({year:s}){var m;const{data:t,isLoading:n}=brs(),{data:r,isLoading:a}=qZn(s),i=Zn(),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=>VZn(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,v=r.reduce((D,O)=>D+Number(O.sale_price),0),y=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 A=Object.entries(S).sort((D,O)=>O[1]-D[1])[0],E={};r.forEach(D=>{const O=kh(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:v,avgPrice:x>0?v/x:0,totalGCI:y,topSource:A?{name:A[0],count:A[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(xn,{className:"h-24"},f))}),e.jsx(xn,{className:"h-64"})]}):!o||c.length===0?e.jsx(je,{className:"py-12",children:e.jsxs(Le,{className:"text-center space-y-2",children:[e.jsx(Yn,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yn,{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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(su,{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:Xm(o.totalVolume,!0)})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{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:Xm(o.avgPrice,!0)})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(su,{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:Xm(o.totalGCI,!0)})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Im,{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(je,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Le,{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:Xm(d.totalVolume,!0)})]})]})}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Member Performance"})}),e.jsx(Le,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:c.map((f,g)=>e.jsxs(An,{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(Ii,{src:f.member.avatar_url||void 0}),e.jsx(za,{className:"text-xs",children:HZn(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:Xm(f.totalVolume,!0)}),e.jsx(wt,{className:"text-right text-sm",children:Xm(f.averagePrice,!0)}),e.jsx(wt,{className:"text-right font-medium",children:Xm(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(Ta,{className:"h-4 w-4"})})})]},f.member.id))})]})})})]}),e.jsxs(pa,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"transactions",children:[e.jsx(E0,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(Xt,{value:"charts",children:[e.jsx(Gl,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(Xt,{value:"map",children:[e.jsx(ui,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Qt,{value:"transactions",children:e.jsx(Dot,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(Qt,{value:"charts",children:h&&e.jsx(Fot,{stats:h,year:s})}),e.jsx(Qt,{value:"map",children:e.jsx(Oot,{transactions:r||[],isLoading:a})})]})]})}const lAe=new Date().getFullYear(),u3t=Array.from({length:10},(s,t)=>lAe-t),Pue="all";function WZn(){var O;const[s,t]=j.useState(lAe),n=s===null?Pue:String(s),r=U=>t(U===Pue?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}=Ow(),x=(g==null?void 0:g.role)==="team_leader",{data:v,isLoading:y}=nnt(s??void 0),{yearStats:b,lifetimeStats:w,showCommission:S}=UUt(s??void 0),{data:A,isLoading:E}=$Ut(s??lAe),{data:I}=k6e(),P=NWs(),R=()=>{if(!v||v.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=v.map(ae=>{var le,re;return[ae.property_address,ae.city||"",ae.state||"",ae.zip||"",ae.transaction_type,ae.close_date,ae.sale_price,...S?[ae.commission_amount||""]:[],((le=ae.lead_source)==null?void 0:le.name)||"",((re=ae.client_type)==null?void 0:re.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(le=>`"${String(le).replace(/"/g,'""')}"`).join(",")).join(` `),G=new Blob([V],{type:"text/csv"}),Z=URL.createObjectURL(G),X=document.createElement("a");X.href=Z,X.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,X.click(),URL.revokeObjectURL(Z)},D=!v||v.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(Yn,{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:Pue,children:"All Years"}),u3t.map(U=>e.jsx(Ge,{value:String(U),children:U},U))]})]})]}),e.jsx(GZn,{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:Pue,children:"All Years"}),u3t.map(U=>e.jsx(Ge,{value:String(U),children:U},U))]})]}),e.jsx($,{variant:"outline",size:"icon",onClick:()=>h(!u),children:e.jsx(Nd,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-lg",children:"Settings"})}),e.jsx(Le,{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(jn,{checked:(I==null?void 0:I.show_commission)??!0,onCheckedChange:U=>P.mutate({show_commission:U})})]})})]}),D&&!y?e.jsx(je,{className:"py-12",children:e.jsxs(Le,{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(Gl,{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(cn,{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(ji,{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(cn,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs($,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(ph,{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(ji,{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(ji,{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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yn,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(su,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Xm(b.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Xm(w.totalVolume,!0)," lifetime"]})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{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:Xm(b.averagePrice,!0)})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Im,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(su,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Xm(b.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Xm(w.totalCommission,!0)," lifetime"]})]})}),S&&b.totalNetToAgent>0&&b.totalNetToAgent!==b.totalCommission&&e.jsx(je,{children:e.jsxs(Le,{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(su,{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:Xm(b.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Xm(w.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&A&&e.jsx(prs,{goals:A,stats:b,year:s,showCommission:S}),e.jsxs(pa,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"transactions",children:"Transactions"}),e.jsx(Xt,{value:"charts",children:"Charts"}),e.jsxs(Xt,{value:"map",children:[e.jsx(ui,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Qt,{value:"transactions",children:e.jsx(Dot,{transactions:v||[],showCommission:S,isLoading:y})}),e.jsx(Qt,{value:"charts",children:e.jsx(Fot,{stats:b,year:s??void 0})}),e.jsx(Qt,{value:"map",children:e.jsx(Oot,{transactions:v||[],isLoading:y})})]})]})]})]}),e.jsx(frs,{open:a,onOpenChange:i}),e.jsx(BZn,{open:l,onOpenChange:o}),e.jsx(UZn,{open:c,onOpenChange:d,year:s??lAe,existingGoals:A})]})}const KZn={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"},YZn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},ZZn={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function XZn({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,showActions:i}){var S,A;const{user:l}=_s(),{data:o}=T$t(s.id),c=E$t(),[d,u]=j.useState(!1),h=E=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(E),m=((S=s.photos)==null?void 0:S.find(E=>E.is_primary))||((A=s.photos)==null?void 0:A[0]),f=(l==null?void 0:l.id)===s.agent_id,g=s.listing_class==="commercial",x=s.commercial??null,v=s.lifecycle_stage==="pitch",y=g?[xE(x==null?void 0:x.building_sf)?`${xE(x==null?void 0:x.building_sf)} building`:null,xE(x==null?void 0:x.available_sf)?`${xE(x==null?void 0:x.available_sf)} available`:null,AEe(x==null?void 0:x.cap_rate)?`${AEe(x==null?void 0:x.cap_rate)} cap`:null,(x==null?void 0:x.price_per_sf)!=null?`${PN(x.price_per_sf,2)}/SF`:null,(x==null?void 0:x.units)!=null?`${x.units} units`:null].filter(Boolean).slice(0,3):[],b=async E=>{E.stopPropagation();try{const I=await c.mutateAsync(s.id);ne.success(I.saved?"Listing saved!":"Listing removed from saved")}catch{ne.error("Failed to save listing")}},w=E=>{if(E.stopPropagation(),l)u(!0);else{const I=`${s.listing_class==="commercial"?"https://commercial.relevelup.com":"https://listings.relevelup.com"}/${s.slug||s.id}`;navigator.clipboard.writeText(I),ne.success("Link copied to clipboard!")}};return e.jsxs(je,{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:[m?e.jsx("img",{src:m.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(w_,{className:"h-12 w-12"})}),e.jsxs("div",{className:"absolute top-2 left-2 flex flex-wrap gap-1",children:[e.jsx($e,{className:`${KZn[s.status]} text-white border-0`,children:g&&v?"Pitch":YZn[s.status]}),g&&e.jsx($e,{className:"border-0 bg-[#0b0f14]/90 text-white",children:x!=null&&x.deal_type?SL[x.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(ei,{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:b,children:e.jsx(Jo,{className:`h-4 w-4 ${o?"fill-pink-500 text-pink-500":""}`})}),e.jsx($,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:w,title:f?"Copy link":"Share & earn leads",children:f?e.jsx(Hd,{className:"h-4 w-4"}):e.jsx(wn,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(g6e,{open:d,onOpenChange:u,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`,isCommercial:s.listing_class==="commercial"}),e.jsxs(Le,{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:g?jG(x,s.price):h(s.price)}),s.open_to_referrals&&e.jsxs($e,{variant:"outline",className:"text-xs",children:[e.jsx(Yn,{className:"h-3 w-3 mr-1"}),"Referrals"]})]}),e.jsxs("div",{children:[g?e.jsx("p",{className:"font-medium truncate",children:sL(s,x)}):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(ui,{className:"h-3 w-3"}),g?$ae(s,x):`${s.city}, ${s.state}${s.neighborhood?` • ${s.neighborhood}`:""}`]})]}),e.jsx("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:g?y.map(E=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(w_,{className:"h-4 w-4"}),E]},E)):e.jsxs(e.Fragment,{children:[s.bedrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(n2,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(C0,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(w_,{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($e,{variant:"secondary",className:"text-xs",children:g?x!=null&&x.commercial_type?r6[x.commercial_type]:"Commercial":ZZn[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(Ta,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hd,{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]})]}),i&&(n||r||a)&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[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:E=>{E.stopPropagation(),a()},children:[e.jsx(qq,{className:"h-4 w-4"}),"Music Video"]}),n&&e.jsxs($,{variant:"outline",size:"sm",className:"flex-1",onClick:E=>{E.stopPropagation(),n()},children:[e.jsx(bp,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx($,{variant:"destructive",size:"sm",onClick:E=>{E.stopPropagation(),r()},children:e.jsx(qn,{className:"h-4 w-4"})})]})]})]})}const zot="lu_listing_selection_v1",xPe=24,yPe=new Set;function _rs(){try{return JSON.parse(sessionStorage.getItem(zot)||"{}")}catch{return{}}}function M$e(s){try{sessionStorage.setItem(zot,JSON.stringify(s))}catch{}yPe.forEach(t=>t())}let _A=_rs();function QZn(){_A=_rs(),yPe.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===zot&&QZn()});const gP={getSnapshot:()=>_A,subscribe(s){return yPe.add(s),()=>yPe.delete(s)},toggle(s){const t={..._A};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=xPe)return!1;t[s.mlsNumber]=s}return _A=t,M$e(t),!0},remove(s){const t={..._A};delete t[s],_A=t,M$e(t)},clear(){_A={},M$e({})},has(s){return!!_A[s]},all(){return Object.values(_A)}};function wrs(){const s=j.useSyncExternalStore(gP.subscribe,gP.getSnapshot,gP.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:gP.toggle,remove:gP.remove,clear:gP.clear}}const JZn=new Set(["office_exclusive","coming_soon","pre_market"]);function eXn(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=JZn.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 dX(s){const{has:t}=wrs(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(XZn,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),gP.toggle(eXn(s.listing))||ne.error(`You can select up to ${xPe} 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(ma,{className:"h-4 w-4"}):e.jsx(pn,{className:"h-4 w-4"})})]})}function tXn({open:s,onOpenChange:t,listings:n}){const{user:r}=_s(),{leadSite:a}=tg(),[i,l]=j.useState("grid"),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(new Set),[x,v]=j.useState(!1),[y,b]=j.useState(!1),{data:w}=eie(),[S,A]=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))),Z=G.length===1?` in ${G[0]}`:"";c(n.length===1?`New listing for you${Z}`:`${n.length} hand-picked listings${Z}`)}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}=st({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}=st({queryKey:["send-listings-suggestions",n.map(G=>G.mlsNumber).join(",")],queryFn:async()=>{const{data:G,error:Z}=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(Z)throw Z;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(Z=>`${Z.first_name??""} ${Z.last_name??""} ${Z.email} ${Z.city??""}`.toLowerCase().includes(G)):E},[E,h]),O=G=>{g(Z=>{const X=new Set(Z);return X.has(G)?X.delete(G):X.add(G),X})},U=()=>{g(G=>{const Z=new Set(G);return R.forEach(X=>Z.add(X.contact_id)),Z})},W=n.length>0&&n.every(G=>G.mlsNumber.startsWith("lx-")),V=async()=>{if(!W&&!(a!=null&&a.id)){ne.error("You need an active lead site to send listings.");return}if(!o.trim())return ne.error("Subject is required");if(f.size===0)return ne.error("Pick at least one recipient");if(!y&&w&&!w.hasVerifiedSes){A(!0);return}const G=E.filter(Z=>f.has(Z.id)).map(Z=>({contact_id:Z.id,email:Z.email,first_name:Z.first_name,last_name:Z.last_name}));v(!0);try{const{data:Z,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(!(Z!=null&&Z.success))throw new Error((Z==null?void 0:Z.error)||"Send failed");ne.success(`Sent ${Z.sent}/${G.length} via ${y?"Gmail":"Amazon SES"}${Z.failed?` · ${Z.failed} failed`:""}`),gP.clear(),g(new Set),t(!1)}catch(Z){ne.error((Z==null?void 0:Z.message)||"Failed to send")}finally{v(!1)}};return e.jsxs(Os,{open:s,onOpenChange:t,children:[e.jsxs(Fs,{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($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(Er,{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 Z;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:((Z=G.photos)==null?void 0:Z[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(Xf,{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(Hc,{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:y?"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(je,{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(wn,{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(go,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:R.slice(0,12).map(G=>{const Z=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:Z,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($e,{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(go,{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 Z=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:Z,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(mr,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Send to ",f.size," ",f.size===1?"contact":"contacts"]})})]})]}),e.jsx(b6e,{open:S,onOpenChange:A,hasPending:!!(w!=null&&w.hasPendingSes),pendingEmails:w==null?void 0:w.pendingEmails})]})}function sXn(){const{selected:s,count:t,remove:n,clear:r}=wrs(),[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>=xPe?"Max reached":`Pick up to ${xPe}`})]})]}),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(mr,{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(qn,{className:"h-4 w-4"})," Clear"]}),e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(Zr,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(tXn,{open:a,onOpenChange:i,listings:s})]})}const nXn=[{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"}],rXn=[{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 aXn({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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(Et,{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(mr,{className:"h-4 w-4"})})]})]}),e.jsxs(Le,{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"}),nXn.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"}),rXn.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(SL).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(r6).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(jn,{checked:s.openToReferrals||!1,onCheckedChange:o=>t({...s,openToReferrals:o||void 0})})]})]})]})}function iXn({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(EE,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(Im,{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($e,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Kl,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(Le,{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(Hd,{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(EE,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Community Leaderboard"})}),e.jsx(Le,{children:e.jsxs(pa,{defaultValue:"sharers",children:[e.jsxs(ga,{className:"w-full",children:[e.jsxs(Xt,{value:"sharers",className:"flex-1",children:[e.jsx(Hd,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(Xt,{value:"listers",className:"flex-1",children:[e.jsx(va,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(Qt,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(Qt,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const h3t={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},m3t={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 oXn(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function lXn({listings:s,isLoading:t}){const n=Zn(),r=j.useRef(null),a=j.useRef(null),i=j.useRef([]),{isAdmin:l}=_s(),[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:v}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();v!=null&&v.value&&c(v.value)}catch(v){console.error("Error fetching mapbox token:",v)}u(!1)})()},[]),j.useEffect(()=>{if(!o||g.length===0||h)return;(async()=>{var v;m(!0);for(const y of g){const b=[y.property_address,y.city,y.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((v=S.features)!=null&&v[0]){const[A,E]=S.features[0].center;await q.from("listings").update({latitude:E,longitude:A}).eq("id",y.id),y.latitude=E,y.longitude=A}}catch(w){console.error("Geocode error:",w)}}m(!1)})()},[o,s]),j.useEffect(()=>{if(!r.current||!o||a.current)return;_u.accessToken=o;const x=s.filter(b=>b.latitude!=null&&b.longitude!=null);let v=[-98.5795,39.8283],y=4;if(x.length>0){const b=x.reduce((S,A)=>S+A.longitude,0)/x.length,w=x.reduce((S,A)=>S+A.latitude,0)/x.length;v=[b,w],y=x.length===1?12:10}return a.current=new _u.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:y,center:v}),a.current.addControl(new _u.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(v=>v.remove()),i.current=[];const x=s.filter(v=>v.latitude!=null&&v.longitude!=null);if(x.forEach(v=>{var E,I,P;const y=h3t[v.status]||"#10B981",b=((E=v.photos)==null?void 0:E.find(R=>R.is_primary))||((I=v.photos)==null?void 0:I[0]),w=document.createElement("div");w.className="cursor-pointer",w.innerHTML=`
`;const S=new _u.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${b!=null&&b.photo_url?``:""}
${oXn(v.price)}
${v.property_address||""}
${v.city}, ${v.state}
${m3t[v.status]||v.status} ${v.bedrooms?`${v.bedrooms} bed`:""} ${v.bathrooms?`${v.bathrooms} bath`:""}
${(P=v.agent)!=null&&P.name?`
Listed by ${v.agent.name}
`:""}
Click to view details →
`),A=new _u.Marker(w).setLngLat([v.longitude,v.latitude]).setPopup(S).addTo(a.current);i.current.push(A)}),x.length>1){const v=new _u.LngLatBounds;x.forEach(y=>v.extend([y.longitude,y.latitude])),a.current.fitBounds(v,{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(je,{children:e.jsx(Le,{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(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(ui,{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(h3t).map(([x,v])=>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:v}}),e.jsx("span",{className:"text-xs",children:m3t[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(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(vl,{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 CXe="homereel_mv_prefill",AXe="homereel_mv_badge_default";function jrs(s){try{sessionStorage.setItem(CXe,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(AXe,JSON.stringify(s.badge))}catch{}}function $Sr(){try{const s=sessionStorage.getItem(CXe);return s?(sessionStorage.removeItem(CXe),JSON.parse(s)):null}catch{return null}}function USr(){try{const s=sessionStorage.getItem(AXe);return s?(sessionStorage.removeItem(AXe),JSON.parse(s)):null}catch{return null}}function Nrs(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 cXn(){var G,Z,X,ae,le,re,te,J;const s=Zn(),{brokerageId:t}=_s(),{data:n,isLoading:r}=b$t(),[a,i]=j.useState("feed"),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState("all"),[m,f]=j.useState({sortBy:"newest"}),{data:g,isLoading:x}=_$t({...m,listingClass:u==="all"?void 0:u,city:c||m.city}),{data:v,isLoading:y}=oqs(),{data:b,isLoading:w}=Bst(),{data:S,isLoading:A}=uqs(),{data:E,isLoading:I}=fqs(),{data:P}=mqs(),R=N$t(),D=m.commercial,O=(g??[]).filter(ce=>{if(!D||ce.listing_class!=="commercial")return!D||Object.values(D).every(fe=>fe===void 0)||ce.listing_class!=="commercial";const ve=ce.commercial??{};return!(D.dealType&&ve.deal_type!==D.dealType||D.commercialType&&ve.commercial_type!==D.commercialType||D.minBuildingSf&&Number(ve.building_sf??0)ce.lifecycle_stage==="pitch"),W=ce=>s(ce.listing_class==="commercial"?`/mission-control/listings/${ce.id}/commercial`:`/mission-control/listings/${ce.id}`),V=async ce=>{if(await mo("Are you sure you want to delete this listing? This action cannot be undone."))try{await R.mutateAsync(ce),ne.success("Listing deleted successfully")}catch{ne.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(cn,{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(je,{children:e.jsxs(Le,{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:(g==null?void 0:g.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(je,{children:e.jsxs(Le,{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:(v==null?void 0:v.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(zI,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(b==null?void 0:b.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(Yn,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((G=S==null?void 0:S.sent)==null?void 0:G.length)||0)+(((Z=S==null?void 0:S.received)==null?void 0:Z.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(pa,{value:a,onValueChange:i,children:[e.jsxs(ga,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(Xt,{value:"feed",children:"Community Feed"}),t&&e.jsx(Xt,{value:"brokerage",children:"Brokerage"}),e.jsx(Xt,{value:"my-listings",children:"My Listings"}),U.length>0&&e.jsxs(Xt,{value:"pitches",children:["Pitches (",U.length,")"]}),e.jsx(Xt,{value:"saved",children:"Saved"}),e.jsx(Xt,{value:"referrals",children:"Referrals"}),e.jsx(Xt,{value:"map",children:"Map"}),e.jsx(Xt,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(Qt,{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(ce=>e.jsx("button",{type:"button",onClick:()=>h(ce),className:`rounded-md px-4 py-1.5 text-sm font-medium capitalize transition ${u===ce?"bg-background shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:ce==="all"?"All listings":ce},ce))}),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:c,onChange:ce=>d(ce.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:m.sortBy,onValueChange:ce=>f({...m,sortBy:ce}),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(Sw,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(aXn,{filters:m,onFiltersChange:f,onClose:()=>o(!1),showCommercial:u!=="residential"}),x?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((ce,ve)=>e.jsxs(je,{children:[e.jsx(xn,{className:"h-48 w-full"}),e.jsxs(Le,{className:"p-4 space-y-2",children:[e.jsx(xn,{className:"h-5 w-3/4"}),e.jsx(xn,{className:"h-4 w-1/2"}),e.jsx(xn,{className:"h-4 w-1/4"})]})]},ve))}):(g==null?void 0:g.length)===0?e.jsx(je,{children:e.jsxs(Le,{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(cn,{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:O.map(ce=>e.jsx(dX,{listing:ce,onClick:()=>W(ce)},ce.id))})]}),e.jsx(Qt,{value:"my-listings",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((ce,ve)=>e.jsxs(je,{children:[e.jsx(xn,{className:"h-48 w-full"}),e.jsxs(Le,{className:"p-4 space-y-2",children:[e.jsx(xn,{className:"h-5 w-3/4"}),e.jsx(xn,{className:"h-4 w-1/2"})]})]},ve))}):(b==null?void 0:b.length)===0?e.jsx(je,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(zI,{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(cn,{className:"h-4 w-4 mr-2"}),"Add Your First Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b==null?void 0:b.map(ce=>e.jsx(dX,{listing:ce,showActions:!0,onClick:()=>W(ce),onEdit:()=>s(ce.listing_class==="commercial"?`/mission-control/listings/${ce.id}/commercial`:`/mission-control/listings/${ce.id}/edit`),onDelete:()=>V(ce.id),onCreateMusicVideo:()=>{const ve=(ce.photos??[]).slice().sort((fe,ue)=>(ue.is_primary?1:0)-(fe.is_primary?1:0)||(fe.sort_order??0)-(ue.sort_order??0)).map(fe=>fe.photo_url).filter(Boolean);if(ve.length===0){ne.error("Add photos to this listing first.");return}jrs({photos:ve,details:{address:ce.property_address||`${ce.city??""} ${ce.state??""}`.trim(),beds:ce.bedrooms?String(ce.bedrooms):"",baths:ce.bathrooms?String(ce.bathrooms):"",sqft:ce.square_footage?String(ce.square_footage):"",price:ce.price?String(ce.price):"",highlights:ce.description||""},sourceLabel:"My Listings",badge:Nrs(ce.status,ce.price)}),s("/admin/beta/homereel?tab=music-video")}},ce.id))})}),e.jsxs(Qt,{value:"pitches",className:"space-y-4",children:[e.jsx(je,{className:"border-dashed",children:e.jsx(Le,{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:U.map(ce=>e.jsx(dX,{listing:ce,showActions:!0,onClick:()=>s(`/mission-control/listings/${ce.id}/commercial`),onEdit:()=>s(`/mission-control/listings/${ce.id}/commercial`),onDelete:()=>V(ce.id)},ce.id))})]}),e.jsx(Qt,{value:"saved",className:"space-y-4",children:y?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ce,ve)=>e.jsxs(je,{children:[e.jsx(xn,{className:"h-48 w-full"}),e.jsxs(Le,{className:"p-4 space-y-2",children:[e.jsx(xn,{className:"h-5 w-3/4"}),e.jsx(xn,{className:"h-4 w-1/2"})]})]},ve))}):(v==null?void 0:v.length)===0?e.jsx(je,{children:e.jsxs(Le,{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:v==null?void 0:v.map(ce=>e.jsx(dX,{listing:ce.listing,onClick:()=>W(ce.listing)},ce.id))})}),e.jsx(Qt,{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(Hd,{className:"h-4 w-4"}),"Referrals Sent (",((X=S==null?void 0:S.sent)==null?void 0:X.length)||0,")"]}),((ae=S==null?void 0:S.sent)==null?void 0:ae.length)===0?e.jsx(je,{children:e.jsx(Le,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(le=S==null?void 0:S.sent)==null?void 0:le.map(ce=>{var ve,fe;return e.jsx(je,{children:e.jsx(Le,{className:"p-4",children:e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ce.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((ve=ce.listing)==null?void 0:ve.property_address)||((fe=ce.listing)==null?void 0:fe.city)})]}),e.jsx($e,{variant:ce.status==="closed"?"default":"secondary",children:ce.status.replace("_"," ")})]})})},ce.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Referrals Received (",((re=S==null?void 0:S.received)==null?void 0:re.length)||0,")"]}),((te=S==null?void 0:S.received)==null?void 0:te.length)===0?e.jsx(je,{children:e.jsx(Le,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(J=S==null?void 0:S.received)==null?void 0:J.map(ce=>{var ve;return e.jsx(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ce.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(ve=ce.sender)==null?void 0:ve.name]})]}),e.jsx($e,{variant:ce.status==="closed"?"default":"secondary",children:ce.status.replace("_"," ")})]}),e.jsx($,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${ce.listing_id}`),children:"View Listing"})]})},ce.id)})})]})]})}),t&&e.jsx(Qt,{value:"brokerage",className:"space-y-4",children:I?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ce,ve)=>e.jsxs(je,{children:[e.jsx(xn,{className:"h-48 w-full"}),e.jsxs(Le,{className:"p-4 space-y-2",children:[e.jsx(xn,{className:"h-5 w-3/4"}),e.jsx(xn,{className:"h-4 w-1/2"})]})]},ve))}):(E==null?void 0:E.length)===0?e.jsx(je,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(zI,{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(cn,{className:"h-4 w-4 mr-2"}),"Add a Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:E==null?void 0:E.map(ce=>e.jsx(dX,{listing:ce,onClick:()=>W(ce)},ce.id))})}),e.jsx(Qt,{value:"map",children:e.jsx(lXn,{listings:g||[],isLoading:x})}),e.jsx(Qt,{value:"leaderboard",children:e.jsx(iXn,{leaderboard:P})})]})]}),e.jsx(sXn,{})]}):e.jsx(Vs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(je,{children:e.jsxs(Le,{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 dXn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function uXn({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=r6e(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 $st(i);window.open(l,"_blank")}catch{ne.error("Failed to open document")}};return e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"text-lg flex items-center gap-2",children:[e.jsx(Qr,{className:"h-5 w-5"}),"Documents & Disclosures (",r.length,")"]})}),e.jsx(Le,{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(Qr,{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:dXn(i.file_size)})]}),e.jsx(ji,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}function gw(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 Wie(){const s=Sa();return st({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 krs(){const s=Sa(),t=Zt();return mt({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 QK(){const s=Sa();return st({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 Srs(){const s=Sa(),t=Zt();return mt({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 Crs(){const s=Zt();return mt({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 hXn(){const s=Zt();return mt({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 mXn(){const s=Zt();return mt({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 fXn(s){return st({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 pXn(){const s=Zt();return mt({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 gXn(s){return st({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 xXn(){const s=Zt();return mt({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 yXn(){const s=Zt();return mt({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 vXn(){const s=Sa();return st({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+(gw(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+(gw(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+(gw(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(gw(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(gw(c)||0)*d},0)}},enabled:!!s})}function bXn(s){const t=Sa();return st({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 _Xn(){const s=Zt();return mt({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 wXn(){const s=Zt();return mt({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 jXn({listing:s}){const t=Zn(),[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l,isLoading:o}=bXn(s.id),{data:c,isLoading:d}=Wie(),{data:u,isLoading:h}=QK(),m=krs(),f=_Xn(),g=wXn(),x=Srs(),v=(u==null?void 0:u.filter(A=>!A.listing_id))||[],y=A=>{if(!(c!=null&&c.length))return null;switch(A){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 A=y(s.status);await x.mutateAsync({deal_name:s.property_address?`${s.property_address}, ${s.city}`:`${s.city}, ${s.state}`,deal_type:"seller",stage_id:(A==null?void 0:A.id)||null,listing_id:s.id,property_address:s.property_address,city:s.city,state:s.state,expected_price:s.price,expected_commission:s.price*.03,commission_percentage:3,priority:"medium",probability:50}),ne.success("Deal created and linked to listing!")}catch(A){console.error("Failed to create deal:",A),ne.error("Failed to create deal")}finally{i(!1)}},w=async()=>{if(!n){ne.error("Please select a deal");return}try{await f.mutateAsync({dealId:n,listingId:s.id}),ne.success("Listing linked to deal!"),r("")}catch{ne.error("Failed to link listing")}},S=async()=>{if(l)try{await g.mutateAsync({dealId:l.id,listingId:s.id}),ne.success("Listing unlinked from deal")}catch{ne.error("Failed to unlink listing")}};return o||d?e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(i2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Le,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(je,{className:"border-primary/20 bg-primary/5",children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(nu,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Le,{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($e,{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(Qa,{className:"h-3 w-3 ml-1"})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:S,disabled:g.isPending,children:g.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(e7,{className:"h-4 w-4"})})]})]})]}):e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(i2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Le,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),v.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:v.map(A=>e.jsx(Ge,{value:A.id,children:A.deal_name},A.id))})]}),e.jsx($,{variant:"secondary",size:"icon",onClick:w,disabled:!n||f.isPending,children:f.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(nu,{className:"h-4 w-4"})})]})]})]})]})}const NXn={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"},kXn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},f3t={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function SXn(){var le,re,te,J,ce,ve,fe,ue,be;const{listingId:s}=Wi(),t=Zn(),{user:n}=_s(),{data:r,isLoading:a}=Kae(s||""),{data:i}=T$t(s||""),{data:l}=cqs(s||""),o=E$t(),c=lqs(),d=dqs(),u=N$t(),h=hqs(),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[v,y]=j.useState(!1),[b,w]=j.useState(!1),[S,A]=j.useState(!1),[E,I]=j.useState(!1),[P,R]=j.useState(null),[D,O]=j.useState({buyerName:"",buyerType:"",notes:""}),U=(n==null?void 0:n.id)===(r==null?void 0:r.agent_id),W=Ee=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ee),V=async Ee=>{const ke=`https://listings.relevelup.com/${(r==null?void 0:r.slug)||(r==null?void 0:r.id)}`,Ie=`Check out this listing: ${(r==null?void 0:r.property_address)||(r==null?void 0:r.city)}`;d.mutate({listingId:r.id,shareType:Ee});try{switch(Ee){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(ke)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(ke),ne.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${Ie} ${ke}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(Ie)}&body=${encodeURIComponent(`Check out this listing: ${ke}`)}`);break}}catch(Fe){console.error("Share error:",Fe),ne.error("Failed to share")}},G=async()=>{try{await u.mutateAsync(r.id),ne.success("Listing deleted"),t("/mission-control/listings")}catch{ne.error("Failed to delete listing")}},Z=async()=>{if(!D.buyerName.trim()){ne.error("Please enter buyer name");return}try{await h.mutateAsync({listingId:r.id,listingAgentId:r.agent_id,buyerName:D.buyerName,buyerType:D.buyerType||void 0,notes:D.notes||void 0}),ne.success("Referral sent successfully!"),x(!1),O({buyerName:"",buyerType:"",notes:""})}catch{ne.error("Failed to send referral")}},X=Ee=>{var Ae,Ce;const ke=(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`,Ie=W((r==null?void 0:r.price)||0),Fe=r!=null&&r.bedrooms?`${r.bedrooms}BD`:"",Ne=r!=null&&r.bathrooms?`${r.bathrooms}BA`:"",Be=r!=null&&r.square_footage?`${r.square_footage.toLocaleString()}SF`:"",Se=[Fe,Ne,Be].filter(Boolean).join(" | ");switch(Ee){case"just_listed":return`🏡 JUST LISTED! ${ke} ${Ie} ${Se} ${(r==null?void 0:r.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Ae=r==null?void 0:r.city)==null?void 0:Ae.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${ke} Now ${Ie}! ${Se} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${f3t[(r==null?void 0:r.property_type)||"single_family"].toLowerCase()} in ${r==null?void 0:r.city}? 👀 I've got just the one for you! ${Se} DM me for details! 📩 #ComingSoon #RealEstate #${(Ce=r==null?void 0:r.city)==null?void 0:Ce.replace(/\s/g,"")}`;default:return""}};if(r&&r.listing_class==="commercial")return e.jsx(eu,{to:`/mission-control/listings/${r.id}/commercial`,replace:!0});if(a)return e.jsx(Vs,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-10 w-32"}),e.jsx(xn,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(xn,{className:"h-48"}),e.jsx(xn,{className:"h-48"}),e.jsx(xn,{className:"h-48"})]})]})});if(!r)return e.jsx(Vs,{title:"Listing Not Found",description:"",children:e.jsx(je,{children:e.jsxs(Le,{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 ae=((le=r.photos)==null?void 0:le.find(Ee=>Ee.is_primary))||((re=r.photos)==null?void 0:re[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(Va,{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:()=>ae&&R(ae.photo_url),children:ae?e.jsx("img",{src:ae.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:(te=r.photos)==null?void 0:te.slice(1,5).map((Ee,ke)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>R(Ee.photo_url),children:e.jsx("img",{src:Ee.photo_url,alt:`Photo ${ke+2}`,className:"w-full h-full object-cover"})},Ee.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(je,{children:e.jsxs(Le,{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($e,{className:`${NXn[r.status]} text-white border-0`,children:kXn[r.status]}),r.is_featured&&e.jsxs($e,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(ei,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),r.open_to_referrals&&e.jsxs($e,{variant:"outline",children:[e.jsx(Yn,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:W(r.price)}),r.property_address&&e.jsx("p",{className:"text-xl font-medium",children:r.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(ui,{className:"h-4 w-4"}),r.city,", ",r.state,r.neighborhood&&` • ${r.neighborhood}`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>o.mutate(r.id),children:e.jsx(Jo,{className:`h-4 w-4 ${i?"fill-pink-500 text-pink-500":""}`})}),e.jsx($,{variant:"outline",size:"icon",onClick:()=>c.mutate(r.id),children:l?e.jsx(KS,{className:"h-4 w-4"}):e.jsx(zy,{className:"h-4 w-4"})}),!U&&e.jsxs($,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>y(!0),children:[e.jsx(wn,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsxs($,{variant:"outline",children:[e.jsx(Hd,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(Cu,{children:[e.jsxs(ja,{onClick:()=>V("copy"),children:[e.jsx(Za,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(ja,{onClick:()=>V("facebook"),children:[e.jsx(Zp,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(ja,{onClick:()=>V("text"),children:[e.jsx(no,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(ja,{onClick:()=>V("email"),children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),U&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",onClick:()=>{const Ee=(r.photos??[]).slice().sort((ke,Ie)=>(Ie.is_primary?1:0)-(ke.is_primary?1:0)||(ke.sort_order??0)-(Ie.sort_order??0)).map(ke=>ke.photo_url).filter(Boolean);if(Ee.length===0){ne.error("Add photos to this listing first.");return}jrs({photos:Ee,details:{address:r.property_address||`${r.city??""} ${r.state??""}`.trim(),beds:r.bedrooms?String(r.bedrooms):"",baths:r.bathrooms?String(r.bathrooms):"",sqft:r.square_footage?String(r.square_footage):"",price:r.price?String(r.price):"",highlights:r.description||""},sourceLabel:"Listing Exchange",badge:Nrs(r.status,r.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(qq,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs($,{variant:"outline",onClick:()=>A(!0),className:"gap-2 border-amber-500/60 text-amber-600 hover:bg-amber-50",children:[e.jsx(wn,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs($,{variant:"outline",onClick:()=>I(!0),className:"gap-2",children:[e.jsx(Xp,{className:"h-4 w-4"}),"QR Code"]}),e.jsxs($,{variant:"outline",onClick:()=>w(!0),className:"gap-2",children:[e.jsx(pn,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs($,{onClick:()=>t(`/mission-control/listings/${r.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(wn,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs($,{variant:"outline",onClick:()=>t(`/mission-control/listings/${r.id}/edit`),children:[e.jsx(bp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx($,{variant:"destructive",size:"icon",onClick:()=>f(!0),children:e.jsx(qn,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[r.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(n2,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.bedrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Beds"})]}),r.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(C0,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.bathrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Baths"})]}),r.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(w_,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.square_footage.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sq Ft"})]}),r.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(Ea,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.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($e,{variant:"secondary",children:[e.jsx(wi,{className:"h-3 w-3 mr-1"}),f3t[r.property_type]]}),r.lot_size&&e.jsxs($e,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx($e,{variant:"secondary",children:"HOA"})]}),r.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:r.description})]}),r.agent_notes&&r.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:r.agent_notes})]}),r.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:[r.co_agent_photo_url?e.jsx("img",{src:r.co_agent_photo_url,alt:r.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:r.co_agent_name.charAt(0)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:r.co_agent_name}),r.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:r.co_agent_brokerage}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:[r.co_agent_email,r.co_agent_phone].filter(Boolean).join(" · ")})]})]})]}),r.mls_link&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:r.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ir,{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(Ta,{className:"h-4 w-4"}),r.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hd,{className:"h-4 w-4"}),r.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jo,{className:"h-4 w-4"}),r.save_count," saves"]})]})]})}),r.allow_sharing&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Share Content"})}),e.jsx(Le,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(Ee=>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:[Ee.replace("_"," ")," Caption"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(X(Ee)),ne.success("Caption copied!")},children:e.jsx(Za,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:X(Ee)})]},Ee))})]}),e.jsx(uXn,{listingId:r.id,ownerOnly:U})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(Le,{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:((ce=(J=r.agent)==null?void 0:J.name)==null?void 0:ce.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((ve=r.agent)==null?void 0:ve.name)||"Unknown"}),((ue=(fe=r.agent)==null?void 0:fe.brokerage)==null?void 0:ue.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),!U&&e.jsx("div",{className:"space-y-2",children:((be=r.agent)==null?void 0:be.email)&&e.jsx($,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${r.agent.email}`,children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),U&&e.jsx(jXn,{listing:r}),!U&&r.open_to_referrals&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"text-lg flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(Le,{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:()=>x(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(Os,{open:!!P,onOpenChange:()=>R(null),children:e.jsx(Fs,{className:"max-w-4xl",children:e.jsx("img",{src:P||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(Os,{open:m,onOpenChange:f,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Delete Listing"}),e.jsx(Er,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:G,disabled:u.isPending,children:u.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(Os,{open:g,onOpenChange:x,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Send Buyer Referral"}),e.jsx(Er,{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:D.buyerName,onChange:Ee=>O({...D,buyerName:Ee.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:D.buyerType,onValueChange:Ee=>O({...D,buyerType:Ee}),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:D.notes,onChange:Ee=>O({...D,notes:Ee.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx($,{onClick:Z,disabled:h.isPending,children:h.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(pUt,{open:E,onOpenChange:I,url:`https://listings.relevelup.com/${r.slug||r.id}`,title:r.property_address||`${r.city}, ${r.state}`,fileBase:r.slug||r.property_address||r.city}),e.jsx(g6e,{open:v,onOpenChange:y,listingId:(r==null?void 0:r.id)||"",listingSlug:(r==null?void 0:r.slug)||null,listingTitle:(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`}),r&&e.jsx(CUt,{open:b,onOpenChange:w,listing:r}),e.jsx(Zst,{listingId:(r==null?void 0:r.id)||null,open:S,onOpenChange:A,initialStatus:WEe(r==null?void 0:r.status)})]})}function CXn({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}`),ne.success(`Imported: ${b.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},v=b=>b?`$${b.toLocaleString()}`:"",y=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(je,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(St,{className:"pb-3",children:[e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(ji,{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(Le,{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(Ct,{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(mr,{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(ui,{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:v(b.price)}),b.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(n2,{className:"h-3 w-3"})," ",b.bedrooms]}),b.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(C0,{className:"h-3 w-3"})," ",b.bathrooms]}),b.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(M4,{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($e,{variant:"outline",className:"text-[10px]",children:y(b.propertyType)}),b.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[b.photos.length," photos"]})]})]},b.mlsNumber))})]})})]})}function AXn({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=Zn(),{user:a}=_s(),[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),v(R))},v=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)}},y=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),ne.error("Failed to load videos")}finally{u(!1)}}},b=async R=>{var D;try{const O=R.map(Z=>Z.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 Z of R)(D=V[Z.bunny_video_id])!=null&&D.thumbnailUrl&&(G[Z.id]={thumbnailUrl:V[Z.bunny_video_id].thumbnailUrl});g(Z=>({...Z,...G}))}catch(O){console.warn("Failed to bulk-fetch signed URLs",O)}},w=()=>{l(!0),y()},S=R=>{t(R.id),m(R),l(!1),ne.success("Video selected")},A=()=>{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(je,{className:"overflow-hidden",children:e.jsx(Le,{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(fa,{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(Ou,{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:A,className:"text-destructive hover:text-destructive",children:e.jsx(mr,{className:"h-4 w-4"})})]})]})})}):e.jsx(je,{className:"border-dashed",children:e.jsx(Le,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(fa,{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(l2,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs($,{type:"button",variant:"outline",onClick:E,className:"gap-2",children:[e.jsx(jx,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(Us,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(l2,{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(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(fa,{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(jx,{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(fa,{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(Ou,{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(jx,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const EXn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function TXn({listingId:s}){const t=j.useRef(null),{data:n=[],isLoading:r}=r6e(s),a=M$t(),i=P$t(),l=vqs(),o=async d=>{if(!(!d||d.length===0)){for(const u of Array.from(d)){if(u.size>25*1024*1024){ne.error(`${u.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:u})}catch(h){ne.error(`Failed to upload ${u.name}: ${h.message}`)}}t.current&&(t.current.value=""),ne.success("Documents uploaded")}},c=async d=>{try{const u=await $st(d);window.open(u,"_blank")}catch{ne.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(Ct,{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(je,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Qr,{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:EXn(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(Ta,{className:"h-3 w-3"}):e.jsx(Nx,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(jn,{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(ji,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:async()=>{await mo(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(mr,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const MXn=[{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"}],PXn=[{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 IXn({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=p6e({id:s}),u={transform:TL.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(zg,{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(mr,{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(ei,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function LXn({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=i6e(CG(lK,{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],[v]=g.splice(m,1),[y]=x.splice(m,1);g.splice(f,0,v),x.splice(f,0,y),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(h6e,{sensors:l,collisionDetection:o6e,onDragEnd:c,children:e.jsx(f6e,{items:o,strategy:Qae,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(IXn,{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(Ct,{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 p3t(){const{listingId:s}=Wi(),[t]=Nc(),n=t.get("brokerage"),r=Zn(),{user:a}=_s(),{hasLeadSite:i}=tg(),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}=Kae(l?s:""),g=w$t(),x=iqs(),v=j$t(),y=k$t(),b=S$t(),w=C$t(),S=A$t(),{data:A=[]}=st({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=[]}=Eae(),R=P.filter(Ae=>Ae.role==="team_leader").map(Ae=>Ae.teamId),D=P.map(Ae=>Ae.teamId),O=R.length>0,{data:U=[]}=st({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(ht=>ht.user_id)));if(!qe.length)return[];const{data:ze,error:Ve}=await q.from("profiles").select("id, name, email, phone, avatar_url, brokerage_name").in("id",qe).order("name");if(Ve)throw Ve;return ze||[]},enabled:D.length>0}),[W,V]=j.useState(""),G=W||(a==null?void 0:a.id)||"",Z=O&&!o&&U.length>1,[X,ae]=j.useState(!1),[le,re]=j.useState([]),[te,J]=j.useState([]),[ce,ve]=j.useState(!1),fe=async Ae=>{if(Ae.size>5*1024*1024){ne.error("Image must be under 5MB");return}ve(!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:Ve}=q.storage.from("listing-photos").getPublicUrl(qe);be(ht=>({...ht,co_agent_photo_url:Ve.publicUrl})),ne.success("Headshot uploaded")}catch(Ce){ne.error((Ce==null?void 0:Ce.message)||"Failed to upload headshot")}finally{ve(!1)}},[ue,be]=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,Ve;m&&l&&(be({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:((Ve=m.year_built)==null?void 0:Ve.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 Ve,ht;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=((Ve=Object.entries(Ce).find(([Qe])=>qe.includes(Qe)))==null?void 0:Ve[1])||"other";be(Qe=>({...Qe,property_address:Ae.address||Qe.property_address,city:Ae.city||Qe.city,state:Ae.state||Qe.state,price:Ae.price?String(Ae.price):Qe.price,property_type:ze,bedrooms:Ae.bedrooms?String(Ae.bedrooms):Qe.bedrooms,bathrooms:Ae.bathrooms?String(Ae.bathrooms):Qe.bathrooms,square_footage:Ae.sqft?String(Ae.sqft):Qe.square_footage,lot_size:Ae.lotSize?String(Ae.lotSize):Qe.lot_size,year_built:Ae.yearBuilt?String(Ae.yearBuilt):Qe.year_built,description:Ae.description||Qe.description})),((ht=Ae.photos)==null?void 0:ht.length)>0&&(d(Ae.photos),te.forEach(Qe=>URL.revokeObjectURL(Qe)),re([]),J([]))},ke=Ae=>{if(!Ae)return;const Ce=Array.from(Ae);re(ze=>[...ze,...Ce]);const qe=Ce.map(ze=>URL.createObjectURL(ze));J(ze=>[...ze,...qe])},Ie=Ae=>{URL.revokeObjectURL(te[Ae]),re(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(),Ve=`${a==null?void 0:a.id}/${m.id}/${Date.now()}.${ze}`,{error:ht}=await q.storage.from("listing-photos").upload(Ve,qe);if(ht)throw ht;const{data:{publicUrl:Qe}}=q.storage.from("listing-photos").getPublicUrl(Ve);await y.mutateAsync({listingId:m.id,photoUrl:Qe,isPrimary:!((Ce=m.photos)!=null&&Ce.length)})}ne.success("Photos uploaded!")}catch(qe){console.error("Upload error:",qe),ne.error("Failed to upload photos")}finally{ae(!1)}}},Ne=async Ae=>{for(let Ce=0;Ce{if(m)try{await b.mutateAsync({photoId:Ae,listingId:m.id}),ne.success("Photo removed")}catch{ne.error("Failed to remove photo")}},Se=async Ae=>{if(Ae.preventDefault(),!ue.city.trim()||!ue.state.trim()||!ue.price){ne.error("Please fill in required fields (City, State, Price)");return}if(o&&!E){ne.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=Z&&G&&G!==(m==null?void 0:m.agent_id)?{agent_id:G}:{},ze=m==null?void 0:m.status;await v.mutateAsync({id:s,...Ce,...qe}),ne.success("Listing updated!");const Ve=`/mission-control/listings/${s}`;ze&&ze!==ue.status?h({open:!0,listingId:s,nextPath:Ve,socialStatus:WEe(ue.status)}):r(Ve)}else{ae(!0);let qe;if(o&&E?qe=await x.mutateAsync({agentId:E,...Ce}):Z&&G&&G!==(a==null?void 0:a.id)?qe=await x.mutateAsync({agentId:G,...Ce}):qe=await g.mutateAsync(Ce),le.length>0)try{await Ne(qe.id),te.forEach(Ve=>URL.revokeObjectURL(Ve)),re([]),J([])}catch(Ve){console.error("Photo upload error:",Ve),ne.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Ve=0;Ver(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(Va,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Assign to Agent *"})}),e.jsxs(Le,{children:[e.jsxs(ms,{value:E,onValueChange:I,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select an agent..."})}),e.jsx(hs,{children:A.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."})]})]}),Z&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Primary Listing Agent"})}),e.jsxs(Le,{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(CXn,{onImport:Ee}),c.length>0&&e.jsxs(je,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(St,{className:"pb-3",children:[e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(ji,{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(Le,{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(mr,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Property Details"})}),e.jsx(Le,{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=>be({...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=>be({...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=>be({...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=>be({...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=>be({...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=>be({...ue,property_type:Ae}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:PXn.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=>be({...ue,status:Ae}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:MXn.map(Ae=>e.jsx(Ge,{value:Ae.value,children:Ae.label},Ae.value))})]})]})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Property Specs (Optional)"})}),e.jsx(Le,{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=>be({...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=>be({...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=>be({...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=>be({...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=>be({...ue,year_built:Ae.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(jn,{checked:ue.has_hoa,onCheckedChange:Ae=>be({...ue,has_hoa:Ae})}),e.jsx(ee,{children:"Has HOA"})]})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Description & Links"})}),e.jsxs(Le,{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=>be({...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=>be({...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(jn,{checked:ue.agent_notes_public,onCheckedChange:Ae=>be({...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=>be({...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=>be({...ue,video_link:Ae.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Co-Listing Agent (optional)"})}),e.jsxs(Le,{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&&(be(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||""})),ne.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=>be({...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=>be({...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=>be({...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=>be({...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&&fe(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(Ct,{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:()=>be(Ae=>({...Ae,co_agent_photo_url:""})),children:[e.jsx(mr,{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(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Le,{children:e.jsx(AXn,{selectedVideoId:ue.video_id,onVideoSelect:Ae=>be({...ue,video_id:Ae}),listingId:l?s:void 0})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Photos"})}),e.jsx(Le,{children:l&&(m!=null&&m.photos)?e.jsx(sUt,{photos:m.photos,uploading:X,onUpload:Ae=>Fe(Ae),onRemove:Ae=>Be(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(LXn,{photoUrls:te,onRemove:Ie,onReorder:(Ae,Ce)=>{J(Ae),re(Ce)},pendingPhotos:le,uploading:X,onUpload:ke})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Le,{children:l&&s?e.jsx(TXn,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Sharing & Collaboration"})}),e.jsxs(Le,{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(jn,{checked:ue.allow_sharing,onCheckedChange:Ae=>be({...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(jn,{checked:ue.open_to_referrals,onCheckedChange:Ae=>be({...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(jn,{checked:ue.open_to_social_promotion,onCheckedChange:Ae=>be({...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(jn,{checked:ue.share_with_brokerage,onCheckedChange:Ae=>be({...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(jn,{checked:ue.site_only,onCheckedChange:Ae=>be({...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(jn,{checked:ue.is_public,disabled:ue.site_only,onCheckedChange:Ae=>be({...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(jn,{checked:ue.show_on_lead_site,onCheckedChange:Ae=>be({...ue,show_on_lead_site:Ae})})]})]})]}),e.jsx($,{type:"submit",className:"w-full",size:"lg",disabled:g.isPending||v.isPending,children:g.isPending||v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(Zst,{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 EXe=[{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"}],Ars=[{type:"extra_video",label:"Extra Video / Reel",icon:fa,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:uJ,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:Hc,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:d2,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:ca,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:Sd,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],RXn=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],P$e={sections:Object.fromEntries(EXe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},DXn=()=>Math.random().toString(36).slice(2,10);function FXn(){const{listingId:s}=Wi(),t=Zn(),{user:n}=_s(),r=Zt(),[a,i]=j.useState("desktop"),[l,o]=j.useState(P$e),[c,d]=j.useState(!1),[u,h]=j.useState(0),{data:m,isLoading:f}=st({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({...P$e,...m.page_config||{},sections:{...P$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]),v=j.useMemo(()=>m?`https://listings.relevelup.com/${m.slug||m.id}`:"",[m]),y=mt({mutationFn:async()=>{const{error:D}=await q.from("listings").update({page_config:l}).eq("id",s);if(D)throw D},onSuccess:()=>{ne.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=>ne.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:DXn(),type:D,data:{}}]}),A=(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(Va,{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(ZN,{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(g1,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>h(D=>D+1),children:[e.jsx(co,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh"]}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:v,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx($,{size:"sm",onClick:()=>y.mutate(),disabled:!c||y.isPending,children:y.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(go,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(uX,{icon:e.jsx(wn,{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(uX,{icon:e.jsx(yd,{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"}),RXn.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(uX,{icon:e.jsx(Qx,{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(uX,{icon:e.jsx(IA,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${R} of ${EXe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:EXe.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(jn,{checked:O,onCheckedChange:W=>w(D.key,W)})]},D.key)})})}),e.jsxs(uX,{icon:e.jsx(cn,{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:Ars.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(OXn,{addon:D,onChange:U=>A(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:()=>y.mutate(),disabled:!c||y.isPending,children:y.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(je,{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(Ta,{className:"h-3.5 w-3.5"}),"Live preview",c&&e.jsx($e,{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(ma,{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(ZN,{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(g1,{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 uX({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 OXn({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=Ars.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(zg,{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(zg,{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(qn,{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 Ers="teleprompter_settings",I$e={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function zXn(){try{const s=localStorage.getItem(Ers);return s?{...I$e,...JSON.parse(s)}:I$e}catch{return I$e}}function BXn(s){try{localStorage.setItem(Ers,JSON.stringify(s))}catch{}}function Bot({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(zXn),{scrollSpeed:f,fontSize:g,lineHeight:x,opacity:v,position:y,isMirrored:b}=h,w=j.useCallback((U,W)=>{m(V=>{const G={...V,[U]:W};return BXn(G),G})},[]),[S,A]=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:Z,clientHeight:X}=o.current;if(G+X>=Z){A(!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(),A(!0)):I(U)},1e3);return()=>clearInterval(W)}else setTimeout(()=>A(!0),100);else r||(A(!1),I(null))},[r,t,a,i]);const R=j.useCallback(()=>{o.current&&(o.current.scrollTop=0),A(!1)},[]),D=j.useCallback(()=>{A(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(Ta,{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[y],E!==null&&"opacity-30"),style:{opacity:E!==null?.3:v},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(Gd,{children:[e.jsx(Wd,{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(Nd,{className:"h-4 w-4"})})}),e.jsx(Dd,{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(bx,{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(bx,{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(bx,{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(v*100),"%"]})]}),e.jsx(bx,{value:[v*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:y==="top"?"default":"outline",size:"sm",onClick:()=>w("position","top"),children:e.jsx(xb,{className:"h-4 w-4"})}),e.jsx($,{variant:y==="center"?"default":"outline",size:"sm",onClick:()=>w("position","center"),children:e.jsx(YN,{className:"h-4 w-4"})}),e.jsx($,{variant:y==="bottom"?"default":"outline",size:"sm",onClick:()=>w("position","bottom"),children:e.jsx(wl,{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(jn,{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(Cv,{className:"h-4 w-4"}):e.jsx(Ou,{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(Sx,{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(Nx,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function $Xn({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}=i9n(),{data:f,isLoading:g}=o9n(),{data:x,isLoading:v}=l9n(),y=c9n(),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})},A=async I=>{try{await y.mutateAsync(I),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},E=m||g||v;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(pa,{value:d,onValueChange:I=>u(I),className:"flex-1 flex flex-col",children:[e.jsxs(ga,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(Xt,{value:"levelup",children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(Xt,{value:"my-scripts",children:[e.jsx(A0,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(Qt,{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($e,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),h==null?void 0:h.map(I=>e.jsx($e,{variant:o===I.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(I.id),children:I.name},I.id))]}),e.jsx(go,{className:"flex-1 max-h-[50vh]",children:E?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{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(Qr,{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(je,{className:Pt("cursor-pointer hover:bg-accent/50 transition-colors",n===I.id&&"ring-2 ring-primary"),onClick:()=>S(I),children:[e.jsx(St,{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(Et,{className:"text-sm font-medium truncate",children:I.title}),I.category&&e.jsx($e,{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(),A(I)},children:e.jsx(A0,{className:"h-4 w-4"})}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Le,{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(Qt,{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(cn,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(go,{className:"flex-1 max-h-[50vh]",children:v?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{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(A0,{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(je,{className:Pt("cursor-pointer hover:bg-accent/50 transition-colors",n===I.id&&"ring-2 ring-primary"),onClick:()=>S(I),children:[e.jsx(St,{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(Et,{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($e,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx($e,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(Le,{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 UXn({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=j.useState(()=>{const o=vV(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(Ct,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:eqs.map(o=>{const c=tqs(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(y1,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(v1,{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(wl,{className:Pt("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(b1,{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(ma,{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: "',vV(s).headerText(n),'"']})]})}function Trs({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,v]=j.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[y,b]=j.useState(!1),[w,S]=j.useState(!1),A=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:Z}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(Z)throw Z;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=>{v(G),b(!1),c(!0);try{const{error:Z}=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(Z)throw Z;ne.success(G?`Assigned to ${G.name}`:"Contact removed"),a==null||a()}catch(Z){console.error("Failed to update contact:",Z),ne.error("Failed to update contact")}finally{c(!1)}},P=async G=>{l(G),c(!0);try{const{error:Z}=await q.from("agent_videos").update({page_template:G}).eq("id",n.id);if(Z)throw Z;m(G),ne.success("Template saved!"),a==null||a()}catch(Z){console.error("Failed to save template:",Z),ne.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",Z=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},O=async()=>{if(!n.thumbnail_url){ne.error("Video thumbnail not available yet");return}const G=D(),Z=`Watch: ${n.title||"Video Message"} ${A}`;try{const X=new Blob([G],{type:"text/html"}),ae=new Blob([Z],{type:"text/plain"}),le=new ClipboardItem({"text/html":X,"text/plain":ae});await navigator.clipboard.write([le]),ne.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(Z+` `+G),ne.success("Copied! Paste into your email.")}},U=async()=>{await navigator.clipboard.writeText(A),u(!0),ne.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},W=()=>{const Z=vV(i).headerText(R),X=i==="default"?`Check out this video: ${A}`:`${Z} Check out this special video: ${A}`;window.open(`sms:?body=${encodeURIComponent(X)}`,"_self")},V=()=>{const G=vV(i),Z=G.headerText(R),X=i==="default"?n.title||"Video Message":Z,ae=`${G.subText} Watch the video: ${A}`,le=x!=null&&x.email?encodeURIComponent(x.email):"";window.open(`mailto:${le}?subject=${encodeURIComponent(X)}&body=${encodeURIComponent(ae)}`,"_self")};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Sd,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(Er,{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(Gd,{open:y,onOpenChange:b,children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":y,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(kw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Dd,{className:"w-[300px] p-0",align:"start",children:e.jsxs(N2,{children:[e.jsx(k2,{placeholder:"Search contacts..."}),e.jsxs(S2,{children:[e.jsx(C2,{children:w?"Loading...":"No contacts found."}),e.jsx(Rw,{children:f.map(G=>e.jsxs(h1,{value:G.name,onSelect:()=>I(G),children:[e.jsx(ma,{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(mr,{className:"h-4 w-4"})})]}),x&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',vV(i).headerText(x.name),'"']})]}),e.jsx(UXn,{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:A,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(ma,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Za,{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(Hc,{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(no,{className:"h-4 w-4"}),"Text"]}),e.jsxs($,{variant:"outline",className:"flex-1 gap-2",onClick:V,children:[e.jsx(pn,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(Nr,{children:e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function qXn(){var qe;const s=Zn(),[t]=Nc(),{toast:n}=Bi(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c}=NQt(),{data:d}=L_(),u=f3(),h=f9n(),[m,f]=j.useState("record"),[g,x]=j.useState(""),[v,y]=j.useState(!1),[b,w]=j.useState(!1),[S,A]=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),[Z,X]=j.useState(r||""),[ae,le]=j.useState(""),[re,te]=j.useState(""),[J,ce]=j.useState(null),[ve,fe]=j.useState(null),[ue,be]=j.useState(null),[Ee,ke]=j.useState(!1),Ie=j.useCallback(async(ze,Ve)=>{I(ze),f("uploading");try{const{videoId:ht,uploadUrl:Qe}=await k6(ae||"Quick Video Touch");W(ht);const{apiKey:at}=await S6(ht),rt=new XMLHttpRequest;rt.upload.onprogress=gt=>{gt.lengthComputable&&R(gt.loaded/gt.total*100)},await new Promise((gt,es)=>{rt.onload=()=>{rt.status>=200&&rt.status<300?gt():es(new Error(`Upload failed: ${rt.status}`))},rt.onerror=()=>es(new Error("Upload failed")),rt.open("PUT",Qe),rt.setRequestHeader("AccessKey",at),rt.send(ze)}),f("processing");let Ke=0;const Je=Date.now(),ft=90*1e3;for(;Ke<4;){if(await new Promise(es=>setTimeout(es,3e3)),Date.now()-Je>ft){const es=ze.size/1048576,Ht=`https://iframe.mediadelivery.net/play/${ht}/${ht}`;await u.mutateAsync({bunny_video_id:ht,playback_url:Ht,file_size_mb:es,title:ae||"Quick Video Touch",notes:re||void 0,contact_id:Z&&Z!=="none"?Z: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 gt=await hk(ht);if(Ke=gt.status,O(gt.encodeProgress||0),Ke===4)G({playbackUrl:gt.directPlayUrl,thumbnailUrl:gt.thumbnailUrl,previewUrl:gt.previewUrl||null,duration:gt.length||Ve,fileSizeMb:(gt.storageSize||ze.size)/(1024*1024)});else if(Ke===5||Ke===6)throw new Error("Video processing failed")}f("details")}catch(ht){console.error("Upload error:",ht),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),f("record")}},[ae,n]),Fe=async()=>{if(!(!U||!V))try{const ze=Z&&Z!=="none"?Z:null,Ve=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:re,task_id:a||null,status:"ready"});ce(Ve.id),fe(Ve.share_token||null),ze&&await h.mutateAsync({contactId:ze,videoId:Ve.id,notes:re}),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"})}},Ne=(ze,Ve)=>{navigator.clipboard.writeText(Ve),be(ze),setTimeout(()=>be(null),2e3),n({title:"Copied to clipboard!"})},Be=()=>ve?`https://video.relevelup.com/${ve}`:(V==null?void 0:V.playbackUrl)||"",Se=()=>{const ze=d==null?void 0:d.find(rt=>rt.id===Z),Ve=ze?`${ze.first_name}`:"",ht=(ze==null?void 0:ze.phone)||"",Qe=(ze==null?void 0:ze.email)||"",at=Be();return{text:`Hey${Ve?` ${Ve}`:""}! I recorded a quick video for you: ${at}`,link:at,contactPhone:ht,contactEmail:Qe}},Ae=()=>{const{text:ze,contactPhone:Ve}=Se(),ht=Ve?`sms:${Ve}?body=${encodeURIComponent(ze)}`:`sms:?body=${encodeURIComponent(ze)}`;window.open(ht,"_self")},Ce=()=>{const{link:ze,contactEmail:Ve}=Se(),ht="Check out this video",Qe=`I recorded a quick video for you: ${ze}`,at=Ve?`mailto:${Ve}?subject=${encodeURIComponent(ht)}&body=${encodeURIComponent(Qe)}`:`mailto:?subject=${encodeURIComponent(ht)}&body=${encodeURIComponent(Qe)}`;window.open(at,"_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(Va,{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(Qr,{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(DT,{maxDurationSeconds:600,onRecordingComplete:Ie,onRecordingStateChange:A,className:"w-full",teleprompterContent:v&&g&&e.jsx(Bot,{text:g,isVisible:v,onToggleVisibility:()=>y(!1),isRecording:S,startCountdown:!1})}),!v&&g&&e.jsxs($,{variant:"outline",className:"mt-4",onClick:()=>y(!0),children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(je,{className:"lg:col-span-1",children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Le,{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(Vy,{open:b,onOpenChange:w,children:[e.jsx(Tae,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full",children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(uy,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(I0,{className:"p-4 border-b",children:e.jsx(L0,{children:"Select a Script"})}),e.jsx($Xn,{onSelectScript:ze=>{x(ze.text),w(!1),y(!0)},className:"h-[calc(100vh-80px)]"})]})]}),g&&e.jsx($,{className:"w-full",onClick:()=>y(!0),children:"Use Script"})]})]})]}),m==="uploading"&&e.jsx(je,{className:"max-w-md mx-auto",children:e.jsxs(Le,{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(je,{className:"max-w-md mx-auto",children:e.jsxs(Le,{className:"pt-6 text-center space-y-4",children:[e.jsx(Ct,{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(je,{className:"max-w-lg mx-auto",children:[e.jsx(St,{children:e.jsx(Et,{children:"Video Details"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:ae,onChange:ze=>le(ze.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Attach to Contact (Optional)"}),e.jsxs(ms,{value:Z,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(Sd,{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:re,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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),m==="share"&&e.jsxs(je,{className:"max-w-lg mx-auto",children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(ma,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Le,{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(no,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:Ce,children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>Ne("link",Se().link),children:[e.jsx(Sd,{className:"h-4 w-4 mr-2"}),"Copy Video Link",ue==="link"&&e.jsx(ma,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>ke(!0),children:[e.jsx(yd,{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&&ve&&e.jsx(Trs,{open:Ee,onOpenChange:ke,video:{id:J,share_token:ve,title:ae||null,contact_id:Z||null,thumbnail_url:(V==null?void 0:V.thumbnailUrl)||null},contactName:((qe=d==null?void 0:d.find(ze=>ze.id===Z))==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(Al,{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 VXn({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(""),[v,y]=j.useState(""),[b,w]=j.useState(""),[S,A]=j.useState(!1),E=vQt(),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&&(y(`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 Z=l.find(X=>X.id===n.contact_id);Z&&(d(Z),x(Z.email||""))}},[s,n.contact_id,l]);const D=async()=>{f(!0);try{const{data:Z,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(Z||[])}catch{console.error("Failed to fetch contacts")}finally{f(!1)}},O=Z=>{d(Z),h(!1),x(Z.email||""),w(`Hey ${Z.first_name}! I recorded a quick video just for you. Click below to watch it:`),y(`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=Z=>{const X=`${Z.first_name||""} ${Z.last_name||""}`.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim();return X?X.length>60?`${X.slice(0,60)}…`:X:Z.email||"Unnamed contact"},V=Z=>{const X=b.split(/\n\n+/).map(re=>`

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

`).join(""),ae=Z?_Qt(Z):I,le=Z?``:"";return`
${X}

▶ Watch Video

${le}
`},G=async()=>{var Z;if(!g){ne.error("Please enter a recipient email");return}if(!I){ne.error("Video does not have a share link");return}A(!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:le,error:re}=await q.functions.invoke("gmail-send",{body:{to:g,subject:v,body:ae,contactId:(c==null?void 0:c.id)||null}});let te=null;if(re&&((Z=re.context)!=null&&Z.json))try{te=await re.context.json()}catch{}if((te==null?void 0:te.error)==="insufficient_scope"||(le==null?void 0:le.error)==="insufficient_scope"){ne.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(re)throw new Error((te==null?void 0:te.message)||re.message);if(!(le!=null&&le.success))throw new Error((le==null?void 0:le.error)||"Failed to send");ne.success("Video email sent!"),t(!1),i==null||i()}catch(X){console.error("Gmail send error:",X),ne.error("Failed to send: "+(X instanceof Error?X.message:"Unknown error"))}finally{A(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{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(Gd,{open:u,onOpenChange:h,children:[e.jsx(Wd,{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(kw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Dd,{className:"w-[350px] p-0",align:"start",children:e.jsxs(N2,{children:[e.jsx(k2,{placeholder:"Search contacts..."}),e.jsxs(S2,{children:[e.jsx(C2,{children:m?"Loading...":"No contacts found."}),e.jsx(Rw,{children:l.filter(Z=>Z.email).map(Z=>e.jsxs(h1,{value:`${W(Z)} ${Z.email||""}`,onSelect:()=>O(Z),children:[e.jsx(ma,{className:Pt("mr-2 h-4 w-4",(c==null?void 0:c.id)===Z.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:W(Z)}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Z.email})]})]},Z.id))})]})]})})]}),c&&e.jsx($,{variant:"ghost",size:"icon",onClick:U,className:"shrink-0",children:e.jsx(mr,{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:Z=>x(Z.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(Vc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"video-subject",children:"Subject"}),e.jsx(pe,{id:"video-subject",value:v,onChange:Z=>y(Z.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:Z=>w(Z.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(Ou,{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(Ou,{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||!v,className:"gap-2",children:[S?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),S?"Sending...":"Send Video Email"]})]})]})]})})}const HXn=()=>{const{user:s}=_s();return st({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 GXn({recipient:s}){return s.watched_at?e.jsxs($e,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(Ou,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs($e,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(lb,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs($e,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(Ta,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs($e,{variant:"outline",className:"text-[10px]",children:[e.jsx(Zr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function WXn({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=qBn(n);return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(Us,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Gl,{className:"h-5 w-5"}),"Send Analytics: ",r]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(xn,{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(go,{className:"h-[400px]",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{children:"Recipient"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Sent"}),e.jsx(Dt,{children:"Last Activity"})]})}),e.jsx(fi,{children:a.map(l=>e.jsxs(An,{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(GXn,{recipient:l})}),e.jsx(wt,{className:"text-xs text-muted-foreground",children:Js(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(wt,{className:"text-xs text-muted-foreground",children:l.last_activity_at?hu(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function KXn(){const{data:s,isLoading:t}=VBn(),{data:n=[],isLoading:r}=HBn(),[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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(xn,{className:"h-4 w-20"})}),e.jsx(Le,{children:e.jsx(xn,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(Zr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Le,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(Ta,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(lb,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(Vn,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Le,{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(fa,{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(Zr,{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(Ta,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(lb,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(Zl,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(WXn,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function YXn({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(fa,{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 ZXn({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:v}){const[y,b]=j.useState(!1);return e.jsxs(je,{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(YXn,{previewSrc:t,thumbnailSrc:n,alt:s.title||"Video preview",isHovered:y}),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(Ou,{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:v(s.duration_seconds)}),s.status!=="ready"&&e.jsx($e,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Le,{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(ca,{className:"h-3 w-3"}),e.jsx("span",{children:Js(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(Ta,{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(pn,{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(ca,{className:"h-3 w-3"}),e.jsx("span",{children:Js(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(Ta,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:w=>w.stopPropagation(),children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Cu,{align:"end",className:"bg-popover",children:[e.jsxs(ja,{onClick:w=>{w.stopPropagation(),r()},children:[e.jsx(Ta,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(P0,{}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),u()},children:[e.jsx(yd,{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(Sd,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),o()},children:[e.jsx(SE,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),c()},children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),d()},children:[e.jsx(Ir,{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(Zr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),i()},children:[e.jsx(pi,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(P0,{}),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(qn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function XXn(){var as,bs;const s=Zn(),{data:t,isLoading:n,refetch:r}=d9n(),{data:a}=rDe(),{data:i}=L_(),l=m9n(),o=h9n(),{isGmailConnected:c,gmailEmail:d}=Gy(),{data:u}=Ow(),{data:h=[],isLoading:m}=HXn(),[f,g]=j.useState("my"),[x,v]=j.useState(""),[y,b]=j.useState(null),[w,S]=j.useState(!1),[A,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(!1),[O,U]=j.useState(!1),[W,V]=j.useState(""),[G,Z]=j.useState(!1),[X,ae]=j.useState(!1),[le,re]=j.useState(!1),[te,J]=j.useState(!1),[ce,ve]=j.useState(""),[fe,ue]=j.useState({}),be=Ut=>{if(!Ut)return"Unassigned";const Ft=i==null?void 0:i.find(is=>is.id===Ut);return Ft?`${Ft.first_name} ${Ft.last_name||""}`.trim():"Unknown"},Ee=Ut=>{if(!Ut)return"0:00";const Ft=Math.floor(Ut/60),is=Ut%60;return`${Ft}:${is.toString().padStart(2,"0")}`},[ke,Ie]=j.useState("all"),Fe=t==null?void 0:t.filter(Ut=>{const Ft=Ut.category||"general";if(ke==="general"&&Ft!=="general"||ke==="open_house"&&Ft!=="open_house")return!1;if(!x)return!0;const is=be(Ut.contact_id).toLowerCase(),jt=(Ut.title||"").toLowerCase(),zs=(Ut.notes||"").toLowerCase();return is.includes(x.toLowerCase())||jt.includes(x.toLowerCase())||zs.includes(x.toLowerCase())}),Ne=(t==null?void 0:t.filter(Ut=>(Ut.category||"general")==="open_house").length)||0,Be=(t==null?void 0:t.filter(Ut=>(Ut.category||"general")==="general").length)||0,Se=(t||[]).filter(Ut=>Ut.status==="processing"&&Ut.bunny_video_id).map(Ut=>Ut.id).join(",");j.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const Ft=t.filter(jt=>jt.status==="processing"&&jt.bunny_video_id);if(!Ft.length)return;let is=!1;for(const jt of Ft)try{const{data:zs,error:yt}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:jt.bunny_video_id,isAgentVideo:!0}});if(yt||!zs)continue;zs.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:zs.directPlayUrl,thumbnail_url:zs.thumbnailUrl,preview_url:zs.previewUrl,duration_seconds:zs.length||jt.duration_seconds,updated_at:new Date().toISOString()}).eq("id",jt.id),is=!0)}catch(zs){console.warn("Reconcile check failed for video",jt.id,zs)}is&&r()})()},[Se,r]),j.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const Ft=t.filter(gs=>(gs==null?void 0:gs.bunny_video_id)&&!fe[gs.id]);if(!Ft.length)return;const is=Ft.map(gs=>gs.bunny_video_id),{data:jt,error:zs}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:is,isAgentVideo:!0}});if(zs)throw zs;const yt=(jt==null?void 0:jt.assets)||{};ue(gs=>{const Ss={...gs};for(const Ds of Ft)yt[Ds.bunny_video_id]&&(Ss[Ds.id]={previewUrl:yt[Ds.bunny_video_id].previewUrl,thumbnailUrl:yt[Ds.bunny_video_id].thumbnailUrl});return Ss})})().catch(Ft=>console.warn("Failed to load signed Bunny asset URLs",Ft))},[t,fe]);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,Ve=qe>=100,ht=async(Ut,Ft)=>{await navigator.clipboard.writeText(Ut),ne.success(`${Ft} copied to clipboard`)},Qe=Ut=>Ut.share_token?`https://video.relevelup.com/${Ut.share_token}`:Ut.playback_url||"",at=Ut=>{const Ft=Qe(Ut),is=i==null?void 0:i.find(Ds=>Ds.id===Ut.contact_id),jt=be(Ut.contact_id),zs=jt!=="Unassigned"?jt.split(" ")[0]:"",yt=(is==null?void 0:is.phone)||"",gs=`Hey${zs?` ${zs}`:""}! I recorded a quick video message for you. Check it out: ${Ft}`,Ss=yt?`sms:${yt}?body=${encodeURIComponent(gs)}`:`sms:?body=${encodeURIComponent(gs)}`;window.open(Ss,"_self")},rt=Ut=>{const Ft=i==null?void 0:i.find(Ss=>Ss.id===Ut.contact_id),is=(Ft==null?void 0:Ft.email)||"",jt=Qe(Ut),zs="Check out this video",yt=`I recorded a quick video for you: ${jt}`,gs=is?`mailto:${is}?subject=${encodeURIComponent(zs)}&body=${encodeURIComponent(yt)}`:`mailto:?subject=${encodeURIComponent(zs)}&body=${encodeURIComponent(yt)}`;window.open(gs,"_self")},Ke=Ut=>{var zs;const Ft=Qe(Ut),is=Ut.title||"Video Message",jt=Ut.share_token?`https://video.relevelup.com/thumb/${Ut.share_token}`:((zs=fe[Ut.id])==null?void 0:zs.thumbnailUrl)||Ut.thumbnail_url||"";return``},Je=async Ut=>{if(!Ut.thumbnail_url&&!Ut.share_token){ne.error("Video thumbnail not available yet");return}const Ft=Ke(Ut),is=Qe(Ut),jt=`Watch: ${Ut.title||"Video Message"} ${is}`;try{const zs=new Blob([Ft],{type:"text/html"}),yt=new Blob([jt],{type:"text/plain"}),gs=new ClipboardItem({"text/html":zs,"text/plain":yt});await navigator.clipboard.write([gs]),ne.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(jt+` `+Ft),ne.success("Copied! Paste into your email.")}},ft=async Ut=>{try{ne.loading("Preparing download...",{id:"download"});const{data:Ft,error:is}=await q.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:Ut.bunny_video_id,isAgentVideo:!0}});if(is||!(Ft!=null&&Ft.downloadUrl))throw new Error((is==null?void 0:is.message)||"Failed to get download URL");const zs=`${((Ut.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,yt=await fetch(Ft.downloadUrl);if(!yt.ok)throw new Error("Failed to fetch video file");const gs=await yt.blob(),Ss=URL.createObjectURL(gs),Ds=document.createElement("a");Ds.href=Ss,Ds.download=zs,Ds.rel="noreferrer",document.body.appendChild(Ds),Ds.click(),Ds.remove(),URL.revokeObjectURL(Ss),ne.success("Download started",{id:"download"})}catch(Ft){console.error("Download error:",Ft),ne.error("Could not force download (your browser may block it).",{id:"download"})}},gt=async Ut=>{b(Ut),Z(!0),V(""),U(!0);try{const{data:Ft,error:is}=await q.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:Ut.bunny_video_id,title:Ut.title,isAgentVideo:!0,shareToken:Ut.share_token}});if(is||!(Ft!=null&&Ft.html))throw new Error("Failed to generate CRM embed code");V(Ft.html)}catch(Ft){console.error("CRM embed error:",Ft),ne.error("Failed to generate CRM embed code"),U(!1)}finally{Z(!1)}},es=Ut=>{b(Ut),S(!0)},Ht=async()=>{if(y)try{await l.mutateAsync({id:y.id,bunnyVideoId:y.bunny_video_id,hardDelete:!0}),E(!1),b(null),ne.success("Video deleted successfully")}catch{ne.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&&((as=u.team)==null?void 0:as.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(Yn,{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(Gl,{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(cn,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),f==="team"?e.jsx(QXn,{videos:h,isLoading:m,searchTerm:x,setSearchTerm:v}):f==="analytics"?e.jsx(KXn,{}):e.jsxs(e.Fragment,{children:[e.jsx(je,{className:ze?"border-amber-500":Ve?"border-destructive":"",children:e.jsxs(Le,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(kJ,{className:`h-5 w-5 ${Ve?"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 ${Ve?"[&>div]:bg-destructive":ze?"[&>div]:bg-amber-500":""}`})]}),ze&&!Ve&&e.jsxs($e,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(vl,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),Ve&&e.jsxs($e,{variant:"destructive",children:[e.jsx(vl,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),Ve&&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:Be},{id:"open_house",label:"Open House Tours",count:Ne}].map(Ut=>e.jsxs("button",{onClick:()=>Ie(Ut.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${ke===Ut.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[Ut.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:Ut.count})]},Ut.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:Ut=>v(Ut.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(je,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(fa,{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(cn,{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(Ut=>{var Ft,is;return e.jsx(ZXn,{video:Ut,previewSrc:(Ft=fe[Ut.id])==null?void 0:Ft.previewUrl,thumbnailSrc:(is=fe[Ut.id])==null?void 0:is.thumbnailUrl,onOpen:()=>es(Ut),onDelete:()=>{b(Ut),E(!0)},onRename:()=>{b(Ut),ve(Ut.title||""),J(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${Ut.contact_id}`),onGetEmbedCode:()=>{b(Ut),D(!0)},onCopyEmailHtml:()=>Je(Ut),onEmbedToCrm:()=>gt(Ut),onShareWithTemplate:()=>{b(Ut),ae(!0)},onSendViaGmail:()=>{b(Ut),re(!0)},isGmailConnected:c,getContactName:be,getShareUrl:Qe,copyToClipboard:ht,formatDuration:Ee},Ut.id)})}),e.jsx(Os,{open:w,onOpenChange:S,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx($s,{children:(y==null?void 0:y.title)||"Video Preview"}),e.jsx(Er,{children:(y==null?void 0:y.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sl,{className:"h-3 w-3"}),be(y.contact_id)]})})]}),y&&e.jsxs("div",{className:"space-y-4",children:[y.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(Ct,{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(co,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:y.playback_url?(()=>{let Ut=y.playback_url;return Ut.includes("iframe.mediadelivery.net/play/")&&(Ut=Ut.replace("/play/","/embed/"),Ut+=(Ut.includes("?")?"&":"?")+"autoplay=false&responsive=true"),Ut.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:Ut,title:y.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:y.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:y.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>ne.error("Video preview failed to load")},y.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(fa,{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:()=>at(y),children:[e.jsx(no,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs($,{variant:"outline",onClick:()=>rt(y),children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs($,{variant:"outline",onClick:()=>ht(Qe(y),"Share link"),children:[e.jsx(Za,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs($,{variant:"outline",onClick:()=>Je(y),children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs($,{variant:"outline",onClick:()=>ft(y),children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs($,{variant:"outline",onClick:()=>{S(!1),gt(y)},children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs($,{variant:"outline",onClick:()=>{S(!1),ae(!0)},children:[e.jsx(yd,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(y==null?void 0:y.share_token)&&e.jsxs($,{variant:"outline",onClick:()=>{S(!1),re(!0)},children:[e.jsx(Zr,{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(qn,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(Os,{open:A,onOpenChange:E,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Delete Video"}),e.jsx(Er,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:Ht,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(kQt,{open:I,onOpenChange:P}),e.jsx(Os,{open:R,onOpenChange:D,children:e.jsxs(Fs,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Embed Video"}),e.jsx(Er,{children:"Copy this code to embed the video on your website."})]}),y&&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 Ut=``;ht(Ut,"Embed code")},children:[e.jsx(Za,{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."})]})]})}),y&&e.jsx(Trs,{open:X,onOpenChange:ae,video:y,contactName:be(y.contact_id)}),y&&e.jsx(VXn,{open:le,onOpenChange:re,video:y,gmailEmail:d,signedThumbnailUrl:(bs=fe[y.id])==null?void 0:bs.thumbnailUrl}),e.jsx(Os,{open:te,onOpenChange:J,children:e.jsxs(Fs,{className:"max-w-sm",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Rename Video"}),e.jsx(Er,{children:"Enter a new title for this video."})]}),e.jsx(pe,{value:ce,onChange:Ut=>ve(Ut.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:Ut=>{Ut.key==="Enter"&&ce.trim()&&o.mutate({id:y.id,title:ce.trim()},{onSuccess:()=>{ne.success("Video renamed"),J(!1)}})}}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>J(!1),children:"Cancel"}),e.jsx($,{disabled:!ce.trim()||o.isPending,onClick:()=>{o.mutate({id:y.id,title:ce.trim()},{onSuccess:()=>{ne.success("Video renamed"),J(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(Os,{open:O,onOpenChange:U,children:e.jsxs(Fs,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(Er,{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(Ct,{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:()=>{ht(W,"CRM embed code")},children:[e.jsx(Za,{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 QXn({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(je,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(Yn,{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(Ii,{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($e,{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(je,{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(fa,{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(Le,{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(Ta,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ca,{className:"h-3 w-3"}),Js(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const JXn=()=>{const{user:s}=_s();return st({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})},g3t=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function eQn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=JXn(),[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(v=>{g.has(v.owner_user_id)||(g.set(v.owner_user_id,{name:v.owner_name||"Unknown",avatar:v.owner_avatar_url,color:g3t[x%g3t.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(v=>{var y,b,w,S;return v.deal_name.toLowerCase().includes(x)||((y=v.contact_name)==null?void 0:y.toLowerCase().includes(x))||((b=v.property_address)==null?void 0:b.toLowerCase().includes(x))||((w=v.city)==null?void 0:w.toLowerCase().includes(x))||((S=v.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 v=x.stage_name||"Unknown";g.has(v)||g.set(v,{name:v,color:x.stage_color,icon:x.stage_icon,deals:[],totalValue:0});const y=g.get(v);y.deals.push(x),y.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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(Us,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Yn,{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(xn,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(xn,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(xn,{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(Yn,{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&&zIe[g.icon]||Dg;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($e,{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(go,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:g.deals.map(v=>{const y=c.get(v.owner_user_id);return e.jsx(tQn,{deal:v,ownerColor:(y==null?void 0:y.color)||"#888",ownerName:(y==null?void 0:y.name)||"Unknown",ownerAvatar:(y==null?void 0:y.avatar)||null,formatPrice:f},v.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 tQn({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(Ii,{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($e,{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(su,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function sQn({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(Yn,{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(kd,{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(go,{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(Yn,{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(jn,{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(Ii,{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(jn,{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(Ii,{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 x3t=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function nQn(){const s=Sa(),{data:t}=Ow(),n=(t==null?void 0:t.role)==="team_leader",r=t==null?void 0:t.teamId,a=st({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:x3t[h%x3t.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function rQn(s){return st({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 aQn(){const s=Sa();return st({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 Mrs({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(Bu,{open:a,onOpenChange:i,children:[e.jsx($u,{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(Cu,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&zIe[c.icon]||Dg,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(ma,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const iQn={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"}},oQn={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 Prs({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=RK(),m=iQn[s.deal_type],f=oQn[s.priority],g=j.useMemo(()=>s.target_close_date?ck(kh(s.target_close_date),new Date):null,[s.target_close_date]),x=l||o||!!s.actual_close_date,v=!x&&g!==null&&g<0,y=!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?kh(s.contract_date):new Date;return ck(R,kh(P))},[s]),w=l&&!s.scorecard_transaction_id,S=!!s.scorecard_transaction_id,A=P=>P?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(P):null;return e.jsxs(je,{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",v&&"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(Le,{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(Ii,{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($e,{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(nu,{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(Vr,{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(Su,{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(su,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:A(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",A(s.expected_commission)," GCI"]}),(()=>{const P=gw(s);return P!==null&&P!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",A(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(Sv,{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(PQt,{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(Mrs,{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]",v&&"text-red-600",y&&!v&&"text-amber-600",!v&&!y&&"text-muted-foreground"),children:[v?e.jsx(vl,{className:"h-3 w-3"}):e.jsx(Ea,{className:"h-3 w-3"}),e.jsx("span",{children:v?`${Math.abs(g)}d overdue`:y?`${g}d left`:Js(kh(s.target_close_date),"MMM d")})]}):null]})]})]})}function lQn({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),v=t.reduce((A,E)=>A+(E.expected_price||0),0),y=t.reduce((A,E)=>A+(E.expected_commission||0),0),b=t.reduce((A,E)=>A+(gw(E)||0),0),w=A=>A>=1e6?`$${(A/1e6).toFixed(1)}M`:A>=1e3?`$${(A/1e3).toFixed(0)}K`:`$${A.toFixed(0)}`,S=s.icon&&zIe[s.icon]||Dg;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($e,{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:A=>i(A,s.id),onDrop:A=>l(A,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($e,{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(kd,{className:"h-3.5 w-3.5"})})]})]}),v>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(v)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[w(y)," GCI"]}),b>0&&b!==y&&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(go,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(A=>e.jsx("div",{draggable:!0,onDragStart:E=>{E.dataTransfer.effectAllowed="move",a(A.id,s.id)},children:e.jsx(Prs,{deal:A,onClick:()=>n(A),isWonStage:c,isLostStage:d,ownerInfo:(u==null?void 0:u(A))||null,tags:h[A.id]||[],overdueTaskCount:m[A.id]||0})},A.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(cn,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}const nk=q;function cQn(s,t=!1){return st({queryKey:["commission-plans",s,t],enabled:!!s,queryFn:async()=>{let n=nk.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 dQn(s){const t=Zt();return mt({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 nk.from("brokerage_commission_plans").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await nk.from("brokerage_commission_plans").insert(r);if(a)throw a}},onSuccess:()=>{t.invalidateQueries({queryKey:["commission-plans",s]}),ne.success("Commission plan saved")},onError:n=>ne.error(n.message||"Could not save plan")})}function uQn(s){return st({queryKey:["cap-progress",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await nk.rpc("get_agent_cap_progress",{_agent_user_id:s});if(n)throw n;return(t||[])[0]??null}})}function hQn(s){return st({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 nk.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 nk.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 nk.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 mQn(s){const t=Zt();return mt({mutationFn:async n=>{const{error:r}=await nk.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 nk.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]}),ne.success("Plan assigned")},onError:n=>ne.error(n.message||"Could not assign plan")})}function fQn(s){const t=Zt();return mt({mutationFn:async n=>{const r=new Date().toISOString().slice(0,10),{error:a}=await nk.from("agent_plan_assignments").update({end_date:r}).eq("id",n);if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-plan-roster",s]}),ne.success("Plan removed from agent")},onError:n=>ne.error(n.message||"Could not remove plan")})}function Irs(){const{user:s}=_s();return st({queryKey:["my-commission-plan",s==null?void 0:s.id],enabled:!!s,staleTime:5*6e4,queryFn:async()=>{const{data:t,error:n}=await nk.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 nk.from("brokerage_commission_plans").select("*").eq("id",t.plan_id).maybeSingle();if(a)throw a;return r?{assignment:t,plan:r}:null}})}function pQn({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=_s(),[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(wn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx($e,{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(y1,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(v1,{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(wn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx($e,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(wl,{className:Pt("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(b1,{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(jn,{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(yw,{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(Km,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(jc,{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(Km,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(cl,{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 gQn=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],xQn=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function L$e({label:s,date:t,onChange:n,placeholder:r="Pick a date",disabled:a}){const[i,l]=j.useState(t?Js(t,"MM/dd/yyyy"):"");j.useEffect(()=>{const c=hvt(i);t&&c&&c.getTime()===t.getTime()||l(t?Js(t,"MM/dd/yyyy"):"")},[t]);const o=c=>{l(c);const d=hvt(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(Gd,{children:[e.jsx(Wd,{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(Ea,{className:"mr-2 h-4 w-4"}),t?Js(t,"PPP"):r]})}),e.jsxs(Dd,{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(A2,{mode:"single",selected:t,onSelect:c=>{n(c),l(c?Js(c,"MM/dd/yyyy"):"")},initialFocus:!0,className:"pointer-events-auto",captionLayout:"dropdown",fromYear:1900,toYear:2100})]})]})]})}function yQn({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=Wie(),{data:i}=L_(),{data:l}=Bst(),o=x6e(),c=Srs(),d=Crs(),u=fit(),{data:h}=Irs(),{data:m}=Eae(),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,v]=j.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[y,b]=j.useState(""),[w,S]=j.useState(!1),[A,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,le,re,te,J,ce,ve,fe,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:((le=n.brokerage_split_pct)==null?void 0:le.toString())||"",team_split_pct:((re=n.team_split_pct)==null?void 0:re.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:((ve=n.bonus_amount)==null?void 0:ve.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?kh(n.target_close_date):void 0,contract_date:n.contract_date?kh(n.contract_date):void 0,listing_date:n.listing_date?kh(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||((fe=a==null?void 0:a[0])==null?void 0:fe.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(be=>{var Ee;return be.id===(r||((Ee=a==null?void 0:a[0])==null?void 0:Ee.id))}))==null?void 0:ue.default_probability)??50),notes:""}),b(""),v({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,be,Ee,ke,Ie;const ae=y.toLowerCase().trim();if(!ae)return!0;const le=((ue=X.first_name)==null?void 0:ue.toLowerCase())||"",re=((be=X.last_name)==null?void 0:be.toLowerCase())||"",te=((Ee=X.email)==null?void 0:Ee.toLowerCase())||"",J=((Ie=(ke=X.phone)==null?void 0:ke.toLowerCase)==null?void 0:Ie.call(ke))||"",ce=`${le} ${re}`.trim(),ve=`${re} ${le}`.trim();if(ce.includes(ae)||ve.includes(ae)||le.includes(ae)||re.includes(ae)||te.includes(ae)||J.includes(ae))return!0;const fe=ae.split(/\s+/).filter(Boolean);return fe.length>1?fe.every(Fe=>le.includes(Fe)||re.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 le=parseFloat(D.brokerage_split_pct)||0,re=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,ve=parseFloat(D.bonus_amount)||0;if(D.commission_calc_method==="referral_first"){let ue=X;te&&(ue-=X*te/100);let be=ue;return le&&(be-=ue*le/100),re&&(be-=X*re/100),J&&(be-=X*J/100),ce&&(be-=ce),Math.max(0,be)+ve}let fe=X;return le&&(fe=fe*((100-le)/100)),re&&(fe=fe*((100-re)/100)),te&&(fe=fe-X*te/100),J&&(fe=fe-X*J/100),ce&&(fe=fe-ce),Math.max(0,fe)+ve},G=async X=>{var ae,le,re;if(X.preventDefault(),!D.deal_name.trim()){ne.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:((le=D.contract_date)==null?void 0:le.toISOString().split("T")[0])||null,listing_date:((re=D.listing_date)==null?void 0:re.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}),ne.success("Deal updated successfully");else{const J=await c.mutateAsync(te);if(ne.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}),ne.success("Client portal created!")}catch{ne.error("Deal created, but portal setup failed")}}t(!1)}catch{ne.error("Failed to save deal")}},Z=c.isPending||d.isPending;return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:n?"Edit Deal":"Add New Deal"}),e.jsx(Er,{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:gQn.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,le=a==null?void 0:a.find(re=>re.id===ae);O(re=>({...re,stage_id:ae,probability:typeof(le==null?void 0:le.default_probability)=="number"?String(le.default_probability):re.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:y,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&&y&&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=y.trim().split(/\s+/);P({first_name:X[0]||"",last_name:X.slice(1).join(" ")||"",email:"",phone:""}),E(!0),S(!1)},children:[e.jsx(lc,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',y.trim(),'"']})]})]})]}),A&&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(lc,{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(Ct,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(lc,{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(nu,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(ms,{value:D.listing_id||"none",onValueChange:X=>{const ae=X==="none"?"":X,le=R.find(re=>re.id===ae);O(le?re=>{var te;return{...re,listing_id:ae,deal_type:"seller",property_address:le.property_address||re.property_address,city:le.city||re.city,state:le.state||re.state,expected_price:((te=le.price)==null?void 0:te.toString())||re.expected_price}}:re=>({...re,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(L$e,{label:"Target Close Date",date:D.target_close_date,onChange:X=>O(ae=>({...ae,target_close_date:X}))}),e.jsx(L$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(L$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:xQn.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(pQn,{formData:x,onChange:v}),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:Z,children:[Z&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function vQn({dealId:s}){const t=Sa(),n=Zt(),[r,a]=j.useState(""),[i,l]=j.useState(!1),{data:o=[]}=st({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=[]}=st({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(y=>y.tag))].sort()},enabled:!!t}),d=mt({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=mt({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($e,{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(mr,{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(cn,{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 bQn(s){return st({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 _Qn(){const s=Sa(),t=Zt();return mt({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 wQn(){const s=Zt();return mt({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 jQn(){const s=Zt();return mt({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 NQn(s){const{data:t,error:n}=await q.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const kQn={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"},SQn={pending:"Needed",submitted:"In review",approved:"Approved",rejected:"Changes requested"};function Lrs({dealId:s,canReview:t=!1,canUpload:n=!1}){const{data:r=[],isLoading:a}=Pzt(s),{data:i=[]}=ELs(s),l=CLs(),o=TLs(),[c,d]=j.useState(null),[u,h]=j.useState(""),[m,f]=j.useState(null),[g,x]=j.useState(null),v=j.useRef(null),y=j.useRef(null),b=A=>{var E;y.current=A,(E=v.current)==null||E.click()},w=async A=>{const E=y.current;if(!(!A||!E)){x(E.id);try{await o.mutateAsync({item:E,file:A}),ne.success("Document uploaded for review")}catch(I){ne.error(I.message||"Upload failed")}finally{x(null),y.current=null,v.current&&(v.current.value="")}}},S=async A=>{try{await l.mutateAsync({item:A,status:"rejected",note:u.trim()||"Changes requested"}),d(null),h("")}catch(E){ne.error(E.message||"Could not update item")}};return a?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{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:v,type:"file",className:"hidden",onChange:A=>{var E;return w((E=A.target.files)==null?void 0:E[0])}}),r.map(A=>{var R;const E=i.filter(D=>D.compliance_item_id===A.id),I=E.find(D=>D.is_current)||E[0],P=A.status!=="approved"&&A.due_date&&A.due_dateD.value===A.phase))==null?void 0:R.label)||A.phase}),A.due_date&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ca,{className:"h-3 w-3"})," Due ",A.due_date]}),E.length>0&&e.jsxs("button",{className:"flex items-center gap-1 hover:text-foreground",onClick:()=>f(m===A.id?null:A.id),children:[e.jsx(Cw,{className:"h-3 w-3"})," ",E.length," version",E.length>1?"s":""]})]}),A.status==="rejected"&&A.review_note&&e.jsx("p",{className:"mt-2 rounded-md bg-destructive/10 p-2 text-xs text-destructive",children:A.review_note})]}),e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1",children:[I&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Syt(I.storage_path),children:e.jsx(ji,{className:"h-4 w-4"})}),n&&A.requires_document&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>b(A),disabled:g===A.id,children:g===A.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(vJ,{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:A,status:"approved",note:null}),children:e.jsx(Vr,{className:"h-4 w-4 text-emerald-600"})}),e.jsx($,{variant:"ghost",size:"icon",title:"Request changes",onClick:()=>{d(c===A.id?null:A.id),h("")},children:e.jsx(ju,{className:"h-4 w-4 text-destructive"})})]})]})]}),c===A.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(A),children:"Send back to agent"})]})]}),m===A.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:()=>Syt(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))})]},A.id)})]})}function Rrs({dealId:s,brokerageId:t,role:n,counterpartName:r}){const{user:a}=_s(),{data:i=[],isLoading:l}=MLs(s),o=PLs(),c=ILs(),[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(""),ne.success("Message sent — an email notification is on the way")}catch(x){ne.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(pn,{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(Ct,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),"Send & notify"]})})]})]})}function CQn({dealId:s}){var a;const{data:t=[]}=Pzt(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(Rm,{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(Lrs,{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(Rrs,{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 TXe=function(s,t){return TXe=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])},TXe(s,t)};function Si(s,t){TXe(s,t);function n(){this.constructor=s}s.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var qc=function(){return qc=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+=cq[(s[r]&3)<<4|s[r+1]>>4],t+=cq[(s[r+1]&15)<<2|s[r+2]>>6],t+=cq[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},y3t=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},TQn=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,MQn=function(s){var t=s.trim(),n=t.substring(0,100),r=n.match(TQn);if(!r)return y3t(t);var a=r[0],i=t.substring(a.length);return y3t(i)},Oc=function(s){return s.charCodeAt(0)},PQn=function(s){return s.codePointAt(0)},Kie=function(s,t){return OS(s.toString(16),t,"0").toUpperCase()},ODe=function(s){return Kie(s,2)},GE=function(s){return String.fromCharCode(s)},IQn=function(s){return GE(parseInt(s,16))},OS=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]},DQn=function(s){for(var t=[],n=0,r=s.length;nn&&d(),l+=m,o+=f}}return d(),c},zQn=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,Brs=function(s){var t=s.match(zQn);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],v=x===void 0?"00":x,y=t[9],b=y===void 0?"00":y,w=g==="Z"?"Z":""+g+v+":"+b,S=new Date(n+"-"+a+"-"+l+"T"+c+":"+u+":"+m+w);return S}},$ot=function(s,t){for(var n,r=0,a;r=0&&s<=65535},ZQn=function(s){return s>=65536&&s<=1114111},Urs=function(s){return Math.floor((s-65536)/1024)+55296},qrs=function(s){return(s-65536)%1024+56320},hL;(function(s){s.BigEndian="BigEndian",s.LittleEndian="LittleEndian"})(hL||(hL={}));var mX="�".codePointAt(0),Vrs=function(s,t){if(t===void 0&&(t=!0),s.length<=1)return String.fromCodePoint(mX);for(var n=t?QQn(s):hL.BigEndian,r=t?2:0,a=[];s.length-r>=2;){var i=b3t(s[r++],s[r++],n);if(XQn(i))if(s.length-r<2)a.push(mX);else{var l=b3t(s[r++],s[r++],n);v3t(l)?a.push(i,l):a.push(mX)}else v3t(i)?(r+=2,a.push(mX)):a.push(i)}return r=55296&&s<=56319},v3t=function(s){return s>=56320&&s<=57343},b3t=function(s,t,n){if(n===hL.LittleEndian)return t<<8|s;if(n===hL.BigEndian)return s<<8|t;throw new Error("Invalid byteOrder: "+n)},QQn=function(s){return Hrs(s)?hL.BigEndian:Grs(s)?hL.LittleEndian:hL.BigEndian},Hrs=function(s){return s[0]===254&&s[1]===255},Grs=function(s){return s[0]===255&&s[1]===254},Wrs=function(s){return Hrs(s)||Grs(s)},JQn=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},cAe=function(s){return Math.ceil(s.toString(2).length/8)},V$=function(s){for(var t=new Uint8Array(cAe(s)),n=1;n<=t.length;n++)t[n-1]=s>>(t.length-n)*8;return t},Zie=function(s){throw new Error(s)},FT={};(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 nJn=0,Krs=1,rJn=2,aJn=3,iJn=258,Uot=29,Qie=256,xne=Qie+1+Uot,zV=30,qot=19,Yrs=2*xne+1,b8=15,R$e=16,oJn=7,Vot=256,Zrs=16,Xrs=17,Qrs=18,PXe=[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],dAe=[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],lJn=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],Jrs=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],cJn=512,LA=new Array((xne+2)*2);eY(LA);var tte=new Array(zV*2);eY(tte);var yne=new Array(cJn);eY(yne);var vne=new Array(iJn-aJn+1);eY(vne);var Hot=new Array(Uot);eY(Hot);var bPe=new Array(zV);eY(bPe);function D$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 eas,tas,sas;function F$e(s,t){this.dyn_tree=s,this.max_code=0,this.stat_desc=t}function nas(s){return s<256?yne[s]:yne[256+(s>>>7)]}function bne(s,t){s.pending_buf[s.pending++]=t&255,s.pending_buf[s.pending++]=t>>>8&255}function bw(s,t,n){s.bi_valid>R$e-n?(s.bi_buf|=t<>R$e-s.bi_valid,s.bi_valid+=n-R$e):(s.bi_buf|=t<>>=1,n<<=1;while(--t>0);return n>>>1}function dJn(s){s.bi_valid===16?(bne(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 uJn(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<=b8;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 aas(s,t,n){var r=new Array(b8+1),a=0,i,l;for(i=1;i<=b8;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]=ras(r[o]++,o))}}function hJn(){var s,t,n,r,a,i=new Array(b8+1);for(n=0,r=0;r>=7;r8?bne(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 mJn(s,t,n,r){oas(s),bne(s,n),bne(s,~n),eJn.arraySet(s.pending_buf,s.window,t,n,s.pending),s.pending+=n}function j3t(s,t,n,r){var a=t*2,i=n*2;return s[a]>1;l>=1;l--)O$e(s,n,l);d=i;do l=s.heap[1],s.heap[1]=s.heap[s.heap_len--],O$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++,O$e(s,n,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],uJn(s,t),aas(n,c,s.bl_count)}function k3t(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[Jrs[t]*2+1]===0;t--);return s.opt_len+=3*(t+1)+5+5+4,t}function pJn(s,t,n,r){var a;for(bw(s,t-257,5),bw(s,n-1,5),bw(s,r-4,4),a=0;a>>=1)if(t&1&&s.dyn_ltree[n*2]!==0)return _3t;if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0)return w3t;for(n=32;n0?(s.strm.data_type===sJn&&(s.strm.data_type=gJn(s)),IXe(s,s.l_desc),IXe(s,s.d_desc),l=fJn(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?las(s,t,n,r):s.strategy===tJn||i===a?(bw(s,(Krs<<1)+(r?1:0),3),N3t(s,LA,tte)):(bw(s,(rJn<<1)+(r?1:0),3),pJn(s,s.l_desc.max_code+1,s.d_desc.max_code+1,l+1),N3t(s,s.dyn_ltree,s.dyn_dtree)),ias(s),r&&oas(s)}function bJn(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[(vne[n]+Qie+1)*2]++,s.dyn_dtree[nas(t)*2]++),s.last_lit===s.lit_bufsize-1}JK._tr_init=xJn;JK._tr_stored_block=las;JK._tr_flush_block=vJn;JK._tr_tally=bJn;JK._tr_align=yJn;function _Jn(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 cas=_Jn;function wJn(){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 jJn=wJn();function NJn(s,t,n,r){var a=jJn,i=r+n;s^=-1;for(var l=r;l>>8^a[(s^t[l])&255];return s^-1}var das=NJn,Got={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"},d_=FT,rk=JK,uas=cas,ZM=das,kJn=Got,m9=0,SJn=1,CJn=3,mL=4,A3t=5,u4=0,E3t=1,ak=-2,AJn=-3,z$e=-5,EJn=-1,TJn=1,Lue=2,MJn=3,PJn=4,IJn=0,LJn=2,zDe=8,RJn=9,DJn=15,FJn=8,OJn=29,zJn=256,LXe=zJn+1+OJn,BJn=30,$Jn=19,UJn=2*LXe+1,qJn=15,Qu=3,wI=258,cC=wI+Qu+1,VJn=32,BDe=42,RXe=69,uAe=73,hAe=91,mAe=103,_8=113,zQ=666,w0=1,Jie=2,pB=3,tY=4,HJn=3;function jI(s,t){return s.msg=kJn[t],t}function T3t(s){return(s<<1)-(s>4?9:0)}function AP(s){for(var t=s.length;--t>=0;)s[t]=0}function XM(s){var t=s.state,n=t.pending;n>s.avail_out&&(n=s.avail_out),n!==0&&(d_.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 fb(s,t){rk._tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,t),s.block_start=s.strstart,XM(s.strm)}function Fh(s,t){s.pending_buf[s.pending++]=t}function fX(s,t){s.pending_buf[s.pending++]=t>>>8&255,s.pending_buf[s.pending++]=t&255}function GJn(s,t,n,r){var a=s.avail_in;return a>r&&(a=r),a===0?0:(s.avail_in-=a,d_.arraySet(t,s.input,s.next_in,a,n),s.state.wrap===1?s.adler=uas(s.adler,t,a,n):s.state.wrap===2&&(s.adler=ZM(s.adler,t,a,n)),s.next_in+=a,s.total_in+=a,a)}function has(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-cC?s.strstart-(s.w_size-cC):0,d=s.window,u=s.w_mask,h=s.prev,m=s.strstart+wI,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 gB(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-cC)){d_.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=GJn(s.strm,s.window,s.strstart+s.lookahead,i),s.lookahead+=r,s.lookahead+s.insert>=Qu)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(gB(s),s.lookahead===0&&t===m9)return w0;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,fb(s,!1),s.strm.avail_out===0)||s.strstart-s.block_start>=s.w_size-cC&&(fb(s,!1),s.strm.avail_out===0))return w0}return s.insert=0,t===mL?(fb(s,!0),s.strm.avail_out===0?pB:tY):(s.strstart>s.block_start&&(fb(s,!1),s.strm.avail_out===0),w0)}function B$e(s,t){for(var n,r;;){if(s.lookahead=Qu&&(s.ins_h=(s.ins_h<=Qu)if(r=rk._tr_tally(s,s.strstart-s.match_start,s.match_length-Qu),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=Qu){s.match_length--;do s.strstart++,s.ins_h=(s.ins_h<=Qu&&(s.ins_h=(s.ins_h<4096)&&(s.match_length=Qu-1)),s.prev_length>=Qu&&s.match_length<=s.prev_length){a=s.strstart+s.lookahead-Qu,r=rk._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-Qu),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=a&&(s.ins_h=(s.ins_h<=Qu&&s.strstart>0&&(a=s.strstart-1,r=l[a],r===l[++a]&&r===l[++a]&&r===l[++a])){i=s.strstart+wI;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>=Qu?(n=rk._tr_tally(s,1,s.match_length-Qu),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(n=rk._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),n&&(fb(s,!1),s.strm.avail_out===0))return w0}return s.insert=0,t===mL?(fb(s,!0),s.strm.avail_out===0?pB:tY):s.last_lit&&(fb(s,!1),s.strm.avail_out===0)?w0:Jie}function YJn(s,t){for(var n;;){if(s.lookahead===0&&(gB(s),s.lookahead===0)){if(t===m9)return w0;break}if(s.match_length=0,n=rk._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,n&&(fb(s,!1),s.strm.avail_out===0))return w0}return s.insert=0,t===mL?(fb(s,!0),s.strm.avail_out===0?pB:tY):s.last_lit&&(fb(s,!1),s.strm.avail_out===0)?w0:Jie}function i5(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 dq;dq=[new i5(0,0,0,0,WJn),new i5(4,4,8,4,B$e),new i5(4,5,16,8,B$e),new i5(4,6,32,32,B$e),new i5(4,4,16,16,H$),new i5(8,16,32,32,H$),new i5(8,16,128,128,H$),new i5(8,32,128,256,H$),new i5(32,128,258,1024,H$),new i5(32,258,258,4096,H$)];function ZJn(s){s.window_size=2*s.w_size,AP(s.head),s.max_lazy_match=dq[s.level].max_lazy,s.good_match=dq[s.level].good_length,s.nice_match=dq[s.level].nice_length,s.max_chain_length=dq[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=Qu-1,s.match_available=0,s.ins_h=0}function XJn(){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=zDe,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 d_.Buf16(UJn*2),this.dyn_dtree=new d_.Buf16((2*BJn+1)*2),this.bl_tree=new d_.Buf16((2*$Jn+1)*2),AP(this.dyn_ltree),AP(this.dyn_dtree),AP(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new d_.Buf16(qJn+1),this.heap=new d_.Buf16(2*LXe+1),AP(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new d_.Buf16(2*LXe+1),AP(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 mas(s){var t;return!s||!s.state?jI(s,ak):(s.total_in=s.total_out=0,s.data_type=LJn,t=s.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?BDe:_8,s.adler=t.wrap===2?0:1,t.last_flush=m9,rk._tr_init(t),u4)}function fas(s){var t=mas(s);return t===u4&&ZJn(s.state),t}function QJn(s,t){return!s||!s.state||s.state.wrap!==2?ak:(s.state.gzhead=t,u4)}function pas(s,t,n,r,a,i){if(!s)return ak;var l=1;if(t===EJn&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>RJn||n!==zDe||r<8||r>15||t<0||t>9||i<0||i>PJn)return jI(s,ak);r===8&&(r=9);var o=new XJn;return s.state=o,o.strm=s,o.wrap=l,o.gzhead=null,o.w_bits=r,o.w_size=1<A3t||t<0)return s?jI(s,ak):ak;if(r=s.state,!s.output||!s.input&&s.avail_in!==0||r.status===zQ&&t!==mL)return jI(s,s.avail_out===0?z$e:ak);if(r.strm=s,n=r.last_flush,r.last_flush=t,r.status===BDe)if(r.wrap===2)s.adler=0,Fh(r,31),Fh(r,139),Fh(r,8),r.gzhead?(Fh(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)),Fh(r,r.gzhead.time&255),Fh(r,r.gzhead.time>>8&255),Fh(r,r.gzhead.time>>16&255),Fh(r,r.gzhead.time>>24&255),Fh(r,r.level===9?2:r.strategy>=Lue||r.level<2?4:0),Fh(r,r.gzhead.os&255),r.gzhead.extra&&r.gzhead.extra.length&&(Fh(r,r.gzhead.extra.length&255),Fh(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(s.adler=ZM(s.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=RXe):(Fh(r,0),Fh(r,0),Fh(r,0),Fh(r,0),Fh(r,0),Fh(r,r.level===9?2:r.strategy>=Lue||r.level<2?4:0),Fh(r,HJn),r.status=_8);else{var l=zDe+(r.w_bits-8<<4)<<8,o=-1;r.strategy>=Lue||r.level<2?o=0:r.level<6?o=1:r.level===6?o=2:o=3,l|=o<<6,r.strstart!==0&&(l|=VJn),l+=31-l%31,r.status=_8,fX(r,l),r.strstart!==0&&(fX(r,s.adler>>>16),fX(r,s.adler&65535)),s.adler=1}if(r.status===RXe)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=ZM(s.adler,r.pending_buf,r.pending-a,a)),XM(s),a=r.pending,r.pending===r.pending_buf_size));)Fh(r,r.gzhead.extra[r.gzindex]&255),r.gzindex++;r.gzhead.hcrc&&r.pending>a&&(s.adler=ZM(s.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=uAe)}else r.status=uAe;if(r.status===uAe)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=ZM(s.adler,r.pending_buf,r.pending-a,a)),XM(s),a=r.pending,r.pending===r.pending_buf_size)){i=1;break}r.gzindexa&&(s.adler=ZM(s.adler,r.pending_buf,r.pending-a,a)),i===0&&(r.gzindex=0,r.status=hAe)}else r.status=hAe;if(r.status===hAe)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=ZM(s.adler,r.pending_buf,r.pending-a,a)),XM(s),a=r.pending,r.pending===r.pending_buf_size)){i=1;break}r.gzindexa&&(s.adler=ZM(s.adler,r.pending_buf,r.pending-a,a)),i===0&&(r.status=mAe)}else r.status=mAe;if(r.status===mAe&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&XM(s),r.pending+2<=r.pending_buf_size&&(Fh(r,s.adler&255),Fh(r,s.adler>>8&255),s.adler=0,r.status=_8)):r.status=_8),r.pending!==0){if(XM(s),s.avail_out===0)return r.last_flush=-1,u4}else if(s.avail_in===0&&T3t(t)<=T3t(n)&&t!==mL)return jI(s,z$e);if(r.status===zQ&&s.avail_in!==0)return jI(s,z$e);if(s.avail_in!==0||r.lookahead!==0||t!==m9&&r.status!==zQ){var c=r.strategy===Lue?YJn(r,t):r.strategy===MJn?KJn(r,t):dq[r.level].func(r,t);if((c===pB||c===tY)&&(r.status=zQ),c===w0||c===pB)return s.avail_out===0&&(r.last_flush=-1),u4;if(c===Jie&&(t===SJn?rk._tr_align(r):t!==A3t&&(rk._tr_stored_block(r,0,0,!1),t===CJn&&(AP(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),XM(s),s.avail_out===0))return r.last_flush=-1,u4}return t!==mL?u4:r.wrap<=0?E3t:(r.wrap===2?(Fh(r,s.adler&255),Fh(r,s.adler>>8&255),Fh(r,s.adler>>16&255),Fh(r,s.adler>>24&255),Fh(r,s.total_in&255),Fh(r,s.total_in>>8&255),Fh(r,s.total_in>>16&255),Fh(r,s.total_in>>24&255)):(fX(r,s.adler>>>16),fX(r,s.adler&65535)),XM(s),r.wrap>0&&(r.wrap=-r.wrap),r.pending!==0?u4:E3t)}function ter(s){var t;return!s||!s.state?ak:(t=s.state.status,t!==BDe&&t!==RXe&&t!==uAe&&t!==hAe&&t!==mAe&&t!==_8&&t!==zQ?jI(s,ak):(s.state=null,t===_8?jI(s,AJn):u4))}function ser(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!==BDe||r.lookahead))return ak;for(l===1&&(s.adler=uas(s.adler,t,n,0)),r.wrap=0,n>=r.w_size&&(l===0&&(AP(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new d_.Buf8(r.w_size),d_.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,gB(r);r.lookahead>=Qu;){a=r.strstart,i=r.lookahead-(Qu-1);do r.ins_h=(r.ins_h<=252?6:AM>=248?5:AM>=240?4:AM>=224?3:AM>=192?2:1;_ne[254]=_ne[254]=1;f9.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 yas(s,t){if(t<65534&&(s.subarray&&xas||!s.subarray&&gas))return String.fromCharCode.apply(null,$De.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 yas(o,r)};f9.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+_ne[s[n]]>t?n:t};function ner(){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 vas=ner,ste=w3,nte=FT,DXe=f9,FXe=Got,rer=vas,bas=Object.prototype.toString,aer=0,$$e=4,BV=0,M3t=1,P3t=2,ier=-1,oer=0,ler=8;function xB(s){if(!(this instanceof xB))return new xB(s);this.options=nte.assign({level:ier,method:ler,chunkSize:16384,windowBits:15,memLevel:8,strategy:oer,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 rer,this.strm.avail_out=0;var n=ste.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==BV)throw new Error(FXe[n]);if(t.header&&ste.deflateSetHeader(this.strm,t.header),t.dictionary){var r;if(typeof t.dictionary=="string"?r=DXe.string2buf(t.dictionary):bas.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=ste.deflateSetDictionary(this.strm,r),n!==BV)throw new Error(FXe[n]);this._dict_set=!0}}xB.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?$$e:aer,typeof s=="string"?n.input=DXe.string2buf(s):bas.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 nte.Buf8(r),n.next_out=0,n.avail_out=r),a=ste.deflate(n,i),a!==M3t&&a!==BV)return this.onEnd(a),this.ended=!0,!1;(n.avail_out===0||n.avail_in===0&&(i===$$e||i===P3t))&&(this.options.to==="string"?this.onData(DXe.buf2binstring(nte.shrinkBuf(n.output,n.next_out))):this.onData(nte.shrinkBuf(n.output,n.next_out)))}while((n.avail_in>0||n.avail_out===0)&&a!==M3t);return i===$$e?(a=ste.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===BV):(i===P3t&&(this.onEnd(BV),n.avail_out=0),!0)};xB.prototype.onData=function(s){this.chunks.push(s)};xB.prototype.onEnd=function(s){s===BV&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=nte.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function Wot(s,t){var n=new xB(t);if(n.push(s,!0),n.err)throw n.msg||FXe[n.err];return n.result}function cer(s,t){return t=t||{},t.raw=!0,Wot(s,t)}function der(s,t){return t=t||{},t.gzip=!0,Wot(s,t)}Xie.Deflate=xB;Xie.deflate=Wot;Xie.deflateRaw=cer;Xie.gzip=der;var eoe={},TC={},Rue=30,uer=12,her=function(t,n){var r,a,i,l,o,c,d,u,h,m,f,g,x,v,y,b,w,S,A,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,v=r.lencode,y=r.distcode,b=(1<>>24,g>>>=A,x-=A,A=S>>>16&255,A===0)O[l++]=S&65535;else if(A&16){E=S&65535,A&=15,A&&(x>>=A,x-=A),x<15&&(g+=D[a++]<>>24,g>>>=A,x-=A,A=S>>>16&255,A&16){if(I=S&65535,A&=15,xd){t.msg="invalid distance too far back",r.mode=Rue;break e}if(g>>>=A,x-=A,A=l-o,I>A){if(A=I-A,A>h&&r.sane){t.msg="invalid distance too far back",r.mode=Rue;break e}if(P=0,R=f,m===0){if(P+=u-A,A2;)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(A&64){t.msg="invalid distance code",r.mode=Rue;break e}else{S=y[(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===D3t||f!==1))return-1;for(W[1]=0,u=1;uL3t||t===F3t&&b>R3t)return 1;for(;;){Z=u-v,o[h]O?(X=V[G+o[h]],ae=R[D+o[h]]):(X=96,ae=0),S=1<>v)+A]=Z<<24|X<<16|ae|0;while(A!==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(v===0&&(v=g),P+=m,x=u-v,y=1<L3t||t===F3t&&b>R3t)return 1;E=w&I,i[E]=g<<24|x<<16|P-l|0}}return w!==0&&(i[P+w]=u-v<<24|64<<16|0),c.bits=g,0},Jj=FT,OXe=cas,o5=das,yer=her,rte=xer,ver=0,_as=1,was=2,O3t=4,ber=5,Due=6,yB=0,_er=1,wer=2,pk=-2,jas=-3,Nas=-4,jer=-5,z3t=8,kas=1,B3t=2,$3t=3,U3t=4,q3t=5,V3t=6,H3t=7,G3t=8,W3t=9,K3t=10,_Pe=11,cA=12,q$e=13,Y3t=14,V$e=15,Z3t=16,X3t=17,Q3t=18,J3t=19,Fue=20,Oue=21,eAt=22,tAt=23,sAt=24,nAt=25,rAt=26,H$e=27,aAt=28,iAt=29,Dp=30,Sas=31,Ner=32,ker=852,Ser=592,Cer=15,Aer=Cer;function oAt(s){return(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24)}function Eer(){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 Jj.Buf16(320),this.work=new Jj.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Cas(s){var t;return!s||!s.state?pk:(t=s.state,s.total_in=s.total_out=t.total=0,s.msg="",t.wrap&&(s.adler=t.wrap&1),t.mode=kas,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Jj.Buf32(ker),t.distcode=t.distdyn=new Jj.Buf32(Ser),t.sane=1,t.back=-1,yB)}function Aas(s){var t;return!s||!s.state?pk:(t=s.state,t.wsize=0,t.whave=0,t.wnext=0,Cas(s))}function Eas(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))?pk:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,Aas(s))}function Tas(s,t){var n,r;return s?(r=new Eer,s.state=r,r.window=null,n=Eas(s,t),n!==yB&&(s.state=null),n):pk}function Ter(s){return Tas(s,Aer)}var lAt=!0,G$e,W$e;function Mer(s){if(lAt){var t;for(G$e=new Jj.Buf32(512),W$e=new Jj.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(rte(_as,s.lens,0,288,G$e,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;rte(was,s.lens,0,32,W$e,0,s.work,{bits:5}),lAt=!1}s.lencode=G$e,s.lenbits=9,s.distcode=W$e,s.distbits=5}function Mas(s,t,n,r){var a,i=s.state;return i.window===null&&(i.wsize=1<=i.wsize?(Jj.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),Jj.arraySet(i.window,t,n-r,a,i.wnext),r-=a,r?(Jj.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=o5(n.check,R,2,0),d=0,u=0,n.mode=B3t;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=Dp;break}if((d&15)!==z3t){s.msg="unknown compression method",n.mode=Dp;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=Dp;break}n.dmax=1<>8&1),n.flags&512&&(R[0]=d&255,R[1]=d>>>8&255,n.check=o5(n.check,R,2,0)),d=0,u=0,n.mode=$3t;case $3t: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=U3t;case U3t: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=o5(n.check,R,2,0)),d=0,u=0,n.mode=q3t;case q3t: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=V3t;case V3t: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)),Jj.arraySet(n.head.extra,r,i,f,I)),n.flags&512&&(n.check=o5(n.check,r,f,i)),o-=f,i+=f,n.length-=f),n.length))break e;n.length=0,n.mode=H3t;case H3t: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 K3t:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=H$e;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=Y3t;break;case 1:if(Mer(n),n.mode=Fue,t===Due){d>>>=2,u-=2;break e}break;case 2:n.mode=X3t;break;case 3:s.msg="invalid block type",n.mode=Dp}d>>>=2,u-=2;break;case Y3t: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=Dp;break}if(n.length=d&65535,d=0,u=0,n.mode=V$e,t===Due)break e;case V$e:n.mode=Z3t;case Z3t:if(f=n.length,f){if(f>o&&(f=o),f>c&&(f=c),f===0)break e;Jj.arraySet(a,r,i,f,l),o-=f,i+=f,c-=f,l+=f,n.length-=f;break}n.mode=cA;break;case X3t: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=Dp;break}n.have=0,n.mode=Q3t;case Q3t: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=rte(ver,n.lens,0,19,n.lencode,0,n.work,D),n.lenbits=D.bits,P){s.msg="invalid code lengths set",n.mode=Dp;break}n.have=0,n.mode=J3t;case J3t:for(;n.have>>24,b=v>>>16&255,w=v&65535,!(y<=u);){if(o===0)break e;o--,d+=r[i++]<>>=y,u-=y,n.lens[n.have++]=w;else{if(w===16){for(O=y+2;u>>=y,u-=y,n.have===0){s.msg="invalid bit length repeat",n.mode=Dp;break}I=n.lens[n.have-1],f=3+(d&3),d>>>=2,u-=2}else if(w===17){for(O=y+3;u>>=y,u-=y,I=0,f=3+(d&7),d>>>=3,u-=3}else{for(O=y+7;u>>=y,u-=y,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=Dp;break}for(;f--;)n.lens[n.have++]=I}}if(n.mode===Dp)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Dp;break}if(n.lenbits=9,D={bits:n.lenbits},P=rte(_as,n.lens,0,n.nlen,n.lencode,0,n.work,D),n.lenbits=D.bits,P){s.msg="invalid literal/lengths set",n.mode=Dp;break}if(n.distbits=6,n.distcode=n.distdyn,D={bits:n.distbits},P=rte(was,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,D),n.distbits=D.bits,P){s.msg="invalid distances set",n.mode=Dp;break}if(n.mode=Fue,t===Due)break e;case Fue:n.mode=Oue;case Oue: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,yer(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;v=n.lencode[d&(1<>>24,b=v>>>16&255,w=v&65535,!(y<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],y=v>>>24,b=v>>>16&255,w=v&65535,!(S+y<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=y,u-=y,n.back+=y,n.length=w,b===0){n.mode=rAt;break}if(b&32){n.back=-1,n.mode=cA;break}if(b&64){s.msg="invalid literal/length code",n.mode=Dp;break}n.extra=b&15,n.mode=eAt;case eAt:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=tAt;case tAt:for(;v=n.distcode[d&(1<>>24,b=v>>>16&255,w=v&65535,!(y<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],y=v>>>24,b=v>>>16&255,w=v&65535,!(S+y<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=y,u-=y,n.back+=y,b&64){s.msg="invalid distance code",n.mode=Dp;break}n.offset=w,n.extra=b&15,n.mode=sAt;case sAt: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=Dp;break}n.mode=nAt;case nAt: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=Dp;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=Oue);break;case rAt:if(c===0)break e;a[l++]=n.length,c--,n.mode=Oue;break;case H$e: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 Oer,this.strm.avail_out=0;var n=$V.inflateInit2(this.strm,t.windowBits);if(n!==Gx.Z_OK)throw new Error(zXe[n]);if(this.header=new zer,$V.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=fAe.string2buf(t.dictionary):Ias.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=$V.inflateSetDictionary(this.strm,t.dictionary),n!==Gx.Z_OK)))throw new Error(zXe[n])}vB.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?Gx.Z_FINISH:Gx.Z_NO_FLUSH,typeof s=="string"?n.input=fAe.binstring2buf(s):Ias.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 ate.Buf8(r),n.next_out=0,n.avail_out=r),i=$V.inflate(n,Gx.Z_NO_FLUSH),i===Gx.Z_NEED_DICT&&a&&(i=$V.inflateSetDictionary(this.strm,a)),i===Gx.Z_BUF_ERROR&&u===!0&&(i=Gx.Z_OK,u=!1),i!==Gx.Z_STREAM_END&&i!==Gx.Z_OK)return this.onEnd(i),this.ended=!0,!1;n.next_out&&(n.avail_out===0||i===Gx.Z_STREAM_END||n.avail_in===0&&(l===Gx.Z_FINISH||l===Gx.Z_SYNC_FLUSH))&&(this.options.to==="string"?(o=fAe.utf8border(n.output,n.next_out),c=n.next_out-o,d=fAe.buf2string(n.output,o),n.next_out=c,n.avail_out=r-c,c&&ate.arraySet(n.output,n.output,o,c,0),this.onData(d)):this.onData(ate.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!==Gx.Z_STREAM_END);return i===Gx.Z_STREAM_END&&(l=Gx.Z_FINISH),l===Gx.Z_FINISH?(i=$V.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Gx.Z_OK):(l===Gx.Z_SYNC_FLUSH&&(this.onEnd(Gx.Z_OK),n.avail_out=0),!0)};vB.prototype.onData=function(s){this.chunks.push(s)};vB.prototype.onEnd=function(s){s===Gx.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=ate.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function Kot(s,t){var n=new vB(t);if(n.push(s,!0),n.err)throw n.msg||zXe[n.err];return n.result}function Ber(s,t){return t=t||{},t.raw=!0,Kot(s,t)}eoe.Inflate=vB;eoe.inflate=Kot;eoe.inflateRaw=Ber;eoe.ungzip=Kot;var $er=FT.assign,Uer=Xie,qer=eoe,Ver=Pas,Las={};$er(Las,Uer,qer,Ver);var Her=Las;const UDe=ru(Her);var cAt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",BQ=new Uint8Array(256);for(var zue=0;zue>4,d[a++]=(l&15)<<4|o>>2,d[a++]=(o&3)<<6|c&63;return d},Wer=function(s){for(var t="",n=0;nr)throw new Error(u0(t)+" must be at least "+n+" and at most "+r+", but was actually "+s)},rS=function(s,t,n,r){Cr(s,t,["number","undefined"]),typeof s=="number"&&e2(s,t,n,r)},Fas=function(s,t,n){if(Cr(s,t,["number"]),s%n!==0)throw new Error(u0(t)+" must be a multiple of "+n+", but was actually "+s)},btr=function(s,t){if(!Number.isInteger(s))throw new Error(u0(t)+" must be an integer, but was actually "+s)},VDe=function(s,t){if(![1,0].includes(Math.sign(s)))throw new Error(u0(t)+" must be a positive number or 0, but was actually "+s)},Kc=new Uint16Array(256);for(var Uue=0;Uue<256;Uue++)Kc[Uue]=Uue;Kc[22]=Oc("");Kc[24]=Oc("˘");Kc[25]=Oc("ˇ");Kc[26]=Oc("ˆ");Kc[27]=Oc("˙");Kc[28]=Oc("˝");Kc[29]=Oc("˛");Kc[30]=Oc("˚");Kc[31]=Oc("˜");Kc[127]=Oc("�");Kc[128]=Oc("•");Kc[129]=Oc("†");Kc[130]=Oc("‡");Kc[131]=Oc("…");Kc[132]=Oc("—");Kc[133]=Oc("–");Kc[134]=Oc("ƒ");Kc[135]=Oc("⁄");Kc[136]=Oc("‹");Kc[137]=Oc("›");Kc[138]=Oc("−");Kc[139]=Oc("‰");Kc[140]=Oc("„");Kc[141]=Oc("“");Kc[142]=Oc("”");Kc[143]=Oc("‘");Kc[144]=Oc("’");Kc[145]=Oc("‚");Kc[146]=Oc("™");Kc[147]=Oc("fi");Kc[148]=Oc("fl");Kc[149]=Oc("Ł");Kc[150]=Oc("Œ");Kc[151]=Oc("Š");Kc[152]=Oc("Ÿ");Kc[153]=Oc("Ž");Kc[154]=Oc("ı");Kc[155]=Oc("ł");Kc[156]=Oc("œ");Kc[157]=Oc("š");Kc[158]=Oc("ž");Kc[159]=Oc("�");Kc[160]=Oc("€");Kc[173]=Oc("�");var Oas=function(s){for(var t=new Array(s.length),n=0,r=s.length;n=un.ExclamationPoint&&s<=un.Tilde&&!Qot[s]},gAt={},xAt=new Map,tn=function(s){Si(t,s);function t(n,r){var a=this;if(n!==gAt)throw new Yot("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+=mb(this.encodedName,n,r),this.encodedName.length},t.of=function(n){var r=Otr(n),a=xAt.get(r);return a||(a=new t(gAt,r),xAt.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}(S_),Btr=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}(S_);const hw=new Btr;var ld=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===hw&&!r))return a},t.prototype.has=function(n){var r=this.dict.get(n);return r!==void 0&&r!==hw},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,rm.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:rm.of(0,65535),offset:0,deleted:!0})},s.createEmpty=function(){return new s},s}(),elt=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+=mb(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}(),qtr=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}(),$as=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(tn.of("Type"),tn.of("ObjStm")),i.dict.set(tn.of("N"),Ac.of(i.objects.length)),i.dict.set(tn.of("First"),Ac.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),v>o[2]&&(o[2]=v)}return o},i.entries=r||[],i.entryTuplesCache=WE.populatedBy(i.computeEntryTuples),i.maxByteWidthsCache=WE.populatedBy(i.computeMaxEntryByteWidths),i.indexCache=WE.populatedBy(i.computeIndex),n.set(tn.of("Type"),tn.of("XRef")),i}return t.prototype.addDeletedEntry=function(n,r){var a=xP.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=xP.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=xP.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=VQn(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(tn.of("W"),a.obj(n)),this.dict.set(tn.of("Index"),a.obj(r))},t.create=function(n,r){r===void 0&&(r=!0);var a=new t(n,[],r);return a.addDeletedEntry(rm.of(0,65535),0),a},t.of=function(n,r,a){return a===void 0&&(a=!0),new t(n,r,a)},t}(Jot),Htr=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 fd(this,void 0,void 0,function(){var n,r,a,i,l,o,c,d,g,x,u,y,h,m,v,f,g,x,v,y,b,w,S,A;return pd(this,function(E){switch(E.label){case 0:n=this.context.largestObjectNumber+1,r=HDe.forVersion(1,7),a=r.sizeInBytes()+2,i=Vtr.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+=mb(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=KQn(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`},_At=function(){for(var s=[],t=0;t"},pAe=function(s){return Kie(s,4)},Ktr=function(s){if(YQn(s))return pAe(s);if(ZQn(s)){var t=Urs(s),n=qrs(s);return""+pAe(t)+pAe(n)}var r=ODe(s),a="0x"+r+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(a)},Ytr=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 Wrs(n)?Vrs(n):Oas(n)},t.prototype.decodeDate=function(){var n=this.decodeText(),r=Brs(n);if(!r)throw new zas(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+=mb(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=OS(String(n.getUTCFullYear()),4,"0"),a=OS(String(n.getUTCMonth()+1),2,"0"),i=OS(String(n.getUTCDate()),2,"0"),l=OS(String(n.getUTCHours()),2,"0"),o=OS(String(n.getUTCMinutes()),2,"0"),c=OS(String(n.getUTCSeconds()),2,"0");return new t("D:"+r+a+i+l+o+c+"Z")},t}(S_),tlt=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-(Z&7)&1),X=W==v*255?0:255;c[G+Z]=X<<24|W<<16|W<<8|W}else if(u==2)for(var Z=0;Z>>2)]>>>6-((Z&3)<<1)&3),X=W==v*85?0:255;c[G+Z]=X<<24|W<<16|W<<8|W}else if(u==4)for(var Z=0;Z>>1)]>>>4-((Z&1)<<2)&15),X=W==v*17?0:255;c[G+Z]=X<<24|W<<16|W<<8|W}else if(u==8)for(var Z=0;Z>>2<<3));a==0;){if(a=v(t,m,1),i=v(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=y(t,m,5)+257,o=y(t,m+5,5)+1,c=y(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(!(Z>>>8))n[h++]=Z;else{if(Z==256)break;var X=h+Z-254;if(Z>264){var ae=E.q[Z-257];X=h+(ae>>>3)+y(t,m,ae&7),m+=ae&7}var le=g[A(t,m)&u];m+=le&15;var re=le>>>4,te=E.c[re],J=(te>>>4)+v(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}();Ja.decode._readInterlace=function(s,t){for(var n=t.width,r=t.height,a=Ja.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],v=0,y=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}A++,E+=g}v*y!=0&&(c+=y*(1+S)),f=f+1}return o};Ja.decode._getBPP=function(s){var t=[1,null,3,1,2,null,4][s.ctype];return t*s.depth};Ja.decode._filterZero=function(s,t,n,r,a){var i=Ja.decode._getBPP(t),l=Math.ceil(r*i/8),o=Ja.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,v=s[h]*x,y=s[h+1]*x,b=s[h+2]*x,w=r[m+3]*(1/255),S=r[m]*w,A=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]=(v+S*I)*R,r[m+1]=(y+A*I)*R,r[m+2]=(b+E*I)*R}else if(c==2){var x=s[h+3],v=s[h],y=s[h+1],b=s[h+2],w=r[m+3],S=r[m],A=r[m+1],E=r[m+2];x==w&&v==S&&y==A&&b==E?(r[m]=0,r[m+1]=0,r[m+2]=0,r[m+3]=0):(r[m]=v,r[m+1]=y,r[m+2]=b,r[m+3]=x)}else if(c==3){var x=s[h+3],v=s[h],y=s[h+1],b=s[h+2],w=r[m+3],S=r[m],A=r[m+1],E=r[m+2];if(x==w&&v==S&&y==A&&b==E)continue;if(x<220&&w>20)return!1}return!0};Ja.encode=function(s,t,n,r,a,i,l){r==null&&(r=0),l==null&&(l=!1);var o=Ja.encode.compress(s,t,n,r,[!1,!1,!1,0,l]);return Ja.encode.compressPNG(o,-1),Ja.encode._main(o,t,n,a,i)};Ja.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;y[d+w+0]=A,y[d+w+1]=E,y[d+w+2]=I}if(d+=f*3,l(y,d,i(y,d-f*3-4,f*3+4)),d+=4,h){l(y,d,f),d+=4,c(y,d,"tRNS"),d+=4;for(var g=0;g>>24&255;d+=f,l(y,d,i(y,d-f-4,f+4)),d+=4}}for(var P=0,x=0;x>2,U>>2));for(var f=0;fG&&X==V[v-G])Z[v]=Z[v-G];else{var ae=w[X];if(ae==null&&(w[X]=ae=S.length,S.push(X),S.length>=300))break;Z[v]=ae}}}var le=S.length;le<=256&&d==!1&&(le<=2?h=1:le<=4?h=2:le<=16?h=4:h=8,h=Math.max(h,c));for(var f=0;f>1)]|=fe[be+Ee]<<4-(Ee&1)*4;else if(h==2)for(var Ee=0;Ee>2)]|=fe[be+Ee]<<6-(Ee&3)*2;else if(h==1)for(var Ee=0;Ee>3)]|=fe[be+Ee]<<7-(Ee&7)*1}te=ve,u=3,ce=1}else if(y==!1&&b.length==1){for(var ve=new Uint8Array(G*re*3),ke=G*re,v=0;vI&&(I=D),RP&&(P=R))}I==-1&&(A=E=I=P=0),a&&((A&1)==1&&A--,(E&1)==1&&E--);var U=(I-A+1)*(P-E+1);Uv&&(v=S),Ay&&(y=A))}v==-1&&(g=x=v=y=0),l&&((g&1)==1&&g--,(x&1)==1&&x--),i={x:g,y:x,width:v-g+1,height:y-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?(Ja._copyTile(d,t,n,P.img,i.width,i.height,-i.x,-i.y,0),Ja.encode._prepareDiff(m,t,n,P.img,i)):Ja._copyTile(m,t,n,P.img,i.width,i.height,-i.x,-i.y,0)};Ja.encode._prepareDiff=function(s,t,n,r,a){Ja._copyTile(s,t,n,r,a.width,a.height,-a.x,-a.y,2)};Ja.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:UDe,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 Ja.crc.update(4294967295,s,t,n)^4294967295}};Ja.quantize=function(s,t){var n=new Uint8Array(s),r=n.slice(0),a=new Uint32Array(r.buffer),i=Ja.quantize.getKDtree(r,t),l=i[0],o=i[1];Ja.quantize.planeDst;for(var c=n,d=a,u=c.length,h=new Uint8Array(n.length>>2),m=0;m>2]=y.ind,d[m>>2]=y.est.rgba}return{abuf:r.buffer,inds:h,plte:o}};Ja.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=Ja.quantize.stats(s,a.i0,a.i1),a.est=Ja.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=Ja.quantize.stats(s,m.i0,m.i1),m.est=Ja.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=Ja.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=Ja.quantize.getNearest(l,t,n,r,a);if(c.tdst<=i*i)return c;var d=Ja.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};Ja.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]};Ja.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}};Ja.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]]}};Ja.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=tsr(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=esr(n.ctype),this.width=n.width,this.height=n.height,this.bitsPerComponent=8}return s.load=function(t){return new s(t)},s}(),Has=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 fd(this,void 0,void 0,function(){var n;return pd(this,function(r){return n=ssr.load(t),[2,new s(n)]})})},s.prototype.embedIntoContext=function(t,n){return fd(this,void 0,void 0,function(){var r,a;return pd(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}(),Gas=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}(),nsr=new Uint8Array(0),toe=function(){function s(t){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=nsr,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 Gas(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 qN(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}(toe),asr=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}(toe),NAt=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),isr=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]),osr=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]),lsr=[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],csr=[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],dsr=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;)A[b++]=P}m=this.generateHuffmanTable(A.subarray(0,g)),f=this.generateHuffmanTable(A.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=isr[W];var V=W>>16;V>0&&(V=this.getBits(V)),r=(W&65535)+V,W=this.getCode(f),W=osr[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 Z=0;Z>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(!A||A<256)v[0]=A,y=1;else if(A>=258)if(A=0;l--)v[l]=h[o],o=f[o];else v[y++]=v[0];else if(A===256){g=9,u=258,y=0;continue}else{this.eof=!0,delete this.lzwState;break}if(E&&(f[u]=x,m[u]=m[x]+1,h[u]=v[0],u++,g=u+d&u+d-1?g:Math.min(Math.log(u+d)/.6931471805599453+1,12)|0),x=A,b+=y,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 jPe(n,0,r.size());r.remove(n)}else{if(n!==0)throw new jPe(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(tn.of("Kids"),n)),{Kids:n}},t.fromDict=function(n,r){return new t(n,r)},t}(Yas),slt=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.Opt=function(){return this.dict.lookupMaybe(tn.of("Opt"),sm,mc,jh)},t.prototype.setOpt=function(n){this.dict.set(tn.of("Opt"),this.dict.context.obj(n))},t.prototype.getExportValues=function(){var n=this.Opt();if(n){if(n instanceof sm||n instanceof mc)return[n];for(var r=[],a=0,i=n.size();ar.size())throw new jPe(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(Jh.MultiSelect))throw new Str;this.dict.set(tn.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,sm,mc),c=l.lookupMaybe(1,sm,mc);r.push({value:o,display:c||o})}}return r}return[]},t}(sY),WDe=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:Jh.Combo,Kids:[]}),a=n.register(r);return new t(r,a)},t}(Zas),SPe=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(tn.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}(Yas),nlt=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}(sY),KDe=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(tn.of("MaxLen"));if(n instanceof Ac)return n},t.prototype.Q=function(){var n=this.dict.lookup(tn.of("Q"));if(n instanceof Ac)return n},t.prototype.setMaxLength=function(n){this.dict.set(tn.of("MaxLen"),Ac.of(n))},t.prototype.removeMaxLength=function(){this.dict.delete(tn.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(tn.of("Q"),Ac.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(tn.of("V"),n)},t.prototype.removeValue=function(){this.dict.delete(tn.of("V"))},t.prototype.getValue=function(){var n=this.V();if(n instanceof sm||n instanceof mc)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}(sY),YDe=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:AN.PushButton,Kids:[]}),a=n.register(r);return new t(r,a)},t}(slt),ZDe=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!==tn.of("Off"))throw new Xot;this.dict.set(tn.of("V"),n);for(var a=this.getWidgets(),i=0,l=a.length;ii)throw new mAt(r,i);for(var l=r,o=0,c=a.size();ol)return u.insertLeafNode(n,l)||d;l-=u.Count().asNumber()}u instanceof KE&&(l-=1)}if(l===0){this.insertLeafKid(a.size(),n);return}throw new fAt(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 mAt(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 KE)if(l===0){this.removeKid(o);return}else l-=1}throw new fAt(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()&&OT[this.bytes.peek()];)this.bytes.next()},s.prototype.skipLine=function(){for(;!this.bytes.done();){var t=this.bytes.peek();if(t===CAt||t===AAt)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===CAt||t===AAt)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(Was(t).decode())},s}(),jsr=un.Space,xX=un.CarriageReturn,yX=un.Newline,vX=[un.s,un.t,un.r,un.e,un.a,un.m],Vue=[un.e,un.n,un.d,un.s,un.t,un.r,un.e,un.a,un.m],Gm={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:vX,streamEOF1:Ju(vX,[jsr,xX,yX]),streamEOF2:Ju(vX,[xX,yX]),streamEOF3:Ju(vX,[xX]),streamEOF4:Ju(vX,[yX]),endstream:Vue,EOF1endstream:Ju([xX,yX],Vue),EOF2endstream:Ju([xX],Vue),EOF3endstream:Ju([yX],Vue)},tis=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(Gm.true))return jne.True;if(this.matchKeyword(Gm.false))return jne.False;if(this.matchKeyword(Gm.null))return hw;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(ilt[n])return this.parseNumberOrRef();throw new Ttr(this.bytes.position(),n)},t.prototype.parseNumberOrRef=function(){var n=this.parseRawNumber();this.skipWhitespaceAndComments();var r=this.bytes.offset();if(S1[this.bytes.peek()]){var a=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===un.R)return this.bytes.assertNext(un.R),rm.of(n,a)}return this.bytes.moveTo(r),Ac.of(n)},t.prototype.parseHexString=function(){var n="";for(this.bytes.assertNext(un.LessThan);!this.bytes.done()&&this.bytes.peek()!==un.GreaterThan;)n+=GE(this.bytes.next());return this.bytes.assertNext(un.GreaterThan),mc.of(n)},t.prototype.parseString=function(){for(var n=0,r=!1,a="";!this.bytes.done();){var i=this.bytes.next();if(a+=GE(i),r||(i===un.LeftParen&&(n+=1),i===un.RightParen&&(n-=1)),i===un.BackSlash?r=!r:r&&(r=!1),n===0)return sm.of(a.substring(1,a.length-1))}throw new Itr(this.bytes.position())},t.prototype.parseName=function(){this.bytes.assertNext(un.ForwardSlash);for(var n="";!this.bytes.done();){var r=this.bytes.peek();if(OT[r]||Tk[r])break;n+=GE(r),this.bytes.next()}return tn.of(n)},t.prototype.parseArray=function(){this.bytes.assertNext(un.LeftSquareBracket),this.skipWhitespaceAndComments();for(var n=jh.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(tn.of("Type"));return i===tn.of("Catalog")?Jas.fromMapWithContext(n,this.context):i===tn.of("Pages")?eis.fromMapWithContext(n,this.context):i===tn.of("Page")?KE.fromMapWithContext(n,this.context):ld.fromMapWithContext(n,this.context)},t.prototype.parseDictOrStream=function(){var n=this.bytes.position(),r=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(Gm.streamEOF1)&&!this.matchKeyword(Gm.streamEOF2)&&!this.matchKeyword(Gm.streamEOF3)&&!this.matchKeyword(Gm.streamEOF4)&&!this.matchKeyword(Gm.stream))return r;var a=this.bytes.offset(),i,l=r.get(tn.of("Length"));l instanceof Ac?(i=a+l.asNumber(),this.bytes.moveTo(i),this.skipWhitespaceAndComments(),this.matchKeyword(Gm.endstream)||(this.bytes.moveTo(a),i=this.findEndOfStreamFallback(n))):i=this.findEndOfStreamFallback(n);var o=this.bytes.slice(a,i);return Nne.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(Gm.stream)?r+=1:this.matchKeyword(Gm.EOF1endstream)||this.matchKeyword(Gm.EOF2endstream)||this.matchKeyword(Gm.EOF3endstream)||this.matchKeyword(Gm.endstream)?r-=1:this.bytes.next(),r!==0););if(r!==0)throw new Ptr(n);return a},t.forBytes=function(n,r,a){return new t(JDe.of(n),r,a)},t.forByteStream=function(n,r,a){return a===void 0&&(a=!1),new t(n,r,a)},t}(wsr),Nsr=function(s){Si(t,s);function t(n,r){var a=s.call(this,JDe.fromPDFRawStream(n),n.dict.context)||this,i=n.dict;return a.alreadyParsed=!1,a.shouldWaitForTick=r||function(){return!1},a.firstOffset=i.lookup(tn.of("First"),Ac).asNumber(),a.objectCount=i.lookup(tn.of("N"),Ac).asNumber(),a}return t.prototype.parseIntoContext=function(){return fd(this,void 0,void 0,function(){var n,r,a,i,l,o,c,d;return pd(this,function(u){switch(u.label){case 0:if(this.alreadyParsed)throw new Zot("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(Gm.xref)||this.matchKeyword(Gm.trailer)||this.matchKeyword(Gm.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}(tis),l5=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},zsr=function(s){al=il=Pu=Iu=$Q=UQ=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,v=h/r,y=f*o+g*c,b=x*o+v*c,w=f*s+g*t,S=x*s+v*t,A=(w-y)*(w-y)+(S-b)*(S-b),E=1/A-.25;E<0&&(E=0);var I=Math.sqrt(E);i===a&&(I=-I);var P=.5*(y+w)-I*(S-b),R=.5*(b+S)+I*(w-y),D=Math.atan2(b-R,y-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 v=t.heightAtSize(a),y=v+v*.2,b=y*i;if(b>Math.abs(n.height))return a-1;a+=1}return a},onr=function(s,t,n,r){for(var a=n.width/r,i=n.height,l=vis,o=DQn(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},lnr=function(s){for(var t=s.length;t>0;t--)if(/\s/.test(s[t]))return t},cnr=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+A),g+o>f&&(f=g+o),d.push({text:w,encoded:S,width:A,height:o,x:I,y:g}),y=E==null?void 0:E.trim()}return{fontSize:r,lineHeight:c,lines:d,bounds:{x:u,y:h,width:m-u,height:f-h}}},dnr=function(s,t){var n=t.fontSize,r=t.font,a=t.bounds,i=t.cellCount,l=Ors(Yie(s));if(l.length>i)throw new rnr(l.length,i);(n===void 0||n===0)&&(n=onr(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,v=0;xf&&(f=I+A),d+c>g&&(g=d+c),u.push({text:l,encoded:S,width:A,height:c,x:I,y:d}),x+=1,v+=w}return{fontSize:n,cells:u,bounds:{x:h,y:m,width:f-h,height:g-m}}},PPe=function(s,t){var n=t.alignment,r=t.fontSize,a=t.font,i=t.bounds,l=Ors(Yie(s));(r===void 0||r===0)&&(r=_is([l],a,i));var o=a.encodeText(l),c=a.widthOfTextAtSize(l,r),d=a.heightAtSize(r,{descender:!1}),u=n===g0.Left?i.x:n===g0.Center?i.x+i.width/2-c/2:n===g0.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}}},rY=function(s){return"normal"in s?s:{normal:s}},unr=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,qL=function(s){var t,n,r=(t=s.getDefaultAppearance())!==null&&t!==void 0?t:"",a=(n=$ot(r,unr).match)!==null&&n!==void 0?n:[],i=Number(a[2]);return isFinite(i)?i:void 0},hnr=/(\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)/,gk=function(s){var t,n=(t=s.getDefaultAppearance())!==null&&t!==void 0?t:"",r=$ot(n,hnr).match,a=r??[],i=a[1],l=a[2],o=a[3],c=a[4],d=a[5];if(d==="g"&&i)return fis(Number(i));if(d==="rg"&&i&&l&&o)return Sh(Number(i),Number(l),Number(o));if(d==="k"&&i&&l&&o&&c)return pis(Number(i),Number(l),Number(o),Number(c))},xk=function(s,t,n,r){var a;r===void 0&&(r=0);var i=[x9(t).toString(),dlt((a=n==null?void 0:n.name)!==null&&a!==void 0?a:"dummy__noop",r).toString()].join(` `);s.setDefaultAppearance(i)},mnr=function(s,t){var n,r,a,i=gk(t),l=gk(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=zT(c==null?void 0:c.getRotation()),m=p9(o,h),f=m.width,g=m.height,x=M6(qc(qc({},o),{rotation:h})),v=Sh(0,0,0),y=(r=C_(c==null?void 0:c.getBorderColor()))!==null&&r!==void 0?r:v,b=C_(c==null?void 0:c.getBackgroundColor()),w=C_(c==null?void 0:c.getBackgroundColor(),.8),S=(a=i??l)!==null&&a!==void 0?a:v;xk(i?t:s.acroField,S);var A={x:0+u/2,y:0+u/2,width:f-u,height:g-u,thickness:1.5,borderWidth:u,borderColor:y,markColor:S};return{normal:{on:Ju(x,Wue(qc(qc({},A),{color:b,filled:!0}))),off:Ju(x,Wue(qc(qc({},A),{color:b,filled:!1})))},down:{on:Ju(x,Wue(qc(qc({},A),{color:w,filled:!0}))),off:Ju(x,Wue(qc(qc({},A),{color:w,filled:!1})))}}},fnr=function(s,t){var n,r,a,i=gk(t),l=gk(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=zT(c==null?void 0:c.getRotation()),m=p9(o,h),f=m.width,g=m.height,x=M6(qc(qc({},o),{rotation:h})),v=Sh(0,0,0),y=(r=C_(c==null?void 0:c.getBorderColor()))!==null&&r!==void 0?r:v,b=C_(c==null?void 0:c.getBackgroundColor()),w=C_(c==null?void 0:c.getBackgroundColor(),.8),S=(a=i??l)!==null&&a!==void 0?a:v;xk(i?t:s.acroField,S);var A={x:f/2,y:g/2,width:f-u,height:g-u,borderWidth:u,borderColor:y,dotColor:S};return{normal:{on:Ju(x,Kue(qc(qc({},A),{color:b,filled:!0}))),off:Ju(x,Kue(qc(qc({},A),{color:b,filled:!1})))},down:{on:Ju(x,Kue(qc(qc({},A),{color:w,filled:!0}))),off:Ju(x,Kue(qc(qc({},A),{color:w,filled:!1})))}}},pnr=function(s,t,n){var r,a,i,l,o,c=gk(t),d=gk(s.acroField),u=qL(t),h=qL(s.acroField),m=t.getRectangle(),f=t.getAppearanceCharacteristics(),g=t.getBorderStyle(),x=f==null?void 0:f.getCaptions(),v=(r=x==null?void 0:x.normal)!==null&&r!==void 0?r:"",y=(i=(a=x==null?void 0:x.down)!==null&&a!==void 0?a:v)!==null&&i!==void 0?i:"",b=(l=g==null?void 0:g.getWidth())!==null&&l!==void 0?l:0,w=zT(f==null?void 0:f.getRotation()),S=p9(m,w),A=S.width,E=S.height,I=M6(qc(qc({},m),{rotation:w})),P=Sh(0,0,0),R=C_(f==null?void 0:f.getBorderColor()),D=C_(f==null?void 0:f.getBackgroundColor()),O=C_(f==null?void 0:f.getBackgroundColor(),.8),U={x:b,y:b,width:A-b*2,height:E-b*2},W=PPe(v,{alignment:g0.Center,fontSize:u??h,font:n,bounds:U}),V=PPe(y,{alignment:g0.Center,fontSize:u??h,font:n,bounds:U}),G=Math.min(W.fontSize,V.fontSize),Z=(o=c??d)!==null&&o!==void 0?o:P;xk(c||u!==void 0?t:s.acroField,Z,n,G);var X={x:0+b/2,y:0+b/2,width:A-b,height:E-b,borderWidth:b,borderColor:R,textColor:Z,font:n.name,fontSize:G};return{normal:Ju(I,RAt(qc(qc({},X),{color:D,textLines:[W.line]}))),down:Ju(I,RAt(qc(qc({},X),{color:O,textLines:[V.line]})))}},gnr=function(s,t,n){var r,a,i,l,o=gk(t),c=gk(s.acroField),d=qL(t),u=qL(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,v=zT(m==null?void 0:m.getRotation()),y=p9(h,v),b=y.width,w=y.height,S=M6(qc(qc({},h),{rotation:v})),A=Sh(0,0,0),E=C_(m==null?void 0:m.getBorderColor()),I=C_(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=wis(g,{alignment:s.getAlignment(),fontSize:d??u,font:n,bounds:O});P=U.lines,R=U.fontSize}else if(s.isCombed()){var U=dnr(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=PPe(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:A;xk(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 Ju(S,xis(V))},xnr=function(s,t,n){var r,a,i,l=gk(t),o=gk(s.acroField),c=qL(t),d=qL(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=zT(h==null?void 0:h.getRotation()),v=p9(u,x),y=v.width,b=v.height,w=M6(qc(qc({},u),{rotation:x})),S=Sh(0,0,0),A=C_(h==null?void 0:h.getBorderColor()),E=C_(h==null?void 0:h.getBackgroundColor()),I=1,P={x:g+I,y:g+I,width:y-(g+I)*2,height:b-(g+I)*2},R=PPe(f,{alignment:g0.Left,fontSize:c??d,font:n,bounds:P}),D=R.line,O=R.fontSize,U=(i=l??o)!==null&&i!==void 0?i:S;xk(l||c!==void 0?t:s.acroField,U,n,O);var W={x:0+g/2,y:0+g/2,width:y-g,height:b-g,borderWidth:g??0,borderColor:A,textColor:U,font:n.name,fontSize:O,color:E,textLines:[D],padding:I};return Ju(w,xis(W))},ynr=function(s,t,n){var r,a,i=gk(t),l=gk(s.acroField),o=qL(t),c=qL(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=zT(u==null?void 0:u.getRotation()),g=p9(d,f),x=g.width,v=g.height,y=M6(qc(qc({},d),{rotation:f})),b=Sh(0,0,0),w=C_(u==null?void 0:u.getBorderColor()),S=C_(u==null?void 0:u.getBackgroundColor()),A=s.getOptions(),E=s.getSelected();s.isSorted()&&A.sort();for(var I="",P=0,R=A.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 anr(n.length,r,this.getName());this.markAsDirty(),this.disableRichFormatting(),n?this.acroField.setValue(mc.fromText(n)):this.acroField.removeValue()},t.prototype.getAlignment=function(){var n=this.acroField.getQuadding();return n===0?g0.Left:n===1?g0.Center:n===2?g0.Right:g0.Left},t.prototype.setAlignment=function(n){NI(n,"alignment",g0),this.markAsDirty(),this.acroField.setQuadding(n)},t.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},t.prototype.setMaxLength=function(n){if(rS(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 inr(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===g0.Center?fL.Center:r===g0.Right?fL.Right:fL.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:Nis(i),page:l}})}catch{r=[]}return{pageCount:n.length,hasAcroform:r.length>0,fields:r}}function DAt(s,t){return s.mapping_mode==="blank"?"":s.mapping_mode==="static"||!s.merge_key?s.static_value||"":t[s.merge_key]??""}async function kis(s,t,n){const r=await e3.load(s,{updateMetadata:!1}),a=await r.embedFont(jW.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=DAt(h,n),f=h.pdf_field_name;if(!m){l.push(f);continue}try{const g=u.getField(f),x=Nis(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=DAt(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:v}=g.getSize(),y=!!h.coords_normalized,b=Number(h.pos_x)*(y?x:1),w=Number(h.width??(y?.2:120))*(y?x:1),S=Number(h.height??(y?.03:18))*(y?v:1),A=Number(h.pos_y)*(y?v:1),E=y?v-A-S:A,I=Number(h.font_size)||(y?Math.min(11,Math.max(7,S*.7)):10);g.drawText(m,{x:y?b+1:b,y:y?E+Math.max(2,(S-I)/2):E,size:I,font:a,color:Sh(0,0,0),maxWidth:y?Math.max(10,w-2):void 0}),i[f]=m}}return{bytes:await r.save(),applied:i,skipped:l}}function glt(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 Sis=20*1024*1024,xlt=[{value:"purchase",label:"Purchase"},{value:"listing",label:"Listing"},{value:"disclosure",label:"Disclosure"},{value:"addendum",label:"Addendum"},{value:"other",label:"Other"}];function yx(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 ylt(s=!1){const t=Sa();return st({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 Snr(s,t=!1){return st({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 Cnr(){const s=Sa(),t=Zt();return mt({mutationFn:async({name:n,description:r,category:a,file:i,templateId:l,brokerageId:o})=>{var y;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>Sis)throw new Error("That PDF is larger than the 20MB limit.");let c;try{c=await knr(await i.arrayBuffer())}catch(b){throw new Error(glt(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=(((y=u==null?void 0:u[0])==null?void 0:y.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:v}=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(v)throw await q.storage.from("form-templates").remove([f]),v;return{templateId:d,version:x}},onSuccess:()=>{t.invalidateQueries({queryKey:["form-templates"]}),t.invalidateQueries({queryKey:["form-template"]})}})}function Cis(){const s=Zt();return mt({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 Anr(){const s=Sa(),t=Zt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r=yx(n);if(!r)throw new Error("That template has no uploaded PDF yet.");const a=await rFe(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:v,version_id:y,...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 Ais(){const s=Zt();return mt({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 rFe(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 tS(s){if(!s)return"";try{const t=kh(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 Enr(){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 Tnr(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 vlt(s){return s?s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`:"0 KB"}const NW=[{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"]}],Eis=new Map(NW.map(s=>[s.key,s])),Mnr={buyer:"Buyer",seller:"Seller",dual:"Dual",referral:"Referral",lease:"Lease"};function Pnr(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":Mnr[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":Tnr(l),"deal.contract_date":tS(t.contract_date),"deal.target_close_date":tS(t.target_close_date),"deal.actual_close_date":tS(t.actual_close_date),"deal.listing_date":tS(t.listing_date),"deal.inspection_date":tS(t.inspection_date),"deal.inspection_contingency_date":tS(t.inspection_contingency_date),"deal.appraisal_date":tS(t.appraisal_date),"deal.loan_approval_date":tS(t.loan_approval_date),"deal.earnest_money_due_date":tS(t.earnest_money_due_date),"deal.title_docs_due_date":tS(t.title_docs_due_date),"deal.final_walkthrough_date":tS(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:Enr()}}function blt(s){const t=Sa();return st({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:Pnr(o)}}})}function Inr(s){return st({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 Lnr(){const s=Sa(),t=Zt();return mt({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 rFe(a.storage_path);let d;try{d=await kis(c,l,i)}catch(w){throw new Error(glt(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:v,error:y}=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(y)throw y;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:v.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:v.id}}),{dealFile:v,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 aoe(s){return st({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 Rnr(){const s=Zt();return mt({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 Tis({open:s,onOpenChange:t,dealId:n,dealName:r,initialTemplateId:a}){const{data:i=[],isLoading:l}=ylt(),[o,c]=j.useState(a),{data:d,isLoading:u,error:h}=blt(s?n:void 0),m=Lnr(),f=j.useMemo(()=>i.find(E=>E.id===o),[i,o]),g=yx(f),{data:x=[],isLoading:v}=aoe(s?g==null?void 0:g.id:void 0);j.useEffect(()=>{s&&a&&c(a)},[s,a]);const y=i.filter(E=>{var I;return((I=yx(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=Eis.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});ne.success(`${E.fileName} saved to this deal's files`),t(!1)}catch(E){ne.error((E==null?void 0:E.message)||"Could not generate the form")}},A=(g==null?void 0:g.mapping_status)==="mapped";return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Prepare a form"}),e.jsx(Er,{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=yx(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&&y.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||v)&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),!u&&!v&&A&&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($e,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(Al,{className:"h-3 w-3"})," ",w," blank"]})]}),e.jsx(go,{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."})]})})]}),!A&&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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:S,disabled:!A||m.isPending||b.length===0,children:[m.isPending?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Dz,{className:"mr-2 h-4 w-4"}),m.isPending?"Generating…":"Generate & save to deal"]})]})]})})}const Dnr=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function Mis(s){return st({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 Fnr(){const s=Zt();return mt({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]}),ne.success("Contact linked to deal")},onError:t=>{var n;(n=t.message)!=null&&n.includes("duplicate")?ne.error("This contact is already linked to this deal"):ne.error("Failed to link contact")}})}function Onr(){const s=Zt();return mt({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]}),ne.success("Contact removed from deal")},onError:()=>{ne.error("Failed to remove contact")}})}const _lt=[{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 aFe(s){var t;return((t=_lt.find(n=>n.value===s))==null?void 0:t.label)||s||"Signer"}function znr(s){const t=Sa();return st({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 Bnr(){const s=Sa(),t=Zt();return mt({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 $nr(){const s=Zt();return mt({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 Pis(){const s=Sa();return st({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 wlt(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 Unr(){const s=Sa(),t=Zt();return mt({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 qnr(){const s=Zt();return mt({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 Vnr(){const s=Sa(),t=Zt();return mt({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=wlt(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:A}=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(A)throw new Error(A.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 Iis({open:s,onOpenChange:t,dealId:n,dealName:r,initialTemplateId:a}){const{data:i=[],isLoading:l}=ylt(),[o,c]=j.useState(a),{data:d,isLoading:u}=blt(s?n:void 0),{data:h=[]}=Mis(n),{data:m=[]}=Pis(),f=Bnr(),g=Vnr(),[x,v]=j.useState("single"),[y,b]=j.useState(void 0),w=j.useMemo(()=>m.find(ce=>ce.id===y),[m,y]),S=j.useMemo(()=>wlt(w,i),[w,i]),{data:A=[],isLoading:E}=st({queryKey:["packet-signer-roles",y,S.map(ce=>{var ve;return(ve=yx(ce))==null?void 0:ve.id}).join(",")],enabled:x==="packet"&&S.length>0,queryFn:async()=>{const ce=S.map(be=>{var Ee;return(Ee=yx(be))==null?void 0:Ee.id}).filter(Boolean);if(!ce.length)return[];const{data:ve,error:fe}=await q.from("form_field_mappings").select("field_kind, signer_role").in("version_id",ce);if(fe)throw fe;const ue=new Set;for(const be of ve||[])be.field_kind&&be.field_kind!=="data"&&be.signer_role&&ue.add(be.signer_role);return[...ue]}}),I=j.useMemo(()=>i.find(ce=>ce.id===o),[i,o]),P=yx(I),{data:R=[],isLoading:D}=aoe(s?P==null?void 0:P.id:void 0),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Z]=j.useState({});j.useEffect(()=>{s&&a&&c(a)},[s,a]);const X=j.useMemo(()=>{const ce=new Set;if(x==="packet")for(const fe of A)ce.add(fe);else for(const fe of R)fe.field_kind&&fe.field_kind!=="data"&&fe.signer_role&&ce.add(fe.signer_role);const ve=_lt.map(fe=>fe.value);return[...ce].sort((fe,ue)=>ve.indexOf(fe)-ve.indexOf(ue))},[R,x,A]);j.useEffect(()=>{var ue,be,Ee;const ce={},ve=h.filter(ke=>ke.contact);let fe=0;for(const ke of X)if(ke==="agent"){const Ie=(ue=d==null?void 0:d.sources)==null?void 0:ue.profile;ce[ke]={name:(Ie==null?void 0:Ie.full_name)||"",email:(Ie==null?void 0:Ie.email)||"",contact_id:null}}else{const Ie=ve[fe++],Fe=Ie!=null&&Ie.contact?`${Ie.contact.first_name||""} ${Ie.contact.last_name||""}`.trim():"";ce[ke]={name:Fe,email:((be=Ie==null?void 0:Ie.contact)==null?void 0:be.email)||"",contact_id:((Ee=Ie==null?void 0:Ie.contact)==null?void 0:Ee.id)||null}}Z(ce),x==="single"&&I&&!O&&U(r?`${I.name} – ${r}`:I.name)},[X,h,d,o,y,x]);const ae=(P==null?void 0:P.mapping_status)==="mapped",le=(ce,ve)=>Z(fe=>({...fe,[ce]:{...fe[ce],...ve}})),re=X.length>0&&X.every(ce=>{var ve,fe,ue;return((fe=(ve=G[ce])==null?void 0:ve.name)==null?void 0:fe.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((ve,fe)=>({full_name:G[ve].name.trim(),email:G[ve].email.trim(),signer_role:ve,contact_id:G[ve].contact_id,is_agent:ve==="agent",order_index:fe}));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}),ne.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}),ne.success(`Signature request sent to ${ce[0].full_name}`)}t(!1)}catch(ve){ne.error((ve==null?void 0:ve.message)||"Could not send the signature request")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"flex max-h-[90vh] max-w-xl flex-col overflow-hidden",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Send for signature"}),e.jsx(Er,{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:()=>v(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:y,onValueChange:b,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose a packet"})}),e.jsx(hs,{children:m.map(ce=>{var ve;return e.jsxs(Ge,{value:ce.id,children:[ce.name," (",((ve=ce.items)==null?void 0:ve.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 ve;return e.jsxs("li",{children:[ce.name,((ve=yx(ce))==null?void 0:ve.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 ve=yx(ce);return e.jsxs(Ge,{value:ce.id,disabled:(ve==null?void 0:ve.mapping_status)!=="mapped",children:[ce.name,ce.scope==="brokerage"?" · Brokerage":"",(ve==null?void 0:ve.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(Ct,{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(Al,{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($e,{variant:"outline",className:"text-[10px]",children:[X.length," signer",X.length===1?"":"s"]})]}),X.map((ce,ve)=>{var fe,ue,be;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:[ve+1,". ",aFe(ce)]}),ce!=="agent"&&h.length>0&&e.jsxs(ms,{value:((fe=G[ce])==null?void 0:fe.contact_id)||"",onValueChange:Ee=>{const ke=h.find(Ie=>{var Fe;return((Fe=Ie.contact)==null?void 0:Fe.id)===Ee});ke!=null&&ke.contact&&le(ce,{contact_id:Ee,name:`${ke.contact.first_name||""} ${ke.contact.last_name||""}`.trim(),email:ke.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=>le(ce,{name:Ee.target.value,contact_id:null})}),e.jsx(pe,{className:"h-8 text-xs",type:"email",placeholder:"Email address",value:((be=G[ce])==null?void 0:be.email)||"",onChange:Ee=>le(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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:J,disabled:!re||te||u,children:[te?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(_f,{className:"mr-2 h-4 w-4"}),te?"Sending…":x==="packet"?`Send ${S.length||""} document${S.length===1?"":"s"}`.replace(" "," "):"Send signature request"]})]})]})})}function Hnr({status:s}){switch(s){case"completed":return e.jsx($e,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Completed"});case"partially_signed":return e.jsx($e,{className:"bg-amber-500/15 text-amber-600 hover:bg-amber-500/15",children:"Partially signed"});case"sent":return e.jsx($e,{variant:"secondary",children:"Sent"});case"declined":return e.jsx($e,{variant:"destructive",children:"Declined"});case"voided":return e.jsx($e,{variant:"outline",children:"Voided"});case"expired":return e.jsx($e,{variant:"outline",children:"Expired"});case"finalize_failed":return e.jsx($e,{variant:"destructive",children:"Needs attention"});default:return e.jsx($e,{variant:"secondary",children:s})}}function Gnr({envelope:s}){const t=Zn(),n=$nr(),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 y=0;y{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 ne.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){ne.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}),ne.success("Envelope voided")}catch(f){ne.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(_f,{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} (${aFe(m.signer_role)}): ${m.status.replace("_"," ")}`).join(" · ")})]}),e.jsx(Hnr,{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"}),ne.success("Reminder sent")}catch(m){ne.error((m==null?void 0:m.message)||"Could not send a reminder")}},children:[e.jsx(YS,{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(PE,{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(ji,{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(Zq,{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(Pz,{className:"mr-1 h-3 w-3"})," Void"]})]})]})}function Wnr({dealId:s,dealName:t}){const[n,r]=j.useState(!1),[a,i]=j.useState(!1),{data:l=[],isLoading:o,error:c}=Inr(s),{data:d=[]}=znr(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(_f,{className:"mr-2 h-4 w-4"})," Send for signature"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>r(!0),children:[e.jsx(Eq,{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(Ir,{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(Gnr,{envelope:u},u.id))]}),o&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Ct,{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(Qr,{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)??"—"," · ",Js(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(Tis,{open:n,onOpenChange:r,dealId:s,dealName:t}),e.jsx(Iis,{open:a,onOpenChange:i,dealId:s,dealName:t})]})}const FAt={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function Lis({open:s,onOpenChange:t}){const{data:n,isLoading:r}=$$n(),a=U$n(),i=q$n(),l=V$n(),[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),ne.success("Question added")}catch{ne.error("Failed to add question")}},g=async b=>{try{await l.mutateAsync(b),ne.success("Question removed")}catch{ne.error("Failed to remove question")}},x=async(b,w)=>{try{await i.mutateAsync({id:b,is_required:w})}catch{ne.error("Failed to update question")}},v=()=>{h.trim()&&(u(b=>({...b,options:[...b.options,h.trim()]})),m(""))},y=b=>{u(w=>({...w,options:w.options.filter((S,A)=>A!==b)}))};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx($s,{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(go,{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(Ct,{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(zg,{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($e,{variant:"secondary",className:"text-xs",children:FAt[b.field_type]||b.field_type}),b.is_required&&e.jsx($e,{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(jn,{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(qn,{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(FAt).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:()=>y(w),className:"text-muted-foreground hover:text-destructive",children:e.jsx(mr,{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(),v()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx($,{variant:"outline",size:"sm",onClick:v,disabled:!h.trim(),className:"h-8",children:e.jsx(cn,{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(jn,{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(Ct,{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(cn,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function Knr({override:s,onChange:t}){const n=Sa(),{data:r}=W9t(),[a,i]=j.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(n){if(d.size>5*1024*1024){ne.error("Image must be under 5MB");return}i(u);try{const h=await K9t(n,d,`${u}`);l(u==="logo"?{logo_url:h}:{cover_photo_url:h})}catch(h){ne.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(wn,{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(OAt,{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(OAt,{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(zAt,{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(zAt,{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(qn,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function OAt({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(Hc,{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(Ct,{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(qn,{className:"h-3.5 w-3.5"})})]})]})]})}function zAt({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(qn,{className:"h-3 w-3"})})]})]})}function Ynr({portalId:s,agentUserId:t}){const n=Zt(),{data:r,isLoading:a}=st({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:v},{data:y},{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(v)throw v;const w=new Map;(y||[]).forEach(A=>w.set(A.vendor_id,A.is_visible));const S=new Map;return(b||[]).forEach(A=>S.set(A.vendor_id,A.is_visible)),{vendors:x||[],selMap:w,overrideMap:S}}}),i=mt({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=>ne.error(h.message)});if(a)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{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(yb,{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=rK.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(go,{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($e,{variant:"outline",className:"text-[10px] shrink-0",children:u(h.category)}),h.owner_type==="brokerage"&&e.jsx($e,{variant:"secondary",className:"text-[10px] shrink-0",children:"Brokerage"}),h.is_required&&e.jsx($e,{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(jn,{checked:m,disabled:h.is_required||i.isPending,onCheckedChange:f=>i.mutate({vendorId:h.id,isVisible:f})})]},h.id)})})})]})}function Znr({portalId:s,ownerId:t,clientEmail:n,linkedPortalId:r,onLink:a}){const[i,l]=j.useState(""),[o,c]=j.useState(!1),{data:d,isLoading:u}=st({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 y,b,w,S;const v=x.deal_pipeline;return((y=x.client_name)==null?void 0:y.toLowerCase().includes(g))||((b=x.client_email)==null?void 0:b.toLowerCase().includes(g))||((w=v==null?void 0:v.deal_name)==null?void 0:w.toLowerCase().includes(g))||((S=v==null?void 0:v.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(nu,{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(e7,{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(nu,{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($e,{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(nu,{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(Ct,{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($e,{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 jlt({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=f3(),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 v="Card Video",{videoId:y,libraryId:b}=await k6(v),{uploadUrl:w,apiKey:S}=await S6(y),A=new XMLHttpRequest;A.upload.onprogress=U=>{U.lengthComputable&&o(U.loaded/U.total*100)},await new Promise((U,W)=>{A.onload=()=>A.status>=200&&A.status<300?U():W(new Error("Upload failed")),A.onerror=()=>W(new Error("Upload failed")),A.open("PUT",w),A.setRequestHeader("AccessKey",S),A.send(g)}),i("processing");let E=0;const I=Date.now(),P=9e4,R=`https://iframe.mediadelivery.net/embed/${b}/${y}`;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:y,playback_url:`https://iframe.mediadelivery.net/play/${b}/${y}`,file_size_mb:W,title:v,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(R),ne.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const U=await hk(y);if(E=U.status,d(U.encodeProgress||0),E===5||E===6)throw new Error("Video processing failed")}const D=await hk(y),O=(D.storageSize||g.size)/(1024*1024);await u.mutateAsync({bunny_video_id:y,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:v,status:"ready",touch_type:"video"}),t(R),ne.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{r(!1),h()},1500)}catch(v){console.error("Recording upload error:",v),ne.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(Os,{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(fa,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(Fs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(DT,{maxDurationSeconds:600,onRecordingComplete:f,onError:g=>ne.error(g)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Ct,{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(Ct,{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(Wl,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const Xnr=s=>`portal-settings-draft:${s}`;function Nlt({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=DK(),[i,l]=j.useState(!1),o=j.useMemo(()=>Xnr(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||""),[v,y]=j.useState(n.appraisal_date||""),[b,w]=j.useState(n.welcome_message||""),[S,A]=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),[Z,X]=j.useState(n.stage_mapping||[]),[ae,le]=j.useState(null),[re,te]=j.useState(n.linked_portal_id||null),[J,ce]=j.useState(n.referral_enabled??!0),[ve,fe]=j.useState(n.referral_reward_text||""),[ue,be]=j.useState(n.referral_cta_headline||""),[Ee,ke]=j.useState(n.homeowner_hub_video_url||""),[Ie,Fe]=j.useState(n.branding_override||{}),Ne=()=>{h(n.next_step_text||""),f(n.next_step_video_url||""),x(n.inspection_date||""),y(n.appraisal_date||""),w(n.welcome_message||""),A(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),fe(n.referral_reward_text||""),be(n.referral_cta_headline||""),ke(n.homeowner_hub_video_url||""),Fe(n.branding_override||{})};j.useEffect(()=>{d(!1);const Ve=localStorage.getItem(o);if(Ve)try{const ht=JSON.parse(Ve);h(ht.nextStepText||""),f(ht.nextStepVideo||""),x(ht.inspectionDate||""),y(ht.appraisalDate||""),w(ht.welcomeMessage||""),A(ht.reviewUrl||""),I(!!ht.showPostClose),R(!!ht.notifyClient),O(!!ht.requireOnboarding),W(!!ht.allowSpouse),G(ht.visibility||n.visibility),X(ht.stageMapping||[]),te(ht.linkedPortalId??null),ce(ht.referralEnabled??!0),fe(ht.referralRewardText||""),be(ht.referralCtaHeadline||""),ke(ht.homeownerHubVideoUrl||""),Fe(ht.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}Ne(),d(!0)},[o,n]),j.useEffect(()=>{if(!c)return;const Ve={nextStepText:u,nextStepVideo:m,inspectionDate:g,appraisalDate:v,welcomeMessage:b,reviewUrl:S,showPostClose:E,notifyClient:P,requireOnboarding:D,allowSpouse:U,visibility:V,stageMapping:Z,linkedPortalId:re,referralEnabled:J,referralRewardText:ve,referralCtaHeadline:ue,homeownerHubVideoUrl:Ee,brandingOverride:Ie};u!==(n.next_step_text||"")||m!==(n.next_step_video_url||"")||g!==(n.inspection_date||"")||v!==(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(Z)!==JSON.stringify(n.stage_mapping||[])||re!==(n.linked_portal_id||null)||J!==(n.referral_enabled??!0)||ve!==(n.referral_reward_text||"")||ue!==(n.referral_cta_headline||"")||Ee!==(n.homeowner_hub_video_url||"")||JSON.stringify(Ie)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify(Ve)):localStorage.removeItem(o)},[u,m,g,v,b,S,E,P,D,U,V,Z,re,J,ve,ue,Ee,Ie,o,c,n]);const Be=()=>{localStorage.removeItem(o),Ne()},Se=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:v||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:Z.length>0?Z:null,linked_portal_id:re,referral_enabled:J,referral_reward_text:ve||null,referral_cta_headline:ue||null,homeowner_hub_video_url:Ee||null,branding_override:Object.values(Ie).some(ht=>ht!=null&&ht!=="")?Ie:null});const Ve=n.linked_portal_id;re&&re!==Ve&&await q.from("client_portals").update({linked_portal_id:n.id}).eq("id",re),!re&&Ve&&await q.from("client_portals").update({linked_portal_id:null}).eq("id",Ve),localStorage.removeItem(o),ne.success("Portal settings saved"),t(!1)}catch{ne.error("Failed to save settings")}},Ae=()=>{X([...Z,{label:""}])},Ce=Ve=>{X(Z.filter((ht,Qe)=>Qe!==Ve)),ae===Ve&&le(null)},qe=(Ve,ht,Qe)=>{const at=[...Z];at[Ve]={...at[Ve],[ht]:Qe},X(at)},ze=()=>{const ht=XLe(null).map(Qe=>({label:Qe.label,description:Qe.description,stageId:void 0}));X(ht)};return e.jsxs(e.Fragment,{children:[e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(Us,{children:e.jsx($s,{children:"Portal Settings"})}),e.jsxs(pa,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ga,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(Xt,{value:"general",children:"General"}),e.jsx(Xt,{value:"timeline",children:"Timeline"}),e.jsx(Xt,{value:"content",children:"Content"}),e.jsx(Xt,{value:"vendors",children:"Vendors"}),e.jsx(Xt,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(Qt,{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(Ve=>e.jsx("button",{onClick:()=>G(Ve),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${V===Ve?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:Ve.charAt(0).toUpperCase()+Ve.slice(1)},Ve))})]}),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(jn,{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(jn,{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(jn,{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(jn,{checked:P,onCheckedChange:R})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(Znr,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:re,onLink:te})}),e.jsx("div",{children:e.jsx(pe,{type:"date",value:g,onChange:Ve=>x(Ve.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:v,onChange:Ve=>y(Ve.target.value),className:"mt-1"})]})]}),e.jsx(Qt,{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.'}),Z.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:Z.map((Ve,ht)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zg,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(pe,{value:Ve.label,onChange:Qe=>qe(ht,"label",Qe.target.value),placeholder:`Stage ${ht+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:()=>le(ae===ht?null:ht),children:ae===ht?"Less":"More"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Ce(ht),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]}),ae===ht&&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:Ve.description||"",onChange:Qe=>qe(ht,"description",Qe.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"}),Ve.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:Ve.video_url.length>40?Ve.video_url.slice(0,40)+"...":Ve.video_url}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>qe(ht,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(jlt,{onVideoReady:Qe=>qe(ht,"video_url",Qe)}),e.jsx(e9,{userId:r,onSelect:Qe=>qe(ht,"video_url",Qe),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 Qe=prompt("Paste a YouTube or Loom URL:");Qe&&qe(ht,"video_url",Qe)},children:[e.jsx(Sd,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},ht))}),Z.length>0&&e.jsxs($,{variant:"outline",size:"sm",onClick:Ae,className:"mt-2 text-xs w-full",children:[e.jsx(cn,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(Qt,{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:Ve=>w(Ve.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:Ve=>h(Ve.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:Ve=>f(Ve.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:Ve=>A(Ve.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(jn,{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:Ve=>be(Ve.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:ve,onChange:Ve=>fe(Ve.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:Ve=>ke(Ve.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(Qt,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(Ynr,{portalId:n.id,agentUserId:r})}),e.jsx(Qt,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(Knr,{override:Ie,onChange:Fe})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx($,{variant:"ghost",onClick:Be,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs($,{onClick:Se,disabled:a.isPending,children:[a.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(tl,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(Lis,{open:i,onOpenChange:l})]})}const Qnr=s=>`portal-update-draft:${s}`;function klt({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=j.useMemo(()=>Qnr(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),[v,y]=j.useState(!1),b=qQt();j.useEffect(()=>{y(!1);const A=localStorage.getItem(i);if(A)try{const E=JSON.parse(A);o(E.title||""),d(E.content||""),h(E.videoUrl||""),f(!!E.isStageChange),x(typeof E.sendNotification=="boolean"?E.sendNotification:a??!0),y(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),f(!1),x(a??!0),y(!0)},[i,a]),j.useEffect(()=>{if(!v)return;const A={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(A)):localStorage.removeItem(i)},[l,c,u,m,g,v,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 A=oC(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:A,force:!0}});if(I)throw I;E!=null&&E.emailSent?ne.success("Update posted & client emailed"):ne.success(`Update posted (${(E==null?void 0:E.reason)||"no email sent"})`)}catch(A){console.error("Notification failed:",A),ne.success("Update posted (notification failed to send)")}else ne.success("Update posted to portal");w(),t(!1)}catch{ne.error("Failed to post update")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{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:A=>o(A.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:A=>d(A.target.value),className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[80px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Everything looked great during the inspection..."})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(pe,{value:u,onChange:A=>h(A.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(fa,{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(zy,{className:"h-3 w-3"}):e.jsx(KS,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function Slt({open:s,onOpenChange:t,portal:n,dealName:r}){const a=DK(),{isGmailConnected:i,gmailEmail:l}=Gy(),[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=oC(n.slug),v=o.split(" ")[0]||"there",y=`Your Transaction Portal – ${r}`,b=`Hi ${v}, 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),ne.success("Portal link copied!")},S=async()=>{if(!d.trim()){ne.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:y,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")}ne.success(`Invite sent to ${d}`),t(!1)}catch(E){ne.error(E.message||"Failed to send invite")}finally{m(!1)}},A=()=>{const E=encodeURIComponent(y),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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{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(ma,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Za,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs($,{onClick:A,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(Ir,{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(Za,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function Jnr({deal:s}){const{isAdmin:t,user:n}=_s(),{data:r,isLoading:a}=z$n(s.id),i=fit(),l=DK(),[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(wn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Ct,{className:"h-3 w-3 animate-spin ml-auto"})]})});const v=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}),ne.success("Client portal enabled!")}catch{ne.error("Failed to create portal")}finally{c(!1)}},y=async E=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:E}),ne.success(E?"Portal enabled":"Portal disabled")}catch{ne.error("Failed to update portal")}},b=()=>{if(!r)return;const E=oC(r.slug);navigator.clipboard.writeText(E),ne.success("Portal link copied!")},w=()=>{if(!r)return;const E=oC(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(wn,{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:v,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(wn,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const S=oC(r.slug),A=(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(wn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx($e,{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(jn,{checked:r.is_enabled,onCheckedChange:y})]}),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($e,{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(Za,{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(Ir,{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(Zr,{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(h4,{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(Nd,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(br,{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(dl,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(Nlt,{open:d,onOpenChange:u,portal:r,dealOwnerId:A}),e.jsx(klt,{open:h,onOpenChange:m,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(Slt,{open:f,onOpenChange:g,portal:r,dealName:s.deal_name})]})}function err({dealId:s,primaryContactId:t}){const n=Zn(),{data:r,isLoading:a}=Mis(s),{data:i}=L_(),l=Fnr(),o=Onr(),[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 A,E,I;if(g.has(w.id))return!1;if(!u.trim())return!0;const S=u.toLowerCase();return((A=w.first_name)==null?void 0:A.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),v=w=>{l.mutate({dealId:s,contactId:w,role:m}),d(!1),h("")},y=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(Yn,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(Gd,{open:c,onOpenChange:d,children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(Dd,{className:"w-80 p-3",align:"start",children:e.jsx(BAt,{search:u,setSearch:h,selectedRole:m,setSelectedRole:f,filteredContacts:x,onAdd:v})})]})]}):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(Yn,{className:"h-4 w-4"}),"Linked Contacts",r&&r.length>0&&e.jsx($e,{variant:"secondary",className:"text-[10px] px-1.5",children:r.length})]}),e.jsxs(Gd,{open:c,onOpenChange:d,children:[e.jsx(Wd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(cn,{className:"h-3.5 w-3.5"})})}),e.jsx(Dd,{className:"w-80 p-3",align:"end",children:e.jsx(BAt,{search:u,setSearch:h,selectedRole:m,setSelectedRole:f,filteredContacts:x,onAdd:v})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(w=>{var S,A,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:[(A=(S=w.contact)==null?void 0:S.first_name)==null?void 0:A[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($e,{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(pn,{className:"h-3 w-3"})})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>y(w.id),children:e.jsx(qn,{className:"h-3 w-3"})})]})]},w.id)})})]})}function BAt({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:Dnr.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(go,{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 HQ=[{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"}],trr=[{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 srr(){const s=Zt();return mt({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 nrr(){const s=Zt();return mt({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 rrr(){return st({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 arr(){const s=Sa(),t=Zt();return mt({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 v=g==="stage_entry"?null:u[g],y=v?new Date(`${v}T12:00:00`):new Date;return y.setDate(y.getDate()+(x||0)),y.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 irr(){const s=Sa(),t=Zt();return mt({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 orr(){const s=Sa();return st({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 Clt(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 k5(s){const t=Clt(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 lrr(s){return s===null?"none":s<0?"overdue":s===0?"today":s<=3?"soon":"upcoming"}const crr={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 J$e(s){const t=Clt(s);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function $At(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 drr({deal:s,compact:t=!1}){const n=srr(),r=nrr(),[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={};HQ.forEach(Z=>{G[Z.key]=(s==null?void 0:s[Z.key])??""}),o(G),i(!0)},x=async()=>{try{await n.mutateAsync({dealId:s.id,dates:l}),ne.success("Transaction dates updated"),i(!1)}catch(G){ne.error((G==null?void 0:G.message)||"Could not save dates")}},v=async(G,Z)=>{const X=f;u(G);try{await r.mutateAsync({dealId:s.id,completed:G}),ne.success(Z)}catch(ae){u(X),ne.error((ae==null?void 0:ae.message)||"Could not update milestone")}},y=j.useMemo(()=>HQ.map(G=>{const Z=(s==null?void 0:s[G.key])??null,X=k5(Z),ae=f.includes(G.key),le=Z?ae?"done":lrr(X):"none";return{...G,value:Z,days:X,isDone:ae,state:le}}),[s,f.join(",")]),b=y.filter(G=>G.value).length,w=y.filter(G=>G.state==="done").length,S=k5(s==null?void 0:s.target_close_date),A=y.filter(G=>G.value&&!G.isDone&&G.days!==null&&G.days>=0).sort((G,Z)=>(G.days??0)-(Z.days??0))[0],E=y.filter(G=>G.state==="overdue"),I=()=>{const G=Array.from(new Set([...f,...E.map(Z=>Z.key)]));v(G,"Past milestones marked complete")},P=(G,Z)=>{const X=Z?f.filter(ae=>ae!==G):[...f,G];v(X,Z?"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,Z)=>{try{await n.mutateAsync({dealId:s.id,dates:{[G]:Z}}),ne.success(Z?"Date saved":"Date cleared"),D(null)}catch(X){ne.error((X==null?void 0:X.message)||"Could not save date")}};return e.jsx(vk,{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(Su,{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${J$e((s==null?void 0:s.actual_close_date)||(s==null?void 0:s.target_close_date))?` ${J$e((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 ${HQ.length} key dates set`})]})]}),e.jsxs(Os,{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(pi,{className:"h-3.5 w-3.5"}),t?"":"Edit dates"]})}),e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx($s,{children:"Key transaction dates"})}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-3 max-h-[60vh] overflow-y-auto pr-1",children:HQ.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:Z=>o(X=>({...X,[G.key]:Z.target.value})),className:"h-9"})]},G.key))}),e.jsxs(Nr,{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(Ct,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(ma,{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:y.map(G=>{const Z=!!G.value;return e.jsxs("div",{className:"relative",children:[e.jsxs(ry,{children:[e.jsx(ay,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:r.isPending,onClick:()=>Z?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",crr[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:J$e(G.value)??"Set date"}),G.value&&e.jsx("p",{className:"text-[10px] opacity-80 truncate",children:$At(G.state,G.days)}),Z&&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(ma,{className:"h-2.5 w-2.5"})})]})}),e.jsx(vx,{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(Gd,{open:R===G.key,onOpenChange:X=>X?W(G.key):D(null),children:[e.jsx(Wd,{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(pi,{className:"h-3 w-3"})})}),e.jsxs(Dd,{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(Ct,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(ma,{className:"h-3.5 w-3.5 mr-1"}),"Save"]})]})]})]})]},G.key)})}),(E.length>0||A||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(Iz,{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(Al,{className:"h-3 w-3"}),E.length," awaiting confirmation"]}),A&&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: ",A.label," · ",$At(A.state,A.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(Iz,{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 urr={Home:va,FileSignature:l_,Handshake:yb,CalendarClock:Su,Sparkles:wn,ClipboardCheck:GN},hrr={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 mrr(s,t){var a;const n=((a=trr.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 Ris({open:s,onOpenChange:t,dealId:n,dealName:r}){const{data:a,isLoading:i}=rrr(),{data:l}=Wie(),o=arr(),c=irr(),[d,u]=j.useState(null),[h,m]=j.useState({}),f=v=>{if(h[v.id])return h[v.id];const y=l==null?void 0:l.find(b=>{var w,S;return((w=b.name)==null?void 0:w.toLowerCase())===((S=v.target_stage_name)==null?void 0:S.toLowerCase())});return(y==null?void 0:y.id)??""},g=async v=>{if(n){u(v.id);try{const y=await o.mutateAsync({playbookId:v.id,dealId:n});ne.success(y>0?`Added ${y} task${y===1?"":"s"} to this deal`:"All tasks already exist on this deal"),y>0&&t(!1)}catch(y){ne.error((y==null?void 0:y.message)||"Could not apply playbook")}finally{u(null)}}},x=async v=>{const y=f(v);if(!y){ne.error("Pick which stage this playbook should trigger on");return}u(`install-${v.id}`);try{const b=await c.mutateAsync({playbookId:v.id,stageId:y});ne.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){ne.error((b==null?void 0:b.message)||"Could not automate playbook")}finally{u(null)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{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(_x,{className:"h-4.5 w-4.5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Transaction Playbooks"}),e.jsx(Er,{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(go,{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(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(BB,{type:"single",collapsible:!0,className:"space-y-3",children:(a||[]).map(v=>{const y=urr[v.icon||"ClipboardCheck"]||GN,b=v.accent_color||"hsl(var(--primary))";return e.jsxs(c6,{value:v.id,className:"border rounded-xl px-0 overflow-hidden bg-card",children:[e.jsx(d6,{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(y,{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:v.name}),e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:[v.tasks.length," steps"]}),v.deal_type&&e.jsx($e,{variant:"outline",className:"text-[10px] capitalize",children:v.deal_type})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.description})]})]})}),e.jsxs(u6,{className:"px-4 pb-4",children:[e.jsx("div",{className:"space-y-1.5 mb-4",children:v.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:mrr(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",hrr[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(v),disabled:d===v.id,children:[d===v.id?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Qp,{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(v),onValueChange:w=>m(S=>({...S,[v.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(v),disabled:d===`install-${v.id}`,children:[d===`install-${v.id}`?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(DE,{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(Vr,{className:"h-3 w-3"}),"Automating adds these steps to every future deal that reaches that stage."]})]})]},v.id)})})})})]})})}function frr(s){return st({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 prr(s){const t=Zt();return mt({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 grr(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 xrr({dealId:s}){const{data:t=[],isLoading:n,error:r}=frr(s),a=prr(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(pn,{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(pn,{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?` · ${Js(kh(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:grr(i.gmail_thread_id,i.gmail_message_id),target:"_blank",rel:"noreferrer",children:e.jsx(Ir,{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(qn,{className:"h-4 w-4"})})]},i.id)})})]})}const yrr=10*1024*1024;function vrr({dealId:s,photoUrl:t}){const n=j.useRef(null),r=Zt(),[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/")){ne.error("Please choose an image file");return}if(d.size>yrr){ne.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),ne.success("Property photo updated")}catch(h){ne.error(h.message||"Upload failed")}finally{i(!1),n.current&&(n.current.value="")}},c=async()=>{i(!0);try{await l(null),ne.success("Photo removed")}catch(d){ne.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(Ct,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(jx,{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(qn,{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 brr={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"}},_rr={note:no,call:Da,email:pn,meeting:Ea,stage_change:Ir,task_completed:Vr,document:va,system:ca};function wrr({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var Ie,Fe;const l=Zn(),{data:o,isLoading:c}=fXn((s==null?void 0:s.id)||""),{data:d,isLoading:u}=gXn((s==null?void 0:s.id)||""),h=pXn(),m=yXn(),f=xXn(),g=mXn(),{data:x,isLoading:v}=bQn((s==null?void 0:s.id)||""),y=_Qn(),b=wQn(),w=jQn(),S=j.useRef(null),[A,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=brr[s.deal_type],Z=(()=>{var Se;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const Ne=((Se=s.listing)==null?void 0:Se.created_at)||s.listing_date;if(!Ne)return null;const Be=s.contract_date?kh(s.contract_date):new Date;return ck(Be,kh(Ne))})(),X=Ne=>Ne?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ne):"-",ae=async()=>{if(A.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:A}),E(""),ne.success("Note added")}catch{ne.error("Failed to add note")}},le=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(""),ne.success("Task added")}catch{ne.error("Failed to add task")}},re=async(Ne,Be)=>{try{await f.mutateAsync({id:Ne,is_completed:Be,deal_id:s.id})}catch{ne.error("Failed to update task")}},te=async()=>{try{await g.mutateAsync(s.id),ne.success("Deal deleted"),n(!1)}catch{ne.error("Failed to delete deal")}},J=(d==null?void 0:d.filter(Ne=>Ne.is_completed).length)||0,ce=(d==null?void 0:d.length)||0,ve=(x==null?void 0:x.length)||0,fe=Ne=>Ne<1024?`${Ne} B`:Ne<1024*1024?`${(Ne/1024).toFixed(1)} KB`:`${(Ne/(1024*1024)).toFixed(1)} MB`,ue=Ne=>Ne?Ne.startsWith("image/")?Hc:Ne.includes("pdf")?Qr:Tq:Tq,be=async Ne=>{const Be=Ne.target.files;if(!(!Be||!s)){V(!0);try{for(const Se of Array.from(Be)){if(Se.size>20*1024*1024){ne.error(`${Se.name} exceeds 20MB limit`);continue}await y.mutateAsync({dealId:s.id,file:Se})}ne.success("File(s) uploaded")}catch{ne.error("Failed to upload file")}finally{V(!1),S.current&&(S.current.value="")}}},Ee=async(Ne,Be)=>{if(s)try{await b.mutateAsync({fileId:Ne,storagePath:Be,dealId:s.id}),ne.success("File deleted")}catch{ne.error("Failed to delete file")}},ke=async(Ne,Be)=>{try{const Se=await NQn(Ne),Ae=document.createElement("a");Ae.href=Se,Ae.download=Be,Ae.target="_blank",document.body.appendChild(Ae),Ae.click(),document.body.removeChild(Ae)}catch{ne.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(Vy,{open:t,onOpenChange:n,children:e.jsxs(uy,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(I0,{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($e,{variant:"outline",className:Pt("text-xs",G.color),children:G.label}),e.jsxs($e,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(L0,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(vQn,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(bp,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>U(!0),children:e.jsx(qn,{className:"h-4 w-4"})})]})]})}),e.jsx(go,{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:[(Ie=s.contact.first_name)==null?void 0:Ie[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(pn,{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(Ir,{className:"h-4 w-4"})})]})]}),e.jsx(err,{dealId:s.id,primaryContactId:s.contact_id}),e.jsx(xrr,{dealId:s.id}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(vrr,{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)]})]}),gw(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(gw(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(Vr,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),Z!==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",Z>90?"text-red-600":Z>60?"text-amber-600":"text-foreground"),children:[Z," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",Js(kh(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(su,{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(drr,{deal:s}),e.jsx(Jnr,{deal:s}),e.jsxs(pa,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(ga,{className:"w-full grid grid-cols-4",children:[e.jsxs(Xt,{value:"tasks",className:"gap-1",children:[e.jsx(Vr,{className:"h-4 w-4"}),"Tasks ",ce>0&&`(${J}/${ce})`]}),e.jsxs(Xt,{value:"files",className:"gap-1",children:[e.jsx(KI,{className:"h-4 w-4"}),"Files ",ve>0&&`(${ve})`]}),e.jsxs(Xt,{value:"forms",className:"gap-1",children:[e.jsx(l_,{className:"h-4 w-4"}),"Forms"]}),e.jsxs(Xt,{value:"activity",className:"gap-1",children:[e.jsx(ca,{className:"h-4 w-4"}),"Activity"]})]}),e.jsx(Qt,{value:"forms",className:"mt-4",children:e.jsx(Wnr,{dealId:s.id,dealName:s.deal_name})}),e.jsxs(Qt,{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:Ne=>P(Ne.target.value),onKeyDown:Ne=>Ne.key==="Enter"&&le()}),e.jsx($,{onClick:le,disabled:!I.trim(),children:e.jsx(cn,{className:"h-4 w-4"})}),e.jsxs($,{variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>D(!0),children:[e.jsx(_x,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"space-y-2",children:[d==null?void 0:d.map(Ne=>e.jsxs("div",{className:Pt("flex items-center gap-3 p-3 rounded-lg border transition-colors",Ne.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(ai,{checked:Ne.is_completed,onCheckedChange:Be=>re(Ne.id,!!Be)}),e.jsx("span",{className:Pt("flex-1 text-sm",Ne.is_completed&&"line-through text-muted-foreground"),children:Ne.title}),Ne.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Js(new Date(Ne.due_date),"MMM d")})]},Ne.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(Qt,{value:"files",className:"mt-4 space-y-3",children:[(s==null?void 0:s.id)&&e.jsx(CQn,{dealId:s.id}),e.jsx("input",{type:"file",ref:S,className:"hidden",multiple:!0,onChange:be,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs($,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var Ne;return(Ne=S.current)==null?void 0:Ne.click()},disabled:W,children:[W?e.jsx(Ct,{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(Ne=>{const Be=ue(Ne.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(Be,{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:Ne.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[fe(Ne.file_size)," · ",Js(new Date(Ne.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(vk,{children:e.jsxs(ry,{children:[e.jsx(ay,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${Ne.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>w.mutate({fileId:Ne.id,visible:!Ne.visible_on_portal,dealId:s.id}),children:Ne.visible_on_portal?e.jsx(Ta,{className:"h-4 w-4"}):e.jsx(Nx,{className:"h-4 w-4"})})}),e.jsx(vx,{side:"top",children:Ne.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>ke(Ne.storage_path,Ne.file_name),children:e.jsx(ji,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Ee(Ne.id,Ne.storage_path),children:e.jsx(mr,{className:"h-4 w-4"})})]})]},Ne.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(Qt,{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:A,onChange:Ne=>E(Ne.target.value),rows:2}),e.jsxs($,{onClick:ae,disabled:!A.trim(),size:"sm",className:"w-full",children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[o==null?void 0:o.map(Ne=>{const Be=_rr[Ne.activity_type]||ca;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(Be,{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:Ne.title}),Ne.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:Ne.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:hu(new Date(Ne.created_at),{addSuffix:!0})})]})]},Ne.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(Ris,{open:R,onOpenChange:D,dealId:s==null?void 0:s.id,dealName:s==null?void 0:s.deal_name}),e.jsx(fc,{open:O,onOpenChange:U,children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Delete Deal?"}),e.jsxs(ic,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:te,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function jrr({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=N6e(),i=Crs(),{data:l}=OB(),{data:o}=Uw(),[c,d]=j.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:Js(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||Js(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}),ne.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(f){console.error("Error syncing to scorecard:",f),ne.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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{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($s,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(Er,{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(Ea,{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(su,{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(Aw,{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(Nr,{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(Qa,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const Nrr={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"}},UAt={urgent:0,high:1,medium:2,low:3};function krr({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 v,y;let x=0;switch(a){case"deal_name":x=f.deal_name.localeCompare(g.deal_name);break;case"stage":{const b=((v=t.find(S=>S.id===f.stage_id))==null?void 0:v.sort_order)||0,w=((y=t.find(S=>S.id===g.stage_id))==null?void 0:y.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?kh(f.target_close_date).getTime():1/0,w=g.target_close_date?kh(g.target_close_date).getTime():1/0;x=b-w;break}case"priority":x=UAt[f.priority]-UAt[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(Lg,{className:"ml-2 h-4 w-4"}):e.jsx(Dy,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:d.map(f=>{const g=h(f.stage_id),x=Nrr[f.deal_type],v=f.target_close_date?ck(kh(f.target_close_date),new Date):null,y=!!(g!=null&&g.is_won_stage)||!!(g!=null&&g.is_lost_stage)||!!f.actual_close_date,b=!y&&v!==null&&v<0,w=!y&&v!==null&&v<=7&&v>=0;return e.jsxs(An,{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(Mrs,{stages:t,currentStageId:f.stage_id||"",onStageSelect:(S,A)=>r(f.id,S,A)})}),e.jsx(wt,{children:e.jsx($e,{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(vl,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:Js(kh(f.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(wt,{children:e.jsx($e,{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 Dis(){const s=Sa();return st({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 Srr(s){const t=Sa();return st({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 Crr(){const s=Sa(),t=Zt();return mt({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 Arr(){const s=Zt();return mt({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 Err(){const s=Zt();return mt({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 iFe(){const s=Zt();return mt({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 Trr(){const s=Zt();return mt({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 Mrr(s){const t=Sa();return st({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 Prr(){const s=Sa(),t=Zt();return mt({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 Irr(){const s=Zt();return mt({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 Lrr(){const s=Sa(),t=Zt();return mt({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 Rrr={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function Drr({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=Srr(s?n:void 0),u=Trr(),h=Lrr(),[m,f]=j.useState(new Set),[g,x]=j.useState(!1),v=(c||[]).filter(S=>S.status!=="done");j.useEffect(()=>{v.length>0&&f(new Set(v.map(S=>S.id)))},[c]);const y=S=>{f(A=>{const E=new Set(A);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),ne.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),ne.error((S==null?void 0:S.message)||"Failed to move deal. Please try again.")}finally{x(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[480px]",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Move Deal"}),e.jsxs(Er,{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($e,{variant:"outline",className:"text-sm",children:a}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx($e,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.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:v.length})," incomplete task",v.length!==1?"s":"",". Select which to mark as done:"]}),e.jsx(go,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:v.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:()=>y(S.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[Rrr[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===v.length?f(new Set):f(new Set(v.map(S=>S.id)))},children:m.size===v.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(Ct,{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(Vr,{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(Ct,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const Frr=[{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"}],Orr=[{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 Fis({open:s,onOpenChange:t}){const n=Sa(),{data:r,isLoading:a}=W9t(),i=y9s(),[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){ne.error("Image must be under 5MB");return}d(g);try{const x=await K9t(n,f,g);u(g==="logo"?{logo_url:x}:{cover_photo_url:x})}catch(x){ne.error(`Upload failed: ${x.message||x}`)}finally{d(null)}}},m=async()=>{try{await i.mutateAsync(l),ne.success("Portal branding saved"),t(!1)}catch{ne.error("Failed to save branding")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(yd,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(Er,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(go,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(zrr,{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:Orr.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(qAt,{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(qAt,{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:Frr.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(VAt,{label:"Brand",value:l.brand_color,onChange:f=>u({brand_color:f})}),e.jsx(VAt,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(tl,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function zrr({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 qAt({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(Hc,{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(Ct,{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(qn,{className:"h-3.5 w-3.5"})})]})]})]})}function VAt({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 Brr(){const s=Sa();return st({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 $rr({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=fit(),d=DK(),u=BQt(),h=$Qt(),[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}),ne.success("Portal enabled!")}catch{ne.error("Failed to create portal")}finally{f(!1)}},v=async A=>{if(r)try{await d.mutateAsync({id:r.id,is_enabled:A}),ne.success(A?"Portal enabled":"Portal disabled")}catch{ne.error("Failed to update portal")}},y=()=>{r&&(navigator.clipboard.writeText(oC(r.slug)),ne.success("Link copied!"))},b=()=>{r&&window.open(oC(r.slug),"_blank")},w=async()=>{if(r)try{await u.mutateAsync(r.id),ne.success("Portal archived")}catch{ne.error("Failed to archive portal")}},S=async()=>{if(r)try{await h.mutateAsync(r.id),ne.success("Portal restored")}catch{ne.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(br,{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($e,{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(FI,{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(qn,{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(br,{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($e,{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:y,title:"Copy link",children:e.jsx(Za,{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(Ir,{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(Zr,{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(h4,{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(Nd,{className:"h-3.5 w-3.5"})}),e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(o_,{className:"h-3.5 w-3.5"})})}),e.jsx(Cu,{align:"end",children:e.jsxs(ja,{onClick:w,children:[e.jsx(wv,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(jn,{checked:r.is_enabled,onCheckedChange:v,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(Ct,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(wn,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function Ois(){const{data:s,isLoading:t}=QK(),{data:n,isLoading:r}=Brr(),[a,i]=j.useState(""),[l,o]=j.useState("all"),c=UQt(),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(null),[x,v]=j.useState(null),[y,b]=j.useState(!1),w=Sa(),S=t||r,A=new Map;n==null||n.forEach(U=>A.set(U.deal_id,U));const I=[...(s||[]).filter(U=>{var X,ae,le,re,te;const W=A.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))||((re=(le=U.contact)==null?void 0:le.last_name)==null?void 0:re.toLowerCase().includes(V))||((te=W==null?void 0:W.client_name)==null?void 0:te.toLowerCase().includes(V));let Z=!0;return l==="active"?Z=!!(W!=null&&W.is_enabled)&&!(W!=null&&W.archived_at):l==="disabled"?Z=!!W&&!W.is_enabled&&!W.archived_at:l==="archived"?Z=!!(W!=null&&W.archived_at):l==="none"?Z=!W:l==="all"&&(Z=!(W!=null&&W.archived_at)||!W),G&&Z})].sort((U,W)=>{const V=A.get(U.id),G=A.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}),ne.success("Portal permanently deleted"),v(null)}catch{ne.error("Failed to delete portal")}};return S?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(Ct,{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(wn,{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(yd,{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(mr,{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(go,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[I.map(U=>{const W=A.get(U.id)||null,V=U.contact?`${U.contact.first_name||""} ${U.contact.last_name||""}`.trim():"";return e.jsx($rr,{dealId:U.id,dealName:U.deal_name,contactName:V,portal:W,onSettingsOpen:u,onComposerOpen:G=>m(G),onInviteOpen:(G,Z)=>g({portal:G,dealName:Z}),onDeleteConfirm:v},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(wn,{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(Nlt,{open:!!d,onOpenChange:U=>!U&&u(null),portal:d,dealOwnerId:w||""}),h&&e.jsx(klt,{open:!!h,onOpenChange:U=>!U&&m(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),f&&e.jsx(Slt,{open:!!f,onOpenChange:U=>!U&&g(null),portal:f.portal,dealName:f.dealName}),e.jsx(Fis,{open:y,onOpenChange:b}),e.jsx(fc,{open:!!x,onOpenChange:U=>!U&&v(null),children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Permanently delete this portal?"}),e.jsx(ic,{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(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:O,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function Urr({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(cn,{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(Yn,{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(co,{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(mr,{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(mr,{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 qrr={closing_soon:{label:"Closing in 7 days",icon:Su,tone:"text-primary"},past_due:{label:"Past close date",icon:Al,tone:"text-destructive"},overdue_tasks:{label:"Overdue tasks",icon:qj,tone:"text-amber-600 dark:text-amber-400"},stalled:{label:"Stalled 14+ days",icon:CJ,tone:"text-muted-foreground"}};function Vrr({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=qrr[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 S7=s=>{const t=Number(s);return Number.isFinite(t)?t:0};function MC(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 kW(s){return S7(s.sale_price)||S7(s.expected_price)}function SW(s){const t=S7(s.expected_commission);if(t>0)return t;const n=S7(s.commission_percentage);return n>0?kW(s)*n/100:0}function Cne(s){const t=SW(s);return t*S7(s.brokerage_split_pct)/100+t*S7(s.franchise_fee_pct)/100+S7(s.transaction_fee)}const Hrr=s=>!!s.actual_close_date,Grr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Wrr(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:`${Grr[h-1]} ${String(m).slice(2)}`,deals:0,volume:0,gci:0,closed:!1})}return s.forEach(u=>{const h=kW(u),m=SW(u),f=Hrr(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=MC(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+=Cne(u));else if(o.activeDeals+=1,o.pipelineVolume+=h,o.pipelineGci+=m,o.brokerageShare+=Cne(u),g){const v=g.y*1e4+g.m*100+g.d;g.y===n&&g.m===r&&(o.closingThisMonth+=1),v>=a&&v<=l&&(o.closingNext30+=1)}if(g){const v=`${g.y}-${String(g.m).padStart(2,"0")}`,y=d.get(v);y&&(y.deals+=1,y.volume+=h,y.gci+=m,f&&(y.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 Gf(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 Krr(){var i;const{user:s}=_s(),{data:t}=Irs(),{data:n}=uQn(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(je,{className:"border-border/60",children:e.jsxs(Le,{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(Aw,{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 ",Gf(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 Yrr 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 bX="deal-pipeline-detail-sheet";function _X(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${(s/1e3).toFixed(0)}K`:`$${Math.round(s).toLocaleString()}`}function Zrr(){var Ur;const s=RK(),{data:t,isLoading:n}=Wie(),{data:r,isLoading:a,refetch:i}=QK(),{data:l,isLoading:o}=vXn(),c=krs(),d=hXn(),[u,h]=j.useState("board"),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[v,y]=j.useState(null),[b,w]=j.useState(null),[S,A]=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"),[Z,X]=j.useState("all"),[ae,le]=j.useState("all"),[re,te]=j.useState(null),{data:J}=Dis(),{data:ce}=aQn(),[ve,fe]=j.useState(!1),[ue,be]=j.useState(!1),[Ee,ke]=j.useState(new Set),[Ie,Fe]=j.useState(!0),Ne=j.useRef(!1),[Be,Se]=j.useState(null),{data:Ae}=Ow(),{isTeamLeader:Ce,teamMembers:qe}=nQn(),ze=j.useMemo(()=>Array.from(Ee),[Ee]),{data:Ve}=rQn(ze),ht=j.useMemo(()=>{const Wn=new Map;return qe.forEach(Sn=>Wn.set(Sn.id,{name:Sn.name,avatar_url:Sn.avatar_url,color:Sn.color})),Wn},[qe]),Qe=j.useCallback(Wn=>Wn.owner_user_id&&ht.get(Wn.owner_user_id)||null,[ht]),at=j.useCallback(Wn=>{ke(Sn=>{const Fn=new Set(Sn);return Fn.has(Wn)?Fn.delete(Wn):Fn.add(Wn),Fn})},[]);j.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[rt,Ke]=Nc(),Je=j.useRef(!1);j.useEffect(()=>{const Wn=rt.get("deal");if(Wn&&r&&r.length>0&&!Je.current){const Sn=r.find(Fn=>Fn.id===Wn);Sn&&(Je.current=!0,y(Sn),x(!0),rt.delete("deal"),Ke(rt,{replace:!0}))}},[r,rt]);const ft=j.useMemo(()=>{if(!Ve||!t)return[];const Wn=new Map(t.map(Sn=>[Sn.name,Sn.id]));return Ve.map(Sn=>{const Fn=Sn._stage_name&&Wn.get(Sn._stage_name)||null;return{...Sn,stage_id:Fn||Sn.stage_id}})},[Ve,t]),gt=j.useMemo(()=>[...Ce&&!Ie?[]:r||[],...ft],[r,ft,Ce,Ie]);j.useEffect(()=>{if(Ne.current||gt.length===0)return;Ne.current=!0;const Wn=sessionStorage.getItem(bX);if(Wn)try{const Sn=JSON.parse(Wn);if(!Sn.open||!Sn.dealId)return;const Fn=gt.find(bn=>bn.id===Sn.dealId);Fn&&(y(Fn),x(!0))}catch{sessionStorage.removeItem(bX)}},[gt]),j.useEffect(()=>{g&&(v!=null&&v.id)?sessionStorage.setItem(bX,JSON.stringify({dealId:v.id,open:!0})):sessionStorage.removeItem(bX)},[g,v==null?void 0:v.id]);const es=j.useMemo(()=>{const Wn={},Sn=new Date;return Sn.setHours(0,0,0,0),(J||[]).forEach(Fn=>{!Fn.deal_id||Fn.status==="done"||!Fn.due_date||kh(Fn.due_date){const Wn=new Set((t||[]).filter(Lr=>Lr.is_won_stage).map(Lr=>Lr.id)),Sn=new Set((t||[]).filter(Lr=>Lr.is_lost_stage).map(Lr=>Lr.id)),Fn=new Date;Fn.setHours(0,0,0,0);const bn=new Date(Fn);bn.setDate(bn.getDate()+7);const xs=new Date(Fn);xs.setDate(xs.getDate()-14);const Tr={closing_soon:new Set,past_due:new Set,overdue_tasks:new Set,stalled:new Set};return gt.forEach(Lr=>{if(!(Lr.stage_id&&(Wn.has(Lr.stage_id)||Sn.has(Lr.stage_id)))){if(Lr.target_close_date){const Xn=kh(Lr.target_close_date);Xn[{key:"closing_soon",count:bs.closing_soon.size},{key:"past_due",count:bs.past_due.size},{key:"overdue_tasks",count:bs.overdue_tasks.size},{key:"stalled",count:bs.stalled.size}],[bs]),Ft=gt.filter(Wn=>{var Bn,cr,Pa,ii,$i,Ln;const Sn=U.toLowerCase(),Fn=Ht[Wn.id]||[],bn=!Sn||Wn.deal_name.toLowerCase().includes(Sn)||((cr=(Bn=Wn.contact)==null?void 0:Bn.first_name)==null?void 0:cr.toLowerCase().includes(Sn))||((ii=(Pa=Wn.contact)==null?void 0:Pa.last_name)==null?void 0:ii.toLowerCase().includes(Sn))||(($i=Wn.property_address)==null?void 0:$i.toLowerCase().includes(Sn))||((Ln=Wn.city)==null?void 0:Ln.toLowerCase().includes(Sn))||Fn.some(xa=>xa.toLowerCase().includes(Sn)),xs=V==="all"||Wn.deal_type===V,Tr=Z==="all"||Fn.includes(Z),Lr=Wn.actual_close_date||Wn.target_close_date||Wn.contract_date||Wn.created_at,la=Lr?String(Lr).slice(0,4):null,Xn=ae==="all"||la===ae,wr=!re||bs[re].has(Wn.id);return bn&&xs&&Tr&&Xn&&wr}),is=j.useMemo(()=>{const Wn=new Set;return Wn.add(String(new Date().getFullYear())),gt.forEach(Sn=>{const Fn=Sn.actual_close_date||Sn.target_close_date||Sn.contract_date||Sn.created_at;Fn&&Wn.add(String(Fn).slice(0,4))}),Array.from(Wn).sort((Sn,Fn)=>Number(Fn)-Number(Sn))},[gt]),jt=j.useMemo(()=>{if(!t)return l||null;const Wn=new Set(t.filter(Lr=>Lr.is_won_stage).map(Lr=>Lr.id)),Sn=new Set(t.filter(Lr=>Lr.is_lost_stage).map(Lr=>Lr.id)),Fn=gt.filter(Lr=>Lr.stage_id&&!Wn.has(Lr.stage_id)&&!Sn.has(Lr.stage_id)),bn=gt.filter(Lr=>Lr.stage_id&&Wn.has(Lr.stage_id)),xs=new Date().getFullYear(),Tr=bn.filter(Lr=>Lr.actual_close_date?new Date(Lr.actual_close_date).getFullYear()===xs:!0);return{totalDeals:gt.length,activeDeals:Fn.length,wonDeals:bn.length,pipelineValue:Fn.reduce((Lr,la)=>Lr+(la.expected_price||0),0),expectedCommission:Fn.reduce((Lr,la)=>Lr+(la.expected_commission||0),0),expectedNetToAgent:Fn.reduce((Lr,la)=>Lr+(gw(la)||0),0),wonValue:bn.reduce((Lr,la)=>Lr+(la.expected_price||0),0),weightedGCI:Fn.reduce((Lr,la)=>Lr+(la.expected_commission||0)*((la.probability??50)/100),0),weightedNet:Fn.reduce((Lr,la)=>Lr+(gw(la)||0)*((la.probability??50)/100),0),ytdWonDeals:Tr.length,ytdWonGCI:Tr.reduce((Lr,la)=>Lr+(la.expected_commission||0),0),ytdWonNet:Tr.reduce((Lr,la)=>Lr+(gw(la)||0),0),projectedAnnualNet:Tr.reduce((Lr,la)=>Lr+(gw(la)||0),0)+Fn.reduce((Lr,la)=>Lr+(gw(la)||0)*((la.probability??50)/100),0)}},[gt,t,l]),zs=Wn=>{y(Wn),x(!0)},yt=Wn=>{w(Wn||null),y(null),f(!0)},gs=Wn=>{y(Wn),x(!1),f(!0)},Ss=Wn=>{x(Wn),Wn||sessionStorage.removeItem(bX)},Ds=(Wn,Sn)=>{A(Wn)},Bt=(Wn,Sn)=>{Wn.preventDefault(),Wn.dataTransfer.dropEffect="move",I(Sn)},zt=async(Wn,Sn)=>{if(Wn.preventDefault(),I(null),!S)return;const Fn=r==null?void 0:r.find(Tr=>Tr.id===S),bn=t==null?void 0:t.find(Tr=>Tr.id===Sn),xs=t==null?void 0:t.find(Tr=>Tr.id===(Fn==null?void 0:Fn.stage_id));if(!Fn||!bn||Fn.stage_id===Sn){A(null);return}Se({dealId:S,dealName:Fn.deal_name,fromStageName:(xs==null?void 0:xs.name)||"Unknown",toStageName:bn.name,toStageId:Sn,isWonStage:bn.is_won_stage,deal:Fn}),A(null)},vs=async()=>{if(!Be)return;const{dealId:Wn,toStageId:Sn,toStageName:Fn,isWonStage:bn,deal:xs}=Be;if(await d.mutateAsync({dealId:Wn,stageId:Sn,stageName:Fn}),ne.success(`Moved to ${Fn}`),bn&&!xs.scorecard_transaction_id){const Tr={...xs,stage_id:Sn};O(Tr),R(!0)}},dn=j.useCallback(async(Wn,Sn,Fn)=>{const bn=r==null?void 0:r.find(Lr=>Lr.id===Wn),xs=t==null?void 0:t.find(Lr=>Lr.id===Sn),Tr=t==null?void 0:t.find(Lr=>Lr.id===(bn==null?void 0:bn.stage_id));!bn||!xs||bn.stage_id===Sn||Se({dealId:Wn,dealName:bn.deal_name,fromStageName:(Tr==null?void 0:Tr.name)||"Unknown",toStageName:Fn,toStageId:Sn,isWonStage:xs.is_won_stage,deal:bn})},[r,t]),Ks=Wn=>Ft.filter(Sn=>Sn.stage_id===Wn),Cn=n||a,Rr=s?"list":u,ia=[{label:"Active Deals",value:(jt==null?void 0:jt.activeDeals)||0,hint:"Deals still in play"},{label:"Weighted GCI",value:_X((jt==null?void 0:jt.weightedGCI)||0),hint:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:_X((jt==null?void 0:jt.weightedNet)||0),hint:"Net to agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:_X((jt==null?void 0:jt.ytdWonNet)||0),subtitle:`${(jt==null?void 0:jt.ytdWonDeals)||0} deals`,hint:"Net commission from deals closed this year"},{label:"Projected Annual",value:_X((jt==null?void 0:jt.projectedAnnualNet)||0),hint:"YTD closed net + weighted active net"}],Hs=[...V!=="all"?[{key:"type",label:`Type: ${V}`,onClear:()=>G("all")}]:[],...ae!=="all"?[{key:"year",label:`Year: ${ae}`,onClear:()=>le("all")}]:[],...Z!=="all"?[{key:"tag",label:`Tag: ${Z}`,onClear:()=>X("all")}]:[],...U?[{key:"search",label:`"${U}"`,onClear:()=>W("")}]:[],...re?[{key:"attention",label:"Needs attention",onClear:()=>te(null)}]:[]],Br=()=>{W(""),G("all"),X("all"),le("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(Urr,{summary:`${(jt==null?void 0:jt.activeDeals)||0} active deals • ${_X((jt==null?void 0:jt.weightedNet)||0)} weighted net`,stats:Rr==="portals"?[]:ia,search:U,onSearchChange:W,onAddDeal:()=>yt(),onRefresh:()=>i(),onTeam:Ae&&!Ce?()=>fe(!0):void 0,showSearch:Rr!=="portals",activeFilters:Hs,onClearAll:Br,resultLabel:Hs.length>0?`${Ft.length} of ${gt.length} deals`:null,viewControls:s?null:e.jsx(vk,{children:e.jsx("div",{className:"hub-glass flex items-center gap-0.5 rounded-full p-1",children:[{mode:"board",icon:Xf,label:"Board",hint:"Kanban board view"},{mode:"list",icon:E0,label:"List",hint:"Grouped list view"},{mode:"table",icon:tV,label:"Table",hint:"Sortable table view"},{mode:"portals",icon:wn,label:"Portals",hint:"Client portal management"}].map(({mode:Wn,icon:Sn,label:Fn,hint:bn})=>e.jsxs(ry,{children:[e.jsx(ay,{asChild:!0,children:e.jsxs("button",{onClick:()=>h(Wn),className:Pt("inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-colors",u===Wn?"bg-background text-foreground shadow-sm":"opacity-80 hover:opacity-100"),children:[e.jsx(Sn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Fn})]})}),e.jsx(vx,{children:bn})]},Wn))})}),filters:Rr!=="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:le,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"}),is.map(Wn=>e.jsx(Ge,{value:Wn,children:Wn},Wn))]})]}),e.jsxs(ms,{value:Z,onValueChange:X,children:[e.jsxs(us,{className:"hub-glass h-10 w-[150px] rounded-full border-0 text-sm",children:[e.jsx(Cp,{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"}),as.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),as.map(Wn=>e.jsx(Ge,{value:Wn,children:Wn},Wn))]})]})]}):null}),e.jsx(Krr,{}),Rr!=="portals"&&e.jsx(Vrr,{items:Ut,active:re,onToggle:Wn=>te(Sn=>Sn===Wn?null:Wn)})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Ce&&!s&&qe.length>0&&e.jsx(sQn,{members:qe,enabledMembers:Ee,onToggleMember:at,isOpen:ue,onToggleOpen:()=>be(Wn=>!Wn),showOwnDeals:Ie,onToggleOwnDeals:()=>Fe(Wn=>!Wn)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:Cn?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(Wn=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(xn,{className:"h-full rounded-xl"})},Wn))}):Rr==="board"?e.jsxs(go,{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(Wn=>e.jsx(lQn,{stage:Wn,deals:Ks(Wn.id),onDealClick:zs,onAddDeal:yt,onDragStart:Ds,onDragOver:Bt,onDrop:zt,isDragOver:E===Wn.id,isWonStage:Wn.is_won_stage,isLostStage:Wn.is_lost_stage,getOwnerInfo:Qe,tagsByDeal:Ht,overdueTasksByDeal:es},Wn.id))}),e.jsx(Iae,{orientation:"horizontal"})]}):Rr==="table"?e.jsx(go,{className:"h-full",children:e.jsx(krr,{deals:Ft,stages:t||[],onDealClick:zs,onStageChange:dn})}):Rr==="portals"?e.jsx(Ois,{}):e.jsx(go,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(Wn=>{const Sn=Ks(Wn.id);return Sn.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:Wn.color}}),e.jsx("h3",{className:"font-semibold",children:Wn.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",Sn.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:Sn.map(Fn=>e.jsx(Prs,{deal:Fn,onClick:()=>zs(Fn),stages:t,onStageChange:dn,showStagePicker:!0,isWonStage:Wn.is_won_stage,isLostStage:Wn.is_lost_stage,ownerInfo:Qe(Fn),tags:Ht[Fn.id]||[],overdueTaskCount:es[Fn.id]||0},Fn.id))})]},Wn.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(Xf,{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:()=>yt(),children:[e.jsx(cn,{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:Br,children:"Clear Filters"})]})]})})})]})]}),e.jsx(yQn,{open:m,onOpenChange:f,deal:v,defaultStageId:b}),e.jsx(wrr,{deal:v,open:g,onOpenChange:Ss,onEdit:gs,isWonStage:v?(Ur=t==null?void 0:t.find(Wn=>Wn.id===v.stage_id))==null?void 0:Ur.is_won_stage:!1,onAddToScorecard:Wn=>{O(Wn),R(!0),x(!1)}}),e.jsx(jrr,{open:P,onOpenChange:R,deal:D,onComplete:()=>{i(),O(null)}}),Be&&e.jsx(Drr,{open:!!Be,onOpenChange:Wn=>{Wn||Se(null)},dealId:Be.dealId,dealName:Be.dealName,fromStageName:Be.fromStageName,toStageName:Be.toStageName,toStageId:Be.toStageId,onConfirm:vs}),e.jsx(eQn,{open:ve,onOpenChange:fe})]})}function Xrr(){return e.jsx(Yrr,{children:e.jsx(Zrr,{})})}function IPe({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"),[v,y]=j.useState(!1),b=Cnr(),w=()=>{d(null),h(""),f(""),x("other"),y(!1),o.current&&(o.current.value="")},S=E=>{if(E){if(E.type!=="application/pdf"&&!E.name.toLowerCase().endsWith(".pdf")){ne.error("Only PDF files can be uploaded.");return}if(E.size>Sis){ne.error("That PDF is larger than the 20MB limit.");return}d(E),!u&&!l&&h(E.name.replace(/\.pdf$/i,""))}},A=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});ne.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){ne.error((E==null?void 0:E.message)||"Upload failed")}};return e.jsx(Os,{open:s,onOpenChange:E=>{E||w(),t(E)},children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:l?`New version of ${r}`:"Upload a form template"}),e.jsxs(Er,{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(Qr,{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:vlt(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:xlt.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:v,onCheckedChange:E=>y(!!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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:A,disabled:!c||!v||b.isPending,children:[b.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),b.isPending?"Reading PDF…":"Upload"]})]})]})})}function ZXe(s){return s.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").toLowerCase().trim()}function HAt(s){return ZXe(s).split(" ").filter(Boolean)}function Qrr(s,t,n){const r=ZXe(s),a=new Set(HAt(s));let i=0;const l=[t,...n];for(const o of l){const c=ZXe(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=HAt(o),u=d.filter(h=>a.has(h)).length;u>0&&(i=Math.max(i,Math.round(u/d.length*45)))}return i}function Jrr(s){if(!s)return null;let t=null;for(const n of NW){const r=Qrr(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 ear=["Deal","Contact","Agent","Other"],eUe="__blank__",tUe="__static__";function zis({version:s}){const{data:t,isLoading:n}=aoe(s.id),r=Rnr(),[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),v=Jrr(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:(v==null?void 0:v.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(v=>v.pdf_field_name===f?{...v,...g}:v))},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}))),ne.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)}),ne.success("Field mapping saved")}catch(f){ne.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(Ct,{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(wn,{className:"mr-1.5 h-4 w-4"})," Apply suggestions"]}),e.jsxs($,{size:"sm",onClick:m,disabled:r.isPending,children:[r.isPending?e.jsx(Ct,{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"?tUe:f.merge_key?f.merge_key:eUe;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($e,{variant:"secondary",className:"mt-1 text-[10px]",children:["Suggested: ",(x=NW.find(v=>v.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:v=>{v===eUe?u(f.pdf_field_name,{mapping_mode:"blank",merge_key:null,static_value:null}):v===tUe?u(f.pdf_field_name,{mapping_mode:"static",merge_key:null}):u(f.pdf_field_name,{mapping_mode:"acroform",merge_key:v,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:eUe,children:"Leave blank"}),e.jsx(Ge,{value:tUe,children:"Fixed text…"}),ear.map(v=>e.jsxs(RMs,{children:[e.jsx(pzt,{children:v}),NW.filter(y=>y.group===v).map(y=>e.jsx(Ge,{value:y.key,children:y.label},y.key))]},v))]})]}),f.mapping_mode==="static"&&e.jsx(pe,{className:"flex-1",placeholder:"Fixed text",value:f.static_value||"",onChange:v=>u(f.pdf_field_name,{static_value:v.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(je,{children:e.jsxs(Le,{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."})]})})}Lot.workerSrc=Rot;const bAe={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"}},sUe=["signature","initials","date_signed","printed_name","text"],GAt=12,tar={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"},Yue=s=>Math.min(1,Math.max(0,s));function Bis({version:s,templateName:t,open:n,onOpenChange:r}){const a=Zt(),{data:i=[],isLoading:l}=aoe(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,v]=j.useState(null),[y,b]=j.useState(!1),[w,S]=j.useState(!1),A=j.useRef(null),E=j.useRef([]),I=j.useRef(null),P=Math.min(s.page_count||1,GAt);j.useEffect(()=>{if(!n)return;let X=!1;return c(null),u(null),rFe(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=A.current;return!o||!ae?void 0:((async()=>{try{const re=await o.arrayBuffer(),te=await gPe({data:re}).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 ve=await te.getPage(ce);if(X)return;const fe=ve.getViewport({scale:1}),ue=J/fe.width,be=ve.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=`${fe.height*ue}px`,Ee.dataset.pageIndex=String(ce-1);const ke=document.createElement("canvas");ke.width=Math.floor(be.width),ke.height=Math.floor(be.height),ke.style.width="100%",ke.style.height="100%",ke.className="rounded-md border border-border bg-white",Ee.appendChild(ke),ae.appendChild(Ee),E.current[ce-1]=Ee;const Ie=ke.getContext("2d");Ie&&await ve.render({canvasContext:Ie,viewport:be}).promise}X||m(ce=>[...ce])}catch(re){X||u((re==null?void 0:re.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),v(null)},[n,l,i]),j.useEffect(()=>{const X=le=>{const re=I.current;if(!re)return;const te=(le.clientX-re.startX)/re.pageW,J=(le.clientY-re.startY)/re.pageH;m(ce=>ce.map(ve=>ve.key!==re.key?ve:re.mode==="move"?{...ve,x:Yue(Math.min(re.orig.x+te,1-ve.w)),y:Yue(Math.min(re.orig.y+J,1-ve.h))}:{...ve,w:Math.min(Math.max(.04,re.orig.w+te),1-ve.x),h:Math.min(Math.max(.015,re.orig.h+J),1-ve.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,le)=>{X.stopPropagation(),X.preventDefault();const re=E.current[ae.page_index];if(!re)return;const te=re.getBoundingClientRect();I.current={key:ae.key,mode:le,startX:X.clientX,startY:X.clientY,orig:ae,pageW:te.width,pageH:te.height},v(ae.key)},D=(X,ae)=>{if(f==="select"){v(null);return}const le=E.current[ae];if(!le)return;const re=le.getBoundingClientRect(),te=bAe[f],J=Yue((X.clientX-re.left)/re.width-te.w/2),ce=Yue((X.clientY-re.top)/re.height-te.h/2),ve={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:sUe.includes(f)?"buyer_1":null,label:null,is_required:!0,font_size:null};m(fe=>[...fe,ve]),v(ve.key),g("select")},O=h.find(X=>X.key===x)||null,U=X=>{O&&m(ae=>ae.map(le=>le.key===O.key?{...le,...X}:le))},W=async(X=!1)=>{if(o){S(!0);try{const ae=await o.arrayBuffer(),le=await gPe({data:ae}).promise,re=Math.min(le.numPages,GAt),te=[];for(let ue=1;ue<=re;ue++){const be=await le.getPage(ue),Ee=be.getViewport({scale:1}),ke=be.getViewport({scale:Math.min(1e3/Ee.width,1.6)}),Ie=document.createElement("canvas");Ie.width=Math.floor(ke.width),Ie.height=Math.floor(ke.height);const Fe=Ie.getContext("2d");Fe&&(Fe.fillStyle="#ffffff",Fe.fillRect(0,0,Ie.width,Ie.height),await be.render({canvasContext:Fe,viewport:ke}).promise,te.push({index:ue-1,image:Ie.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 ve=(J==null?void 0:J.fields)||[];if(!ve.length){ne.info("The scan did not find any blank fields on this form. Place them manually below.");return}const fe=ve.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,...fe]),v(null),ne.success(`${fe.length} field${fe.length===1?"":"s"} placed${J!=null&&J.cached?" (from the earlier scan)":""}. Review, nudge, then save.`)}catch(ae){ne.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=>sUe.includes(ae.field_kind));for(const ae of X)if(!ae.signer_role){ne.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 le=h.map((ce,ve)=>({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:sUe.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:ve}));if(le.length){const{error:ce}=await q.from("form_field_mappings").insert(le);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;ne.success("Placement saved"),a.invalidateQueries({queryKey:["form-field-mappings",s.id]}),a.invalidateQueries({queryKey:["form-templates"]}),r(!1)}catch(ae){ne.error((ae==null?void 0:ae.message)||"Could not save placement")}finally{b(!1)}},G=[{tool:"select",label:"Select",icon:zJ},{tool:"data",label:"Merge field",icon:eP},{tool:"signature",label:"Signature",icon:_f},{tool:"initials",label:"Initials",icon:aV},{tool:"date_signed",label:"Date signed",icon:Wc},{tool:"printed_name",label:"Printed name",icon:sl},{tool:"text",label:"Text input",icon:rV}],Z=s.page_count||1;return e.jsx(Os,{open:n,onOpenChange:r,children:e.jsxs(Fs,{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($s,{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(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(wn,{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(Ct,{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:A,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?bAe[O.field_kind].label:"Field settings"}),e.jsx(go,{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}),NW.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:_lt.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:bAe[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(jn,{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]),v(X.key)},children:[e.jsx(Za,{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)),v(null)},children:[e.jsx(qn,{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:y,children:[y?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save placement"]})})]})]}),e.jsx(sar,{boxes:h,pageRefs:E,selectedKey:x,onSelect:v,onDragStart:R})]})})}function sar({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(nar,{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":tar[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=NW.find(d=>d.key===l.merge_key))==null?void 0:c.label)||l.merge_key:l.static_value||"Data":`${l.label||bAe[l.field_kind].label} · ${aFe(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 nar({target:s,children:t}){return yv.createPortal(t,s)}function rar({templates:s}){const{data:t=[],isLoading:n}=Pis(),r=Unr(),a=qnr(),[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((y,b)=>y.sort_order-b.sort_order).map(y=>y.template_id))))},[i]);const f=s.filter(y=>{var b;return((b=yx(y))==null?void 0:b.mapping_status)==="mapped"}),g=y=>m(b=>b.includes(y)?b.filter(w=>w!==y):[...b,y]),x=(y,b)=>m(w=>{const S=[...w],A=y+b;return A<0||A>=S.length?w:([S[y],S[A]]=[S[A],S[y]],S)}),v=async()=>{if(!o.trim())return ne.error("Give the packet a name");if(!h.length)return ne.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}),ne.success(i==="new"?"Packet created":"Packet updated"),l(null)}catch(y){ne.error((y==null?void 0:y.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(T4,{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(cn,{className:"mr-2 h-4 w-4"})," New packet"]})]}),n?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length===0?e.jsx(je,{className:"border-dashed",children:e.jsx(Le,{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(y=>{const b=wlt(y,s);return e.jsx(je,{children:e.jsxs(Le,{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(T4,{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:y.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($e,{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(y),children:[e.jsx(pi,{className:"mr-1 h-3 w-3"})," Edit"]}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:async()=>{await mo(`Delete the "${y.name}" packet? The forms themselves are kept.`)&&(await a.mutateAsync(y.id),ne.success("Packet deleted"))},children:e.jsx(qn,{className:"h-3 w-3"})})]})]})]})},y.id)})}),e.jsx(Os,{open:!!i,onOpenChange:y=>!y&&l(null),children:e.jsxs(Fs,{className:"flex max-h-[88vh] max-w-lg flex-col overflow-hidden",children:[e.jsxs(Us,{children:[e.jsx($s,{children:i==="new"?"New form packet":"Edit packet"}),e.jsx(Er,{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:y=>c(y.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:y=>u(y.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Forms in this packet"}),e.jsx(go,{className:"max-h-56 rounded-lg border",children:e.jsx("div",{className:"divide-y",children:f.map(y=>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(y.id),onCheckedChange:()=>g(y.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:y.name})]},y.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((y,b)=>{const w=s.find(S=>S.id===y);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(Lg,{className:"h-3 w-3"})})]},y)})})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:r.isPending,children:[r.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Save packet"]})]})]})})]})}function aar(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 kis(s.templateBytes,t,s.values),r=n.bytes.buffer.slice(n.bytes.byteOffset,n.bytes.byteOffset+n.bytes.byteLength),a=await e3.load(r,{updateMetadata:!1}),i=await a.embedFont(jW.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),v=Number(d.width??(g?.2:140))*(g?m:1),y=Number(d.height??(g?.04:24))*(g?f:1),b=Number(d.pos_y)*(g?f:1),w=g?f-b-y:b;if(u.png){const S=aar(u.png);if(!S){o.push("signature");continue}const A=await a.embedPng(S),E=Math.min(v/A.width,y/A.height),I=A.width*E,P=A.height*E;h.drawImage(A,{x:x+(v-I)/2,y:w+(y-P)/2,width:I,height:P})}else{const S=u.text.trim(),A=Math.min(11,Math.max(7,y*.6));h.drawText(S,{x:x+1,y:w+Math.max(2,(y-A)/2),size:A,font:i,color:Sh(0,0,0),maxWidth:Math.max(10,v-2)})}}return{bytes:await a.save(),skipped:o}}const $is='"Segoe Script","Brush Script MT",cursive';function oar(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 ${$is}`,n.fillText(s,t.width/2,t.height/2+24),t.toDataURL("image/png")}function lar({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(pa,{defaultValue:"draw",className:"w-full",children:[e.jsxs(ga,{className:"grid w-full grid-cols-2",children:[e.jsx(Xt,{value:"draw",children:"Draw"}),e.jsx(Xt,{value:"type",children:"Type"})]}),e.jsxs(Qt,{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(Aq,{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(Qt,{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:$is},children:a||" "})}),e.jsxs($,{type:"button",size:"sm",className:"w-full",disabled:!a.trim(),onClick:()=>t(oar(a.trim())),children:["Use this ",s]})]})]})}const car=["signature","initials","date_signed","printed_name","text"],dar={signature:"Signature",initials:"Initials",date_signed:"Date signed",printed_name:"Printed name",text:"Text"};function uar({open:s,onOpenChange:t,template:n,version:r}){const a=Sa(),{data:i=[],isLoading:l}=aoe(s?r.id:void 0),{data:o=[]}=QK(),[c,d]=j.useState(""),{data:u}=blt(s&&c?c:void 0),[h,m]=j.useState({}),[f,g]=j.useState({}),[x,v]=j.useState(null),[y,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&&car.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({}),v(null),d(""))},[s]);const A=R=>R.merge_key||R.pdf_field_name||R.id,E=R=>{v(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}),ne.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 rFe(r.storage_path),D={...h},{bytes:O}=await iar({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"}),Z=URL.createObjectURL(G),X=document.createElement("a");if(X.href=Z,X.download=W,X.click(),URL.revokeObjectURL(Z),c&&a){const ae=`${a}/${c}/${crypto.randomUUID()}.pdf`,{error:le}=await q.storage.from("deal-files").upload(ae,G,{contentType:"application/pdf"});if(le)throw le;const{error:re}=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(re)throw re;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}}),ne.success("Saved to the deal and downloaded")}else ne.success("Your signed PDF is downloading");t(!1)}catch(R){ne.error(glt(R))}finally{b(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"flex max-h-[90vh] max-w-2xl flex-col overflow-hidden",children:[e.jsxs(Us,{children:[e.jsxs($s,{children:["Fill & sign — ",n.name]}),e.jsx(Er,{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(Ct,{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=A(R),O=R.merge_key?((W=Eis.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(_f,{className:"h-4 w-4"})," Your signature"]}),S.length>0&&e.jsxs($e,{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:()=>v(null),children:"Redo"})]}):e.jsx(lar,{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:[dar[R.field_kind||"text"]," · page ",(R.page_index??0)+1,R.signer_role?` · ${aFe(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(Vr,{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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:y,children:"Cancel"}),e.jsxs($,{onClick:P,disabled:y||l,children:[y?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ji,{className:"mr-2 h-4 w-4"}),"Finish & download"]})]})]})})}function har({status:s}){return s==="mapped"?e.jsx($e,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Ready"}):s==="needs_placement"?e.jsx($e,{variant:"outline",children:"Needs field placement"}):e.jsx($e,{variant:"secondary",children:"Needs mapping"})}function mar(){var X,ae;const{data:s=[],isLoading:t,error:n}=ylt(),{data:r=[]}=QK(),a=Cis(),i=Ais(),l=Anr(),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,v]=j.useState(null),[y,b]=j.useState(""),[w,S]=j.useState(null),[A,E]=j.useState("generate"),[I,P]=j.useState(null),[R,D]=j.useState("all"),O=s.some(le=>le.scope==="brokerage"),U=s.filter(le=>le.name.toLowerCase().includes(f.trim().toLowerCase())).filter(le=>R==="all"||(le.scope||"mine")===R).sort((le,re)=>(le.scope==="brokerage"?1:0)-(re.scope==="brokerage"?1:0)),W=async le=>{try{await l.mutateAsync(le),ne.success(`"${le.name}" copied to your forms`)}catch(re){ne.error((re==null?void 0:re.message)||"Could not copy that form")}},V=h?s.find(le=>le.id===h.id)||h:null,G=yx(V),Z=async le=>{if(await mo(`Delete "${le.name}" and all of its versions? Forms already generated stay on their deals.`))try{await i.mutateAsync(le),(h==null?void 0:h.id)===le.id&&m(null),ne.success("Template deleted")}catch(re){ne.error((re==null?void 0:re.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(cn,{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:le=>g(le.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(([le,re])=>e.jsx($,{size:"sm",variant:R===le?"secondary":"ghost",className:"h-7 text-xs",onClick:()=>D(le),children:re},le))})]}),t&&e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),n&&e.jsx(je,{children:e.jsx(Le,{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(je,{className:"border-dashed",children:e.jsxs(Le,{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(Qr,{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(le=>{var J;const re=yx(le),te=le.scope==="brokerage";return e.jsx(je,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Le,{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(Qr,{className:"h-5 w-5 text-primary"})}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>m(le),children:[e.jsx("p",{className:"truncate font-medium",children:le.name}),te&&e.jsxs($e,{variant:"outline",className:"mt-1 gap-1 text-[10px]",children:[e.jsx(wi,{className:"h-3 w-3"})," Brokerage form"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(J=xlt.find(ce=>ce.value===le.category))==null?void 0:J.label," · v",(re==null?void 0:re.version_number)??1,re?` · ${re.page_count} page${re.page_count===1?"":"s"}`:""]})]}),e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsx(Cu,{align:"end",children:te?e.jsxs(e.Fragment,{children:[e.jsx(ja,{onClick:()=>m(le),children:"View details"}),e.jsxs(ja,{disabled:l.isPending,onClick:()=>W(le),children:[e.jsx(Za,{className:"mr-2 h-4 w-4"})," Copy to my forms"]}),e.jsxs(ja,{disabled:(re==null?void 0:re.mapping_status)!=="mapped",onClick:()=>P(le),children:[e.jsx(_f,{className:"mr-2 h-4 w-4"})," Fill & sign"]})]}):e.jsxs(e.Fragment,{children:[e.jsx(ja,{onClick:()=>m(le),children:"Open & map fields"}),e.jsxs(ja,{onClick:()=>S(le),children:[e.jsx(Xf,{className:"mr-2 h-4 w-4"})," Place fields & signatures"]}),e.jsxs(ja,{disabled:(re==null?void 0:re.mapping_status)!=="mapped",onClick:()=>{E("sign"),v(le),b("")},children:[e.jsx(_f,{className:"mr-2 h-4 w-4"})," Send for signature"]}),e.jsxs(ja,{disabled:(re==null?void 0:re.mapping_status)!=="mapped",onClick:()=>P(le),children:[e.jsx(_f,{className:"mr-2 h-4 w-4"})," Fill & sign myself"]}),e.jsxs(ja,{onClick:()=>u(le),children:[e.jsx(ni,{className:"mr-2 h-4 w-4"})," Upload new version"]}),e.jsxs(ja,{onClick:()=>a.mutate({id:le.id,patch:{is_archived:!0}}),children:[e.jsx(wv,{className:"mr-2 h-4 w-4"})," Archive"]}),e.jsxs(ja,{className:"text-destructive",onClick:()=>Z(le),children:[e.jsx(qn,{className:"mr-2 h-4 w-4"})," Delete"]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(har,{status:re==null?void 0:re.mapping_status}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs($,{variant:"ghost",size:"sm",disabled:(re==null?void 0:re.mapping_status)!=="mapped",onClick:()=>P(le),children:[e.jsx(_f,{className:"mr-1.5 h-4 w-4"})," Fill & sign"]}),e.jsxs($,{variant:"ghost",size:"sm",disabled:(re==null?void 0:re.mapping_status)!=="mapped",onClick:()=>{E("sign"),v(le),b("")},children:[e.jsx(_f,{className:"mr-1.5 h-4 w-4"})," Send"]}),e.jsxs($,{variant:"ghost",size:"sm",disabled:(re==null?void 0:re.mapping_status)!=="mapped",onClick:()=>{E("generate"),v(le),b("")},children:[e.jsx(Eq,{className:"mr-1.5 h-4 w-4"})," Use"]})]})]})]})},le.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(rar,{templates:s})})]}),e.jsx(Vy,{open:!!V,onOpenChange:le=>!le&&m(null),children:e.jsxs(uy,{side:"right",className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(I0,{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(Va,{className:"h-3 w-3"})," Back"]}),e.jsx(L0,{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," · ",vlt(G.file_size)," · uploaded ",Js(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(wi,{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(Za,{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(Xf,{className:"mr-2 h-4 w-4"})," Place fields & signatures on the document"]}),e.jsx(zis,{version:G})]})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This template has no uploaded version yet."})]})]})}),e.jsx(IPe,{open:o,onOpenChange:c}),e.jsx(IPe,{open:!!d,onOpenChange:le=>!le&&u(null),templateId:d==null?void 0:d.id,templateName:d==null?void 0:d.name}),e.jsx(Vy,{open:!!x&&!y,onOpenChange:le=>!le&&v(null),children:e.jsxs(uy,{side:"bottom",className:"space-y-4",children:[e.jsx(I0,{className:"text-left",children:e.jsx(L0,{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:y,onValueChange:b,children:[e.jsx(us,{className:"max-w-md",children:e.jsx(fs,{placeholder:"Select a deal"})}),e.jsx(hs,{children:r.map(le=>e.jsx(Ge,{value:le.id,children:le.deal_name},le.id))})]})]})}),x&&y&&A==="generate"&&e.jsx(Tis,{open:!0,onOpenChange:le=>{le||(v(null),b(""))},dealId:y,dealName:(X=r.find(le=>le.id===y))==null?void 0:X.deal_name,initialTemplateId:x.id}),x&&y&&A==="sign"&&e.jsx(Iis,{open:!0,onOpenChange:le=>{le||(v(null),b(""))},dealId:y,dealName:(ae=r.find(le=>le.id===y))==null?void 0:ae.deal_name,initialTemplateId:x.id}),w&&yx(w)&&e.jsx(Bis,{open:!0,onOpenChange:le=>!le&&S(null),version:yx(w),templateName:w.name}),I&&yx(I)&&e.jsx(uar,{open:!0,onOpenChange:le=>!le&&P(null),template:I,version:yx(I)})]})}function Uis({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var W;const i=Crr(),l=Arr(),{data:o}=QK(),c=Sa(),{data:d}=st({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"),[v,y]=j.useState("none"),[b,w]=j.useState("medium"),[S,A]=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"),y(n.contact_id||"none"),w(n.priority),A(n.status),I(n.due_date?pv(n.due_date):void 0)):(h(""),f(""),x(r||"none"),y("none"),w("medium"),A("todo"),I(void 0))},[n,s,r]);const U=async()=>{if(!u.trim()){ne.error("Task title is required");return}try{const V={title:u.trim(),description:m.trim()||null,deal_id:g==="none"?null:g,contact_id:v==="none"?null:v,stage_id:a||null,priority:b,status:S,due_date:E?Js(E,"yyyy-MM-dd"):null};n?(await l.mutateAsync({id:n.id,...V}),ne.success("Task updated")):(await i.mutateAsync(V),ne.success("Task created")),t(!1)}catch{ne.error("Failed to save task")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[480px]",children:[e.jsx(Us,{children:e.jsx($s,{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=>A(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(Gd,{children:[e.jsx(Wd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("w-full justify-start text-left font-normal",!E&&"text-muted-foreground"),children:[e.jsx(Ea,{className:"mr-2 h-4 w-4"}),E?Js(E,"PPP"):"Pick a date"]})}),e.jsx(Dd,{className:"w-auto p-0",align:"start",children:e.jsx(A2,{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(Gd,{open:P,onOpenChange:R,children:[e.jsx(Wd,{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(wi,{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(kw,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Dd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(N2,{children:[e.jsx(k2,{placeholder:"Search deals..."}),e.jsxs(S2,{children:[e.jsx(C2,{children:"No deals found."}),e.jsxs(Rw,{children:[e.jsxs(h1,{value:"no-deal",onSelect:()=>{x("none"),R(!1)},children:[e.jsx(ma,{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(h1,{value:V.deal_name,onSelect:()=>{x(V.id),R(!1)},children:[e.jsx(ma,{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(Gd,{open:D,onOpenChange:O,children:[e.jsx(Wd,{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"}),v!=="none"?(()=>{const V=d==null?void 0:d.find(G=>G.id===v);return V?`${V.first_name} ${V.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(kw,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Dd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(N2,{children:[e.jsx(k2,{placeholder:"Search contacts..."}),e.jsxs(S2,{children:[e.jsx(C2,{children:"No contacts found."}),e.jsxs(Rw,{children:[e.jsxs(h1,{value:"no-contact",onSelect:()=>{y("none"),O(!1)},children:[e.jsx(ma,{className:Pt("mr-2 h-4 w-4",v==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(V=>e.jsxs(h1,{value:`${V.first_name} ${V.last_name}`,onSelect:()=>{y(V.id),O(!1)},children:[e.jsx(ma,{className:Pt("mr-2 h-4 w-4",v===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 far={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 par({tasks:s}){const t=iFe(),n=Err(),r=Zn(),[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{ne.error("Failed to update task")}},o=async u=>{try{await n.mutateAsync(u),ne.success("Task deleted")}catch{ne.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(Vr,{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(WAt,{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(wi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:h.dealName}),e.jsxs($e,{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(WAt,{task:m,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:f=>r(`/mission-control/pipeline?deal=${f}`)},m.id))]},u)),a&&e.jsx(Uis,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function WAt({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&R4(pv(s.due_date))&&!bv(pv(s.due_date)),o=!i&&s.due_date&&bv(pv(s.due_date)),c=far[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(Vr,{className:"h-5 w-5 text-emerald-500"}):e.jsx(Dg,{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($e,{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(ca,{className:"h-3 w-3"}),Js(pv(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(bp,{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(qn,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const gar=[{status:"todo",label:"To Do",icon:Dg,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:ef,color:"border-t-blue-500"},{status:"done",label:"Done",icon:Vr,color:"border-t-emerald-500"}],xar={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function yar({tasks:s}){const t=iFe(),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{ne.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:gar.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($e,{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(bar,{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 bar({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&R4(pv(s.due_date))&&!bv(pv(s.due_date)),a=!n&&s.due_date&&bv(pv(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:xar[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(wi,{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(ca,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",Js(pv(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 KAt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function _ar({tasks:s}){const[t,n]=j.useState(new Date),r=iFe(),a=Zm(t),i=uw(t),l=w1(a),o=TLe(i),c=JMs({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{ne.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(n8(t,1)),children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:Js(t,"MMMM yyyy")}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>n(Av(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=Js(m,"yyyy-MM-dd"),g=d.get(f)||[],x=Dae(m,t),v=bv(m);return e.jsxs("div",{className:Pt("border-r border-b min-h-[100px] p-1",!x&&"bg-muted/30",v&&"bg-primary/5"),children:[e.jsx("div",{className:Pt("text-xs font-medium mb-1 text-right px-1",!x&&"text-muted-foreground/40",v&&"text-primary font-bold"),children:Js(m,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[g.slice(0,3).map(y=>e.jsxs("button",{onClick:()=>h(y),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",y.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[y.status==="done"?e.jsx(Vr,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(Dg,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[KAt[y.priority]," ",y.title]})]},y.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(Vr,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(Dg,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[KAt[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 war={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function jar({open:s,onOpenChange:t,stages:n}){var y;const[r,a]=j.useState(((y=n[0])==null?void 0:y.id)||""),{data:i,isLoading:l}=Mrr(r||void 0),o=Prr(),c=Irr(),[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(""),ne.success("Template added")}catch{ne.error("Failed to add template")}},v=async b=>{try{await c.mutateAsync(b),ne.success("Template deleted")}catch{ne.error("Failed to delete template")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-[560px]",children:[e.jsx(Us,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(yJ,{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(go,{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:war[b.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:b.title}),b.default_due_offset_days&&e.jsxs($e,{variant:"outline",className:"text-[10px]",children:["+",b.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>v(b.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(qn,{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(cn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function Nar(){const{data:s,isLoading:t}=Dis(),{data:n}=Wie(),[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,v]=j.useState(!1),y=j.useMemo(()=>{if(!s)return[];const S=new Map;return s.forEach(A=>{A.deal&&S.set(A.deal.id,A.deal.deal_name)}),Array.from(S,([A,E])=>({id:A,name:E}))},[s]),b=j.useMemo(()=>s?s.filter(S=>{var D,O,U,W;const A=i.toLowerCase(),E=!A||S.title.toLowerCase().includes(A)||((O=(D=S.deal)==null?void 0:D.deal_name)==null?void 0:O.toLowerCase().includes(A))||`${((U=S.contact)==null?void 0:U.first_name)||""} ${((W=S.contact)==null?void 0:W.last_name)||""}`.toLowerCase().includes(A),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&&R4(pv(S.due_date))&&!bv(pv(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(A=>A.status!=="done");return{total:S.length,overdue:S.filter(A=>A.due_date&&R4(pv(A.due_date))&&!bv(pv(A.due_date))).length,dueToday:S.filter(A=>A.due_date&&bv(pv(A.due_date))).length,dueThisWeek:S.filter(A=>A.due_date&&ZIs(pv(A.due_date))).length,completed:s.filter(A=>A.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:()=>v(!0),children:[e.jsx(Sw,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs($,{size:"sm",onClick:()=>g(!0),children:[e.jsx(cn,{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(E0,{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(Al,{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(ca,{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(Wc,{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(Vr,{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"}),y.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(E0,{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(i2,{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(Wc,{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(par,{tasks:b}),r==="kanban"&&e.jsx(yar,{tasks:b}),r==="calendar"&&e.jsx(_ar,{tasks:b})]}),e.jsx(Uis,{open:f,onOpenChange:g}),e.jsx(jar,{open:x,onOpenChange:v,stages:n||[]})]})})}function kar(s){const t=Clt(s);return t?t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""}function Sar({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 Zue({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 Car(){const s=Zn(),{data:t,isLoading:n}=orr(),r=iFe(),[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 A,E,I,P;return((A=S.deal_name)==null?void 0:A.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=>{HQ.forEach(S=>{const A=w[S.key],E=k5(A);A&&E!==null&&E<=30&&b.push({id:`${w.id}-${S.key}`,kind:"date",label:S.label,dealId:w.id,dealName:w.deal_name,date:A,days:E})}),w.tasks.filter(S=>S.status!=="done"&&S.due_date).forEach(S=>{const A=k5(S.due_date);A!==null&&A<=30&&b.push({id:S.id,kind:"task",label:S.title,dealId:w.id,dealName:w.deal_name,date:S.due_date,days:A,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=k5(E.target_close_date);return I!==null&&I>=0&&I<=7}).length,S=b.reduce((E,I)=>E+I.tasks.filter(P=>{const R=k5(P.due_date);return P.status!=="done"&&R!==null&&R<0}).length,0),A=b.reduce((E,I)=>E+(Number(I.expected_price)||0),0);return{active:b.length,closingSoon:w,overdueTasks:S,volume:A}},[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}`),v=async b=>{try{await r.mutateAsync({id:b,status:"done"}),ne.success("Task completed")}catch{ne.error("Could not update task")}},y=({title:b,items:w,tone:S})=>{if(w.length===0)return null;const A=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",A)}),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:()=>v(E.id),"aria-label":`Complete ${E.label}`}):e.jsx(Su,{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," · ",kar(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(_x,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(Zue,{icon:Fg,label:"Active transactions",value:f.active}),e.jsx(Zue,{icon:sh,label:"Closing within 7 days",value:f.closingSoon,tone:"warn"}),e.jsx(Zue,{icon:Al,label:"Overdue tasks",value:f.overdueTasks,tone:f.overdueTasks>0?"danger":"good"}),e.jsx(Zue,{icon:Zl,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(Ct,{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(Su,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"text-sm font-semibold",children:"Deadline Radar"}),e.jsx($e,{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(Vr,{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(y,{title:"Overdue",items:m.overdue,tone:"danger"}),e.jsx(y,{title:"Today",items:m.today,tone:"warn"}),e.jsx(y,{title:"This week",items:m.week,tone:"warn"}),e.jsx(y,{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=k5(b.target_close_date),A=b.tasks.filter(P=>P.status!=="done"),E=A.filter(P=>{const R=k5(P.due_date);return R!==null&&R<0}),I=A.filter(P=>P.due_date).sort((P,R)=>(k5(P.due_date)??0)-(k5(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(Sar,{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($e,{variant:"outline",className:"text-[10px] capitalize",children:b.deal_type}),S!==null&&e.jsx($e,{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($e,{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(Ris,{open:l,onOpenChange:o})]})}function qis(){const s=Sa();return st({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 Aar(){const s=Zt();return mt({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 Ear(){const s=Zt();return mt({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 Tar=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),nUe=[{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"}],Mar={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function Vis(){const{data:s=[],isLoading:t}=qis(),n=Aar(),r=Ear(),[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}),ne.success("Status updated")},h=f=>{const g=l[f.id];n.mutate({id:f.id,agent_notes:g}),o(x=>{const{[f.id]:v,...y}=x;return y}),ne.success("Notes saved")},m=async f=>{await mo(`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(Dl,{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(dl,{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"},...nUe.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(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(je,{children:e.jsxs(Le,{className:"py-12 text-center",children:[e.jsx(dl,{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 y,b;const g=nUe.find(w=>w.value===f.status),x=(y=f.client_portals)==null?void 0:y.slug,v=f.referrer_name||((b=f.client_portals)==null?void 0:b.client_name)||"Anonymous client";return e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(Et,{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(Ea,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:v})," ·"," ",Tar(f.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($e,{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:nUe.map(w=>e.jsx(Ge,{value:w.value,className:"text-xs",children:w.label},w.value))})]})]})]})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.friend_interest&&e.jsx($e,{variant:"secondary",className:"text-xs",children:Mar[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(pn,{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(Ah,{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,...A}=w;return A}),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(Ir,{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(qn,{className:"h-3.5 w-3.5"})})]})]})]},f.id)})})]})}function His({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=rK.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(je,{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(jc,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(ei,{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($e,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx($e,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs($e,{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(pn,{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(cl,{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(Ea,{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(ui,{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(Ta,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(Nx,{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(bp,{className:"w-3.5 h-3.5"})}),n&&e.jsx($,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(qn,{className:"w-3.5 h-3.5"})})]})]})}function Gis({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=a9s(),[c,d]=j.useState({}),[u,h]=j.useState(!1),m=j.useRef(null),f=async v=>{if(!v.type.startsWith("image/")){ne.error("Please select an image");return}if(v.size>5*1024*1024){ne.error("Image must be under 5MB");return}h(!0);try{const y=v.name.split(".").pop()||"png",b=`${r}/${a||i||"misc"}/${Date.now()}.${y}`,{error:w}=await q.storage.from("vendor-logos").upload(b,v,{upsert:!0,contentType:v.type});if(w)throw w;const{data:S}=q.storage.from("vendor-logos").getPublicUrl(b);d(A=>({...A,logo_url:S.publicUrl})),ne.success("Logo uploaded")}catch(y){ne.error(y.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=(v,y)=>d(b=>({...b,[v]:y})),x=async()=>{var v;if(!((v=c.name)!=null&&v.trim())){ne.error("Name is required");return}try{await o.mutateAsync(c),ne.success(n?"Vendor updated":"Vendor added"),t(!1)}catch(y){ne.error(y.message||"Failed to save vendor")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{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:v=>g("name",v.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Company"}),e.jsx(pe,{value:c.company||"",onChange:v=>g("company",v.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:c.category,onValueChange:v=>g("category",v),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:rK.map(v=>e.jsx(Ge,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:c.phone||"",onChange:v=>g("phone",v.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:c.email||"",onChange:v=>g("email",v.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Website"}),e.jsx(pe,{value:c.website||"",onChange:v=>g("website",v.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:v=>{var b;const y=(b=v.target.files)==null?void 0:b[0];y&&f(y),v.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(mr,{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 v;return(v=m.current)==null?void 0:v.click()},disabled:u,children:[u?e.jsx(Ct,{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:v=>g("address",v.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:v=>g("description",v.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:v=>g("action_type",v),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:s9s.map(v=>e.jsx(Ge,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Booking URL (Calendly etc.)"}),e.jsx(pe,{value:c.booking_url||"",onChange:v=>g("booking_url",v.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:v=>g("disclosure_text",v.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(jn,{checked:!!c.is_active,onCheckedChange:v=>g("is_active",v)})]}),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(jn,{checked:!!c.is_featured,onCheckedChange:v=>g("is_featured",v)})]}),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(jn,{checked:!!c.is_required,onCheckedChange:v=>g("is_required",v)})]})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:x,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function Wis({embedded:s=!1}={}){const t=Sa(),{brokerageId:n}=_s(),{data:r,isLoading:a}=r9s(),{data:i={}}=z9t("agent",t),l=F9t(),o=i9s(),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,f]=j.useState(""),[g,x]=j.useState("all"),v=(r==null?void 0:r.vendors)||[],y=(r==null?void 0:r.selections)||[],b=j.useMemo(()=>{const D=new Map;return y.forEach(O=>D.set(O.vendor_id,O.is_visible)),D},[y]),w=j.useMemo(()=>v.filter(D=>!(g!=="all"&&D.category!==g||m&&!`${D.name} ${D.company||""}`.toLowerCase().includes(m.toLowerCase()))),[v,m,g]),S=w.filter(D=>D.owner_type==="agent"),A=w.filter(D=>D.owner_type==="brokerage"),E=async D=>{if(await mo("Delete this vendor?"))try{await l.mutateAsync(D),ne.success("Vendor deleted")}catch(O){ne.error(O.message)}},I=async(D,O)=>{try{await o.mutateAsync({vendorId:D,isVisible:O})}catch(U){ne.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(wx,{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(cn,{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"}),rK.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(pa,{defaultValue:n?"all":"personal",children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"all",children:["All (",w.length,")"]}),n&&e.jsxs(Xt,{value:"brokerage",children:["From Brokerage (",A.length,")"]}),e.jsxs(Xt,{value:"personal",children:["My Personal (",S.length,")"]})]}),e.jsx(Qt,{value:"all",className:"mt-4",children:e.jsx(rUe,{vendors:w,isVisibleInPortals:P,onToggle:I,onEdit:D=>{d(D),h(!0)},onDelete:E,userId:t,clicks:i})}),n&&e.jsx(Qt,{value:"brokerage",className:"mt-4",children:A.length===0?e.jsx(YAt,{icon:e.jsx(wn,{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(rUe,{vendors:A,isVisibleInPortals:P,onToggle:I,userId:t,clicks:i})}),e.jsx(Qt,{value:"personal",className:"mt-4",children:S.length===0?e.jsx(YAt,{icon:e.jsx(wx,{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(cn,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(rUe,{vendors:S,isVisibleInPortals:P,onToggle:I,onEdit:D=>{d(D),h(!0)},onDelete:E,userId:t,clicks:i})})]}),e.jsx(Gis,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?R:e.jsx(Vs,{children:R})}function rUe({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(His,{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 YAt({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 Par(s){return st({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 Iar(s){const t=Zt(),n=()=>{t.invalidateQueries({queryKey:["brokerage-form-folders",s]}),t.invalidateQueries({queryKey:["form-templates"]})},r=mt({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=mt({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=mt({mutationFn:async o=>{const{error:c}=await q.from("brokerage_form_folders").delete().eq("id",o);if(c)throw c},onSuccess:n}),l=mt({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 Lar({status:s}){return s==="mapped"?e.jsx($e,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Ready"}):s==="needs_placement"?e.jsx($e,{variant:"outline",children:"Needs field placement"}):e.jsx($e,{variant:"secondary",children:"Needs mapping"})}function Rar(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=_s(),{data:a=[],isLoading:i}=Snr(s),l=Cis(),o=Ais(),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,f]=j.useState(null),[g,x]=j.useState(null),[v,y]=j.useState(""),[b,w]=j.useState("all"),{data:S=[]}=Par(s),{createFolder:A,deleteFolder:E,moveTemplate:I}=Iar(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 Z=await A.mutateAsync(V);w(Z.id),ne.success("Folder created")}catch(Z){ne.error((Z==null?void 0:Z.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(v.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=yx(D),U=async(V,G)=>{const Z=yx(V);if(G&&(Z==null?void 0:Z.mapping_status)!=="mapped"){ne.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}}),ne.success(G?"Published to your agents":"Unpublished — agents can no longer use it")}catch(X){ne.error((X==null?void 0:X.message)||"Could not update the form")}},W=async V=>{if(await mo(`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),ne.success("Form deleted")}catch(G){ne.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(cn,{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:v,onChange:V=>y(V.target.value)})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:P,children:[e.jsx(wJ,{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(Mq,{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 mo(`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(qn,{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(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),!i&&a.length===0&&e.jsx(je,{className:"border-dashed",children:e.jsxs(Le,{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(wi,{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 Z;const G=yx(V);return e.jsx(je,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Le,{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(Qr,{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:[(Z=xlt.find(X=>X.value===V.category))==null?void 0:Z.label," · v",(G==null?void 0:G.version_number)??1,G?` · ${G.page_count} page${G.page_count===1?"":"s"}`:""]})]}),e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Cu,{align:"end",children:[e.jsx(ja,{onClick:()=>f(V),children:"Open & map fields"}),e.jsxs(ja,{onClick:()=>x(V),children:[e.jsx(Xf,{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(P0,{}),e.jsx(_L,{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(Mq,{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(P0,{})]}),e.jsxs(ja,{onClick:()=>l.mutate({id:V.id,patch:{is_archived:!0,is_published:!1}}),children:[e.jsx(wv,{className:"mr-2 h-4 w-4"})," Archive"]}),e.jsxs(ja,{className:"text-destructive",onClick:()=>W(V),children:[e.jsx(qn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Lar,{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(jn,{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(Vy,{open:!!D,onOpenChange:V=>!V&&f(null),children:e.jsxs(uy,{side:"right",className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(I0,{className:"space-y-1 text-left",children:[e.jsx(L0,{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," ·"," ",vlt(O.file_size)," · uploaded"," ",Js(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(Xf,{className:"mr-2 h-4 w-4"})," Place fields & signatures on the document"]}),e.jsx(zis,{version:O})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This form has no uploaded version yet."})]})]})}),e.jsx(IPe,{open:c,onOpenChange:d,brokerageId:s}),e.jsx(IPe,{open:!!u,onOpenChange:V=>!V&&h(null),templateId:u==null?void 0:u.id,templateName:u==null?void 0:u.name,brokerageId:s}),g&&yx(g)&&e.jsx(Bis,{open:!0,onOpenChange:V=>!V&&x(null),version:yx(g),templateName:g.name})]})}function Dar(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=_s(),{data:a=[],isLoading:i}=n9s(s),{data:l={}}=z9t("brokerage",s),o=F9t(),[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 v=a.filter(b=>!(g!=="all"&&b.category!==g||m&&!`${b.name} ${b.company||""}`.toLowerCase().includes(m.toLowerCase()))),y=async b=>{if(await mo("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(b),ne.success("Vendor deleted")}catch(w){ne.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(wi,{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(cn,{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"}),rK.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..."}):v.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(wi,{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(cn,{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:v.map(b=>e.jsx(His,{vendor:b,onEdit:()=>{d(b),h(!0)},onDelete:()=>y(b.id),clickCount:l[b.id]},b.id))}),e.jsx(Gis,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}function Kis({portalId:s,portalSlug:t,clientName:n,agentName:r}){const{data:a,isLoading:i}=U9t(s),l=q9t(),o=c9s(),[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(""),ne.success("Message sent — your client was emailed")}catch(g){ne.error((g==null?void 0:g.message)||"Could not send message")}};return e.jsx(je,{children:e.jsxs(Le,{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(Ct,{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"," ·"," ",Js(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(Ct,{className:"w-4 h-4 mr-1.5 animate-spin"}):e.jsx(Zr,{className:"w-4 h-4 mr-1.5"}),"Send & notify"]})})]})]})})}function Far({selectedPortalId:s,onSelectPortal:t}){const{data:n,isLoading:r}=V9t(),[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(Ct,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):!n||n.length===0?e.jsx(je,{children:e.jsxs(Le,{className:"p-10 text-center",children:[e.jsx(no,{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(je,{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($e,{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:hu(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(Va,{className:"w-4 h-4 mr-1.5"}),"All conversations"]}),e.jsx(Kis,{portalId:f.portalId,portalSlug:f.slug,clientName:f.clientName})]}):e.jsx(je,{children:e.jsx(Le,{className:"p-10 text-center text-sm text-muted-foreground",children:"Pick a client to see the conversation."})})})]})}const Oar=[{value:"overview",label:"Portals",icon:Xf},{value:"messages",label:"Messages",icon:no},{value:"vendors",label:"Vendors",icon:yb},{value:"referrals",label:"Referrals",icon:dl},{value:"branding",label:"Branding",icon:yd},{value:"questions",label:"Onboarding",icon:Sv}];function zar(){const[s,t]=Nc(),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}=V9t(),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(Dl,{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(wn,{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(s7,{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(br,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(pa,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(ga,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:Oar.map(m=>e.jsxs(Xt,{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($e,{className:"ml-1 h-5 px-1.5",children:h})]},m.value))}),e.jsx(Qt,{value:"overview",className:"mt-6",children:e.jsx(Ois,{})}),e.jsx(Qt,{value:"messages",className:"mt-6",children:e.jsx(Far,{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(Qt,{value:"vendors",className:"mt-6",children:e.jsx(Bar,{})}),e.jsx(Qt,{value:"referrals",className:"mt-6",children:e.jsx($ar,{})}),e.jsx(Qt,{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(yd,{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(Nd,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(Qt,{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(Sv,{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(Nd,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(Fis,{open:i,onOpenChange:l}),e.jsx(Lis,{open:o,onOpenChange:c})]})}function Bar(){return e.jsx(Wis,{embedded:!0})}function $ar(){return e.jsx(Vis,{})}const Y$=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function Uar(s){return st({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 qar(){const{portalId:s}=Wi(),t=Zn(),n=Sa(),{data:r,isLoading:a}=Uar(s),{data:i=[]}=B$n(s),{data:l=[]}=qis(),o=DK(),c=BQt(),d=$Qt(),u=UQt(),[h,m]=j.useState(!1),[f,g]=j.useState(!1),[x,v]=j.useState(!1),[y,b]=j.useState(!1),w=(r==null?void 0:r.portal)??null,S=(r==null?void 0:r.deal)??null,A=j.useMemo(()=>w?l.filter(Z=>Z.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(Ct,{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(br,{to:"/mission-control/client-portals",children:[e.jsx(Va,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const E=oC(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),ne.success("Portal link copied!")},U=async Z=>{try{await o.mutateAsync({id:w.id,is_enabled:Z}),ne.success(Z?"Portal enabled":"Portal disabled")}catch{ne.error("Failed to update")}},W=async()=>{try{await c.mutateAsync(w.id),ne.success("Portal archived")}catch{ne.error("Failed to archive")}},V=async()=>{try{await d.mutateAsync(w.id),ne.success("Portal restored")}catch{ne.error("Failed to restore")}},G=async()=>{try{await u.mutateAsync({id:w.id,dealId:w.deal_id}),ne.success("Portal deleted"),t("/mission-control/client-portals")}catch{ne.error("Failed to delete")}};return e.jsxs(Vs,{children:[e.jsx(Dl,{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(br,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(Va,{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(wn,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:I}),e.jsx($e,{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($e,{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(pn,{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(jn,{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(Za,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs($,{onClick:()=>window.open(E,"_blank"),variant:"outline",size:"sm",children:[e.jsx(Ir,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs($,{onClick:()=>v(!0),size:"sm",children:[e.jsx(Zr,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs($,{onClick:()=>g(!0),variant:"outline",size:"sm",children:[e.jsx(h4,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs($,{onClick:()=>m(!0),variant:"outline",size:"sm",children:[e.jsx(Nd,{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(FI,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs($,{onClick:W,variant:"ghost",size:"sm",children:[e.jsx(wv,{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(qn,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Xue,{icon:h4,label:"Updates Posted",value:i.length}),e.jsx(Xue,{icon:dl,label:"Referrals",value:A.length}),e.jsx(Xue,{icon:Ea,label:"Inspection",value:w.inspection_date?Y$(w.inspection_date):"—"}),e.jsx(Xue,{icon:Ea,label:"Appraisal",value:w.appraisal_date?Y$(w.appraisal_date):"—"})]}),e.jsxs(pa,{defaultValue:"updates",className:"w-full",children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"updates",children:["Updates (",i.length,")"]}),e.jsx(Xt,{value:"messages",children:"Messages"}),e.jsxs(Xt,{value:"referrals",children:["Referrals (",A.length,")"]}),e.jsx(Xt,{value:"branding",children:"Branding"}),e.jsx(Xt,{value:"details",children:"Details"})]}),e.jsx(Qt,{value:"messages",className:"mt-4",children:e.jsx(Kis,{portalId:w.id,portalSlug:w.slug,clientName:w.client_name})}),e.jsx(Qt,{value:"updates",className:"mt-4",children:e.jsx(je,{children:e.jsxs(Le,{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(h4,{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(h4,{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(Z=>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:Z.title}),Z.is_stage_change&&e.jsx($e,{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:Y$(Z.created_at)}),Z.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:Z.content}),Z.video_url&&e.jsxs("a",{href:Z.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(fa,{className:"w-3 h-3"})," View video"]})]})})},Z.id))})]})})}),e.jsx(Qt,{value:"referrals",className:"mt-4",children:e.jsx(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),A.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(dl,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"When your client refers a friend, they'll show up here."})]}):e.jsx("div",{className:"space-y-2",children:A.map(Z=>e.jsx(br,{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:Z.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Z.friend_email||Z.friend_phone||"No contact info"," · ",Y$(Z.created_at)]})]}),e.jsx($e,{variant:"outline",className:"text-xs capitalize",children:Z.status})]})},Z.id))})]})})}),e.jsx(Qt,{value:"branding",className:"mt-4",children:e.jsx(je,{children:e.jsx(Le,{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(yd,{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(Nd,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(Qt,{value:"details",className:"mt-4",children:e.jsx(je,{children:e.jsxs(Le,{className:"p-6 space-y-4",children:[e.jsx(TM,{label:"Visibility",value:w.visibility}),e.jsx(TM,{label:"Onboarding Required",value:w.require_onboarding?"Yes":"No"}),e.jsx(TM,{label:"Allow Spouse",value:w.allow_spouse?"Yes":"No"}),e.jsx(TM,{label:"Notify Client on Updates",value:w.notify_client?"Yes":"No"}),e.jsx(TM,{label:"Show Post-Close Tips",value:w.show_post_close_tips?"Yes":"No"}),e.jsx(TM,{label:"Slug",value:w.slug,mono:!0}),e.jsx(TM,{label:"Created",value:Y$(w.created_at)}),e.jsx(TM,{label:"Last Updated",value:Y$(w.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs($,{variant:"outline",onClick:()=>m(!0),children:[e.jsx(Nd,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(Nlt,{open:h,onOpenChange:m,portal:w,dealOwnerId:n||""}),e.jsx(klt,{open:f,onOpenChange:g,portalId:w.id,portalSlug:w.slug,notifyClient:w.notify_client}),e.jsx(Slt,{open:x,onOpenChange:v,portal:w,dealName:I}),e.jsx(fc,{open:y,onOpenChange:b,children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Permanently delete this portal?"}),e.jsx(ic,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:G,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function Xue({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 TM({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 XXe=[{value:"video_intro",label:"Video Intro",icon:fa,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:ME,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:Cp,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:nu,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:Hd,description:"Links to your social profiles"}],Var=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],Har={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function Yis({cardId:s}){const{data:t,isLoading:n}=NDs(s),r=kDs(),a=SDs(),i=CDs(),[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(xn,{className:"h-16 w-full"}),e.jsx(xn,{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:Har[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),A=w==="up"?S-1:S+1;if(A<0||A>=t.length)return;const E=t[A];a.mutate({id:b.id,sort_order:E.sort_order}),a.mutate({id:E.id,sort_order:b.sort_order})},x=async b=>{await mo("Remove this block from this card?")&&i.mutate(b.id)},v=(b,w)=>{a.mutate({id:b.id,config:w},{onSuccess:()=>h(null)})},y=b=>XXe.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(cn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((b,w)=>{const S=y(b.block_type),A=(S==null?void 0:S.icon)||Cp;return e.jsx(je,{className:b.is_visible?"":"opacity-50",children:e.jsx(Le,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zg,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(A,{className:"h-4 w-4 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-xs",children:(S==null?void 0:S.label)||b.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Gar(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(Lg,{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(Ta,{className:"h-3 w-3"}):e.jsx(Nx,{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(qn,{className:"h-3 w-3"})})]})]})})},b.id)}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(cn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:XXe.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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:m,disabled:!c||r.isPending,children:"Add Block"})]})]})}),u&&e.jsx(War,{block:u,onSave:b=>v(u,b),onClose:()=>h(null)})]})}function Gar(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 War({block:s,onSave:t,onClose:n}){const[r,a]=j.useState(s.config),i=XXe.find(l=>l.value===s.block_type);return e.jsx(Os,{open:!0,onOpenChange:n,children:e.jsxs(Fs,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs($s,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(Kar,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(Yar,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(Zar,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx(Xar,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(Qar,{config:r,onChange:a}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx($,{onClick:()=>t(r),children:"Save"})]})]})})}function Kar({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}=st({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}=st({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:x,error:v}=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(v)throw v;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 v=(w=x.playback_url)==null?void 0:w.match(/\/(?:play|embed)\/(\d+)\//),b=`https://iframe.mediadelivery.net/embed/${v?v[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(pa,{value:i,onValueChange:l,children:[e.jsxs(ga,{className:"w-full",children:[e.jsx(Xt,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(Xt,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(Qt,{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(go,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(xn,{className:"h-14 w-full"}),e.jsx(xn,{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:v=>{var y;v.currentTarget.style.display="none",(y=v.currentTarget.nextElementSibling)==null||y.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(fa,{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(ma,{className:"h-4 w-4 text-primary flex-shrink-0"})]},x.id))})})]}),e.jsx(Qt,{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 Yar({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(je,{children:e.jsxs(Le,{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(qn,{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(cn,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function Zar({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:Var.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 Xar({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(qn,{className:"h-3 w-3"})})]},o)),e.jsxs($,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(cn,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const ZAt=[{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 Qar({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=ZAt.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=JHe[c],u=ZAt.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(qn,{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=JHe[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 Jar({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(),ne.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(dk,{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(ji,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function aUe(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 eir(){const{user:s}=_s(),{data:t,isLoading:n}=_Ds(s==null?void 0:s.id),r=RK(),[a,i]=j.useState(null),l=j.useMemo(()=>a||(t?aUe(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(xn,{className:"h-8 w-48"}),e.jsx(xn,{className:"h-32 w-full"}),e.jsx(xn,{className:"h-32 w-full"})]})});if(!t)return e.jsx(Vs,{children:e.jsx(sir,{userId:s==null?void 0:s.id})});const o=l||aUe(t),c=d=>{i(u=>{const h=u||aUe(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(nir,{card:t}),e.jsx(oir,{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(ZN,{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(tir,{card:t,form:o})})]})})]})})}function tir({card:s,form:t}){const{data:n}=st({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(Ktt,{card:r})})}function sir({userId:s}){var c;const[t,n]=j.useState(""),r=R7t(),{data:a}=st({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){ne.error("Please enter a URL slug for your card");return}r.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>ne.success("Your digital card has been created!")})},o=[{icon:cl,title:"Shareable Link",desc:"One link that works everywhere"},{icon:Qp,title:"Lead Capture",desc:"Collect leads automatically"},{icon:Tf,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:yd,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(wn,{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(je,{className:"shadow-lg border-2",children:[e.jsxs(St,{className:"text-center pb-2",children:[e.jsx(Et,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(Vn,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Le,{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(wn,{className:"h-4 w-4 mr-2"}),r.isPending?"Creating...":"Create My Card"]})]})]})]})}function nir({card:s}){const n=`https://cards.relevelup.com/${s.slug}`,r=()=>{navigator.clipboard.writeText(n),ne.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($e,{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(cl,{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(Za,{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(Ir,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function rir({userId:s}){const t=Zt(),n=j.useRef(null),[r,a]=j.useState(!1),[i,l]=j.useState(""),{data:o,isLoading:c}=st({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,v]=j.useState(!1),y=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,A=((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=mt({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"]}),ne.success("Profile updated!")},onError:()=>ne.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){ne.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/")){ne.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=>{v(!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),Z=G.publicUrl+"?t="+Date.now();await q.from("profiles").update({avatar_url:Z}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ne.success("Photo updated!")}catch{ne.error("Failed to upload photo")}finally{v(!1)}};return c?e.jsx(xn,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(je,{className:E?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(Le,{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(vl,{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(Ii,{src:S||void 0,alt:y}),e.jsx(za,{className:"text-lg font-semibold bg-primary/10 text-primary",children:A})]}),e.jsx("div",{className:"absolute inset-0 bg-black/40 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(jx,{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:y,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(Gnt,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:D,aspectRatio:1})]})}function air({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 v;const x=(v=f.target.files)==null?void 0:v[0];if(x){if(!x.type.startsWith("image/")){ne.error("Please select an image file");return}a(g);try{const y=x.name.split(".").pop()||"png",w=`${n}/${g==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${y}`,{error:S}=await q.storage.from("card-logos").upload(w,x,{upsert:!0});if(S)throw S;const{data:A}=q.storage.from("card-logos").getPublicUrl(w),E=A.publicUrl+"?t="+Date.now();t(g==="brokerage_logo_url"?I=>({...I,[g]:E,brokerage_display_name:""}):I=>({...I,[g]:E,team_name:""})),ne.success("Logo uploaded!")}catch{ne.error("Failed to upload logo")}finally{a(null),f.target.value=""}}},m=f=>{t(g=>({...g,[f]:""}))};return e.jsx(je,{children:e.jsxs(Le,{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(jx,{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(bx,{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(jx,{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(bx,{value:[s.team_logo_size||56],onValueChange:([f])=>t(g=>({...g,team_logo_size:f})),min:24,max:120,step:4})]})]})]})]})})}function iir({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(yd,{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 oir({card:s,form:t,setForm:n}){var x;const r=D7t(),a=Zt(),{data:i}=F7t(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 v=JSON.stringify(t);if(v!==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=v,h("saved"),setTimeout(()=>h("idle"),2e3)},onError:()=>h("idle")})},1500),()=>{f.current&&clearTimeout(f.current)}},[t]);const g=async()=>{const v=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!v){ne.error("Please enter a valid URL");return}if(v===s.slug){ne.info("No changes to save");return}d(!0);try{const{data:y}=await q.from("agent_cards").select("id").eq("slug",v).neq("id",s.id).maybeSingle();if(y){ne.error("This URL is already taken. Try another one.");return}const{error:b}=await q.from("agent_cards").update({slug:v}).eq("id",s.id);if(b)throw b;o(v),a.invalidateQueries({queryKey:["agent-card"]}),ne.success("Card address updated!")}catch{ne.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(pa,{defaultValue:"content",children:[e.jsxs(ga,{className:"w-full h-11 p-1",children:[e.jsxs(Xt,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(jv,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(Xt,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Ta,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(Xt,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Qp,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(Xt,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Xp,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(Xt,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Pm,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(Qt,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(rir,{userId:s.user_id}),e.jsx(air,{form:t,setForm:n,userId:s.user_id}),e.jsx(je,{children:e.jsxs(Le,{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(jn,{checked:t.is_published,onCheckedChange:v=>n(y=>({...y,is_published:v}))})]}),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:v=>o(v.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:v=>n(y=>({...y,display_email:v.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:v=>n(y=>({...y,theme:v})),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(iir,{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:v=>n(y=>({...y,title:v.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:v=>n(y=>({...y,positioning_statement:v.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:v=>n(y=>({...y,bio:v.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:v=>n(y=>({...y,review_snippet:v.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:v=>n(y=>({...y,review_source_url:v.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:v=>n(y=>({...y,booking_url:v.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:v=>n(y=>({...y,custom_cta_label:v.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(Qt,{value:"sections",className:"mt-4",children:e.jsx(je,{children:e.jsx(Le,{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:v,label:y,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:y}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsx(jn,{checked:t[v],onCheckedChange:w=>n(S=>({...S,[v]:w}))})]},v))})})}),e.jsx(Qt,{value:"blocks",className:"mt-4",children:e.jsx(Yis,{cardId:s.id})}),e.jsx(Qt,{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:Ta,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:Pm,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:lc,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(v=>e.jsx(je,{className:"overflow-hidden",children:e.jsxs(Le,{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 ${v.color}`,children:e.jsx(v.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:v.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:v.value})]})},v.label))}),i&&i.leads.length>0&&e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-base",children:"Recent Leads"})}),e.jsx(Le,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(v=>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:v.name}),v.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:v.phone})]}),v.intent&&e.jsx($e,{variant:"secondary",className:"text-xs",children:v.intent})]},v.id))})]}),(!i||i.leads.length===0)&&e.jsx(je,{children:e.jsxs(Le,{className:"p-8 text-center",children:[e.jsx(Pm,{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(Qt,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(je,{children:e.jsx(Le,{className:"p-6",children:e.jsx(Jar,{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 lir(){const s=Zt(),[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,v]=j.useState(null),[y,b]=j.useState(0),[w,S]=j.useState(""),[A,E]=j.useState(!1),{data:I,isLoading:P}=st({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:le,error:re}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(re)throw re;return le}}),R=mt({mutationFn:async le=>{const{data:re,error:te}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:le}});if(te)throw te;if(re!=null&&re.error)throw new Error(re.error);return re},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),ne.success("BoldTrail connected successfully!")},onError:le=>{ne.error(le.message||"Failed to connect BoldTrail")}}),D=mt({mutationFn:async()=>{const{data:le,error:re}=await q.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(re)throw re;return le},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ne.success("BoldTrail disconnected")},onError:()=>ne.error("Failed to disconnect")}),O=mt({mutationFn:async le=>{const{data:re,error:te}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:le}});if(te)throw te;if(re!=null&&re.error)throw new Error(re.error);return re},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ne.success("Sync direction saved")},onError:le=>{ne.error(le.message||"Failed to save sync direction")}}),U=mt({mutationFn:async()=>{const{data:le,error:re}=await q.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(re)throw re;if(le!=null&&le.error)throw new Error(le.error);return le},onSuccess:le=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),le.kvcore_user_id){const re=le.detected_name||le.detected_email||`ID ${le.kvcore_user_id}`;ne.success(`Detected your BoldTrail account: ${re}`)}else if(le.candidates&&le.candidates.length>0){const re=le.candidates.slice(0,5).map(te=>`${te.id} (${te.count} contacts)`).join(", ");ne.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${re}. Pick yours and enter it below.`,{duration:12e3}),E(!0)}else ne.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),E(!0)},onError:le=>ne.error(le.message||"Detection failed")}),W=mt({mutationFn:async le=>{const{data:re,error:te}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...le}});if(te)throw te;if(re!=null&&re.error)throw new Error(re.error);return re},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ne.success("Settings saved"),E(!1)},onError:le=>ne.error(le.message||"Failed to save settings")}),V=mt({mutationFn:async()=>{const{data:le,error:re}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(re)throw re;if(le!=null&&le.error)throw new Error(le.error);return le},onSuccess:le=>{g(null),c(le),a(!0)},onError:le=>{ne.error(le.message||"Failed to generate sync preview")}}),G=mt({mutationFn:async()=>{v("Initializing sync..."),b(5);const{data:le,error:re}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:ae}});if(re)throw re;if(le!=null&&le.error)throw new Error(le.error);const te=le;let J=te.sync_log_id,ce=te.next_phase,ve=te.next_offset,fe=te.push_total||0,ue=te.pull_total||0,be=0,Ee=0;for(;ce!=="finalize";){const Fe=fe+ue;ce==="fetch_bt"?v("Fetching BoldTrail contacts..."):ce==="analyze"?(v("Analyzing contacts..."),b(15)):ce==="push"?(v(`Pushing contacts to BoldTrail... (${be}/${fe})`),b(Fe>0?be/Fe*100:0)):ce==="pull"&&(v(`Pulling contacts from BoldTrail... (${Ee}/${ue})`),b(Fe>0?(fe+Ee)/Fe*100:0));const{data:Ne,error:Be}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:ce,offset:ve,sync_log_id:J,sync_direction:ae}});if(Be)throw Be;if(Ne!=null&&Ne.error)throw new Error(Ne.error);const Se=Ne;be+=Se.chunk_pushed||0,Ee+=Se.chunk_pulled||0,Se.push_total!==void 0&&(fe=Se.push_total||0),Se.pull_total!==void 0&&(ue=Se.pull_total||0),Se.progress&&v(Se.progress),ce==="pull"&&ue>0?b(Math.min(95,Ee/ue*100)):ce==="push"&&fe>0&&b(Math.min(95,be/fe*100)),ce=Se.next_phase,ve=Se.next_offset}v("Finalizing sync..."),b(95);const{data:ke,error:Ie}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:J,sync_direction:ae}});if(Ie)throw Ie;return b(100),ke},onSuccess:le=>{v(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"]}),ne.success(`Sync complete! Pushed ${le.contacts_pushed||0}, pulled ${le.contacts_pulled||0}, skipped ${le.contacts_skipped||0} duplicates.`)},onError:le=>{v(null),b(0),ne.error(le.message||"Sync failed")}}),Z=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(je,{children:[e.jsx(St,{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(Dy,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(Et,{className:"text-lg flex items-center gap-2",children:["BoldTrail",Z&&e.jsx($e,{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(ef,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(Vn,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Le,{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(Wl,{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(Wl,{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(Wl,{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"})]}),Z?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($e,{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(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Disconnect BoldTrail?"}),e.jsx(ic,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{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(u2,{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(jn,{checked:(I==null?void 0:I.sync_include_no_email)!==!1,onCheckedChange:le=>W.mutate({sync_include_no_email:le}),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(u2,{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(jn,{checked:!!(I!=null&&I.sync_only_owned),onCheckedChange:le=>W.mutate({sync_only_owned:le}),disabled:W.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Your BoldTrail Agent ID"}),A?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"number",placeholder:"e.g. 12345",value:w,onChange:le=>S(le.target.value),className:"h-8 text-sm"}),e.jsx($,{size:"sm",onClick:()=>{const le=w.trim()===""?null:Number(w);W.mutate({kvcore_user_id:le})},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(co,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{var le;S(((le=I==null?void 0:I.kvcore_user_id)==null?void 0:le.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(KMe,{value:X,onChange:le=>O.mutate(le)})}),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(co,{className:"h-4 w-4 animate-spin"}):e.jsx(Ta,{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:le=>n(le.target.value),className:"flex-1"}),e.jsxs($,{onClick:()=>R.mutate(t),disabled:!t||t.length<10||R.isPending,children:[R.isPending?e.jsx(co,{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(Os,{open:r,onOpenChange:le=>{G.isPending||a(le)},children:e.jsxs(Fs,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Dy,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Er,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const le=ae==="pull_only"?0:o.to_push,re=ae==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(KMe,{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(u2,{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:le}),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:re}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Lg,{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(Yn,{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:y||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:x||"Sync in progress..."})]}),le>0&&e.jsxs(y1,{open:d,onOpenChange:u,children:[e.jsx(v1,{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"}),le," contacts to push to BoldTrail"]}),e.jsx(wl,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(b1,{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"]})]})})]}),re>0&&e.jsxs(y1,{open:h,onOpenChange:m,children:[e.jsx(v1,{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(Lg,{className:"h-3 w-3 text-blue-600"}),re," contacts to pull from BoldTrail"]}),e.jsx(wl,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(b1,{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"]})]})})]}),le===0&&re===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||le===0&&re===0,className:"gap-2",children:[G.isPending?e.jsx(co,{className:"h-4 w-4 animate-spin"}):e.jsx(Dy,{className:"h-4 w-4"}),G.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Fs,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(Us,{className:"p-6 pb-0",children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Dy,{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 Z$=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 cir(){const s=Zt(),[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}=st({queryKey:["lofty-status"],queryFn:async()=>await Z$({action:"status"})}),x=()=>s.invalidateQueries({queryKey:["lofty-status"]}),v=mt({mutationFn:async()=>Z$({action:"save_token",api_token:t.trim()}),onSuccess:E=>{ne.success(E!=null&&E.contact_count?`Connected to Lofty — ${E.contact_count} contacts found`:"Connected to Lofty"),n(""),x()},onError:E=>ne.error(E.message)}),y=mt({mutationFn:async()=>Z$({action:"disconnect"}),onSuccess:()=>{ne.success("Lofty disconnected"),x()},onError:E=>ne.error(E.message)}),b=mt({mutationFn:async E=>Z$({action:"save_settings",...E}),onSuccess:()=>x(),onError:E=>ne.error(E.message)}),w=mt({mutationFn:async()=>Z$({action:"detect_owner"}),onSuccess:E=>{const I=(E==null?void 0:E.candidates)||[];m(I),I.length===0?ne.info("No assigned-agent IDs found on your Lofty contacts."):I.length===1?(b.mutate({lofty_user_id:I[0].id}),ne.success(`Using Lofty agent ID ${I[0].id}`)):ne.success("Pick which Lofty agent ID is yours below.")},onError:E=>ne.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 Z$({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"),ne.success(D.message||"Lofty sync complete"))}}catch(E){ne.error(E.message||"Lofty sync failed"),u(null)}finally{l(!1),setTimeout(()=>c(0),2500),x()}},A=!!(f!=null&&f.connected);return e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Et,{className:"flex items-center gap-2",children:["Lofty",A?e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Wl,{className:"h-3 w-3"})," Connected"]}):e.jsx($e,{variant:"outline",children:"Not connected"})]}),e.jsx(Vn,{children:"Sync your Lofty (formerly Chime) contacts — names, emails, phones, address, source, stage, tags and notes — into Agent OS."})]}),A&&e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon","aria-label":"Disconnect Lofty",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Disconnect Lofty?"}),e.jsx(ic,{children:"Your API key and sync settings will be removed. Contacts already imported into Agent OS stay put."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:()=>y.mutate(),children:"Disconnect"})]})]})]})]})}),e.jsx(Le,{className:"space-y-5",children:g?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading…"]}):A?e.jsxs("div",{className:"space-y-5",children:[e.jsx(KMe,{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(jn,{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(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Yn,{className:"h-3.5 w-3.5"}),"Detect my Lofty agent ID"]}),(f==null?void 0:f.lofty_user_id)&&e.jsxs($e,{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(jn,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(co,{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($e,{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:()=>v.mutate(),disabled:t.trim().length<10||v.isPending,children:[v.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(QN,{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(Ir,{className:"ml-1 h-3 w-3"})]})})]})]})})]})}function dir(){const s=Zt(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(null),{data:d,isLoading:u}=st({queryKey:["fub-status"],queryFn:async()=>{const{data:x,error:v}=await q.functions.invoke("followupboss-sync",{body:{action:"status"}});if(v)throw v;return x}}),h=mt({mutationFn:async x=>{const{data:v,error:y}=await q.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:x}});if(y)throw y;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{ne.success("Connected to Follow Up Boss"),n(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:x=>ne.error(x.message)}),m=mt({mutationFn:async()=>{const{error:x}=await q.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(x)throw x},onSuccess:()=>{ne.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),f=mt({mutationFn:async x=>{const{error:v}=await q.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:x}});if(v)throw v},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from FUB…");let x=0,v=0,y=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);v+=E.chunk_created||0,y+=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 A=w||S?` · pushed ${w}${S?`, ${S} failed`:""}`:"";ne.success(`Sync complete · ${v} new, ${y} updated${b?`, ${b} skipped`:""}${A}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(w){ne.error(w.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(je,{children:[e.jsx(St,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(QN,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs($e,{variant:"default",className:"ml-1",children:[e.jsx(Wl,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Vn,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Le,{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(jn,{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(co,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:r,children:[e.jsx(qn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Disconnect Follow Up Boss?"}),e.jsx(ic,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{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(Ir,{className:"h-3 w-3"})]})]})]}),e.jsx($,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function uir(){var V;const s=Zt(),[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,v]=j.useState(!1),[y,b]=j.useState(new Set),{data:w,isLoading:S}=st({queryKey:["cloze-status"],queryFn:async()=>{const{data:G,error:Z}=await q.functions.invoke("cloze-sync",{body:{action:"status"}});if(Z)throw Z;return G}}),A=mt({mutationFn:async()=>{const{data:G,error:Z}=await q.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(Z)throw Z;if(G!=null&&G.error)throw new Error(G.error);return G},onSuccess:()=>{ne.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:G=>ne.error(G.message)}),E=mt({mutationFn:async()=>{const{error:G}=await q.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(G)throw G},onSuccess:()=>{ne.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),I=mt({mutationFn:async G=>{const{error:Z}=await q.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:G}});if(Z)throw Z},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),P=mt({mutationFn:async G=>{const{error:Z}=await q.functions.invoke("cloze-sync",{body:{action:"set_scope",...G}});if(Z)throw Z},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),R=async()=>{v(!0);try{const{data:G,error:Z}=await q.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(Z)throw Z;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){ne.error(G.message||"Failed to load segments")}finally{v(!1)}},D=async()=>{const G=Array.from(y);await P.mutateAsync({sync_scope:"segments",selected_segments:G}),ne.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 Z=0,X=0,ae=0;for(;;){const{data:le,error:re}=await q.functions.invoke("cloze-sync",{body:{action:"sync",offset:Z}});if(re)throw re;if(le!=null&&le.error)throw new Error(le.error);if(X+=le.chunk_created||0,ae+=le.chunk_updated||0,Z=le.next_offset,u(`Pulling · ${X+ae} contacts processed`),c(le.done?100:Math.min(95,(X+ae)%200/2)),le.done)break;await new Promise(te=>setTimeout(te,300))}ne.success(`Pulled · ${X} new, ${ae} updated`)}if(G==="push_only"||G==="bidirectional"){c(0),u("Pushing to Cloze…");let Z=0,X=0,ae=0;for(;;){const{data:le,error:re}=await q.functions.invoke("cloze-sync",{body:{action:"push",offset:Z}});if(re)throw re;if(le!=null&&le.error)throw new Error(le.error);X+=le.chunk_pushed||0,ae+=le.chunk_failed||0,Z=le.next_offset;const te=le.total?Math.min(100,Math.round(Z/le.total*100)):100;if(c(te),u(`Pushing · ${Z} / ${le.total||"?"}`),le.done)break;await new Promise(J=>setTimeout(J,300))}ne.success(`Pushed · ${X}${ae?`, ${ae} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(Z){ne.error(Z.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(je,{children:[e.jsx(St,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(QN,{className:"h-5 w-5 text-primary"}),"Cloze",(w==null?void 0:w.connected)&&e.jsxs($e,{variant:"default",className:"ml-1",children:[e.jsx(Wl,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Vn,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(Le,{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(QJ,{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 Z=y.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:Z,onCheckedChange:X=>{const ae=new Set(y);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($e,{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 (",y.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(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsxs($,{disabled:i,children:[e.jsx(co,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Preview sync"}),e.jsx(ic,{asChild:!0,children:e.jsx(hir,{segments:f})})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:O,children:"Start Sync"})]})]})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:i,children:[e.jsx(qn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Disconnect Cloze?"}),e.jsx(ic,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{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(Ir,{className:"h-3 w-3"})]})]})]}),e.jsx($,{onClick:()=>A.mutate(),disabled:!t.trim()||!r.trim()||A.isPending,children:A.isPending?"Connecting…":"Connect Cloze"})]})})]})}function hir({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 mir(){const s=Zt(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(null),{data:d,isLoading:u}=st({queryKey:["boomtown-status"],queryFn:async()=>{const{data:x,error:v}=await q.functions.invoke("boomtown-sync",{body:{action:"status"}});if(v)throw v;return x}}),h=mt({mutationFn:async x=>{const{data:v,error:y}=await q.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:x}});if(y)throw y;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{ne.success("Connected to Boomtown"),n(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:x=>ne.error(x.message)}),m=mt({mutationFn:async()=>{const{error:x}=await q.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(x)throw x},onSuccess:()=>{ne.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),f=mt({mutationFn:async x=>{const{error:v}=await q.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:x}});if(v)throw v},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let x=0,v=0,y=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);v+=E.chunk_created||0,y+=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 A=w||S?` · pushed ${w}${S?`, ${S} failed`:""}`:"";ne.success(`Sync complete · ${v} new, ${y} updated${b?`, ${b} skipped`:""}${A}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(w){ne.error(w.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(je,{children:[e.jsx(St,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(QN,{className:"h-5 w-5 text-primary"}),"Boomtown",(d==null?void 0:d.connected)&&e.jsxs($e,{variant:"default",className:"ml-1",children:[e.jsx(Wl,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Vn,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(Le,{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(jn,{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(co,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:r,children:[e.jsx(qn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Disconnect Boomtown?"}),e.jsx(ic,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{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(Ir,{className:"h-3 w-3"})]})]}),e.jsx($,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function Zis(){const s=Zn(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState("Test from ReLevelUp"),[o,c]=j.useState(!1),{data:d,isLoading:u}=st({queryKey:["ses-config"],queryFn:async()=>{const f=await cne();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){ne.error("Please fill in From and To email addresses");return}c(!0);try{const f=await cne(),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?ne.success(`Test email sent! Message ID: ${x.messageId}`):ne.error(x.error||"Failed to send test email")}catch(f){ne.error(f.message||"Failed to send test email")}finally{c(!1)}},m=(d==null?void 0:d.configured)===!0;return e.jsxs(je,{children:[e.jsx(St,{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(pn,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(Vn,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx($e,{variant:m?"default":"secondary",children:u?"Checking...":m?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wl,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vl,{className:"h-3 w-3"})," Not Configured"]})})]})}),m&&e.jsxs(Le,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs($,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(gm,{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(Le,{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 iUe(s){const t=await cne(),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 fir({status:s}){return s==="verified"?e.jsxs($e,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Vr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs($e,{variant:"secondary",children:[e.jsx(ca,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs($e,{variant:"destructive",children:[e.jsx(vl,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs($e,{variant:"outline",children:[e.jsx(vl,{className:"h-3 w-3 mr-1"})," Not started"]})}function Xis({brokerageId:s,onVerifiedSelect:t}){const n=Zt(),[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}=st({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=mt({mutationFn:async()=>iUe({action:"request_verification",brokerage_id:s,email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ne.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:b=>ne.error(b.message)}),v=async b=>{var w,S;u(b.id);try{const A=await iUe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((w=A.sender)==null?void 0:w.status)==="verified"?ne.success(`${b.email} is verified! 🎉`):ne.info(`Status: ${((S=A.sender)==null?void 0:S.status)||"unknown"}`)}catch(A){ne.error(A.message)}finally{u(null)}},y=mt({mutationFn:async b=>iUe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ne.success("Sender removed"),m(null)},onError:b=>ne.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(pn,{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(fir,{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:()=>v(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(co,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(qn,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(pn,{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(cn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(fc,{open:!!h,onOpenChange:b=>!b&&m(null),children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Remove this sender?"}),e.jsxs(ic,{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(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:()=>h&&y.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function oUe(s){const t=await cne(),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 pir({status:s}){return s==="verified"?e.jsxs($e,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Vr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs($e,{variant:"secondary",children:[e.jsx(ca,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs($e,{variant:"destructive",children:[e.jsx(vl,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs($e,{variant:"outline",children:[e.jsx(vl,{className:"h-3 w-3 mr-1"})," Not started"]})}function gir({userId:s,onVerifiedSelect:t}){const n=Zt(),[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}=st({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=mt({mutationFn:async()=>oUe({action:"request_verification",scope:"user",email:r,display_name:i||void 0}),onSuccess:b=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ne.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),b!=null&&b.domain_warning&&ne.warning("Heads up about this address",{description:b.domain_warning,duration:15e3}),a(""),l(""),c(!1)},onError:b=>ne.error(b.message)}),v=async b=>{var w,S;u(b.id);try{const A=await oUe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((w=A.sender)==null?void 0:w.status)==="verified"?ne.success(`${b.email} is verified! 🎉`):ne.info(`Status: ${((S=A.sender)==null?void 0:S.status)||"unknown"}`)}catch(A){ne.error(A.message)}finally{u(null)}},y=mt({mutationFn:async b=>oUe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ne.success("Sender removed"),m(null)},onError:b=>ne.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(pn,{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(pir,{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:()=>v(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(co,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(qn,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(pn,{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(cn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(fc,{open:!!h,onOpenChange:b=>!b&&m(null),children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Remove this sender?"}),e.jsxs(ic,{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(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:()=>h&&y.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function xir(){var S,A,E,I,P;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=_s(),i=a||((S=r==null?void 0:r[0])==null?void 0:S.id)||null,l=(t||n)&&!!i,o=Zt(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState(""),{data:g}=st({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}=st({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}}),v=((A=g==null?void 0:g.reply_to_email)==null?void 0:A.trim())||((E=x==null?void 0:x.email)==null?void 0:E.trim())||"",y=((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(v),f(y))},[c,v,y]);const b=mt({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]}),ne.success("Reply-to email saved!"),d(!1)},onError:R=>ne.error(R.message)}),w=!!v;return e.jsxs(je,{children:[e.jsx(St,{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(Zr,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(Et,{className:"text-lg flex items-center gap-2",children:["Mass Email",w?e.jsxs($e,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(Wl,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx($e,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(Vn,{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(Le,{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:y||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(pi,{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(v),f(y)},children:[e.jsx(mr,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(Vc,{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(Rm,{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(gir,{userId:s.id,onVerifiedSelect:R=>{h(R),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(Vc,{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(Rm,{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(Xis,{brokerageId:i})]})]})]})]})}function yir({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 vir=[{id:"all",label:"All tools",icon:Xf},{id:"crm",label:"Real estate CRMs",icon:x0},{id:"social",label:"Social media",icon:Hd},{id:"communication",label:"Communication",icon:pn},{id:"marketing",label:"AI & marketing",icon:wn}],bir={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",ses:"Amazon SES"};function _ir({connected:s,label:t}){return s?e.jsxs($e,{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($e,{variant:"outline",className:"text-muted-foreground",children:t||"Available"})}function vj({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($e,{variant:"secondary",className:"text-[10px] uppercase",children:o}),e.jsx(_ir,{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 wir(){const s=Zn(),{isAdmin:t,user:n}=_s(),{actingAsAgent:r,effectiveUserId:a}=Sae(),i=Zt(),[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"),[v,y]=j.useState(null),{scopeUserId:b,isDelegated:w}=yir({authUserId:n==null?void 0:n.id,actingAsUserId:(r==null?void 0:r.id)??a}),{data:S,isLoading:A}=st({queryKey:["gmail-integration",b],enabled:!!b&&!w,queryFn:async()=>{const{data:Be,error:Se}=await q.from("gmail_integrations").select("*").eq("user_id",b).maybeSingle();if(Se)throw Se;return Be}}),{data:E}=st({queryKey:["social-accounts",b],enabled:!!b&&!w,queryFn:async()=>{const{data:Be,error:Se}=await q.from("social_accounts").select("*").eq("user_id",b).order("created_at",{ascending:!1});if(Se)throw Se;return Be}}),{data:I}=st({queryKey:["google-business-status",b],enabled:!!b&&!w,queryFn:async()=>{const{data:Be,error:Se}=await q.functions.invoke("google-business-oauth",{body:{action:"get_status"}});if(Se)throw Se;return Be}}),P=mt({mutationFn:async Be=>{const{error:Se}=await q.functions.invoke("google-business-oauth",{body:{action:"set_primary_location",locationId:Be}});if(Se)throw Se},onSuccess:()=>{ne.success("Business updated"),i.invalidateQueries({queryKey:["google-business-status",b]}),i.invalidateQueries({queryKey:["social-accounts",b]})},onError:()=>ne.error("Could not update your business selection")}),R=mt({mutationFn:async()=>{const{error:Be}=await q.functions.invoke("google-business-oauth",{body:{action:"disconnect"}});if(Be)throw Be},onSuccess:()=>{i.invalidateQueries({queryKey:["google-business-status",b]}),i.invalidateQueries({queryKey:["social-accounts",b]}),ne.success("Google Business disconnected")},onError:()=>ne.error("Could not disconnect Google Business")}),D=mt({mutationFn:async()=>{const{data:Be,error:Se}=await q.functions.invoke("google-business-oauth",{body:{action:"rescan_locations"}});if(Se)throw Se;return Be},onSuccess:Be=>{i.invalidateQueries({queryKey:["google-business-status",b]}),Be!=null&&Be.success&&Be.locationsCount?ne.success(Be.message??"Locations updated"):ne.error((Be==null?void 0:Be.message)??"No business locations were found on this Google account.")},onError:()=>ne.error("Could not check Google for your business")}),O=async()=>{if(w){ne.error("Account connections must be made by the agent from their own login.");return}f(!0);try{const{data:Be,error:Se}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/mission-control/integrations"}});if(Se)throw Se;if(Be!=null&&Be.authUrl)window.location.href=Be.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(Be){console.error("Google Business OAuth error:",Be),ne.error("Failed to start Google connection. Please try again."),f(!1)}},U=async()=>{if(w){ne.error("Account connections must be made by the agent from their own login.");return}o(!0);try{const{data:Be,error:Se}=await q.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(Se)throw Se;if(Be!=null&&Be.authUrl)window.location.href=Be.authUrl;else throw new Error("Failed to get authorization URL")}catch(Be){console.error("Gmail OAuth error:",Be),ne.error("Failed to start Gmail connection"),o(!1)}},W=async Be=>{if(w){ne.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:Se,error:Ae}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:Be}});if(Ae)throw Ae;if(Se!=null&&Se.authUrl)window.location.href=Se.authUrl;else throw new Error("Failed to get authorization URL")}catch(Se){console.error("Meta OAuth error:",Se),ne.error("Failed to start connection. Make sure Meta App credentials are configured."),d(!1)}},V=async()=>{if(w){ne.error("Account connections must be made by the agent from their own login.");return}h(!0);try{const{data:Be,error:Se}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(Se)throw Se;if(Be!=null&&Be.authUrl)window.location.href=Be.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(Be){console.error("LinkedIn OAuth error:",Be),ne.error("Failed to start LinkedIn connection. Please try again."),h(!1)}},G=mt({mutationFn:async Be=>{const{error:Se}=await q.from("gmail_integrations").delete().eq("id",Be).eq("user_id",b);if(Se)throw Se},onSuccess:()=>{i.invalidateQueries({queryKey:["gmail-integration",b]}),ne.success("Gmail disconnected")},onError:()=>{ne.error("Failed to disconnect Gmail")}}),Z=mt({mutationFn:async Be=>{const{error:Se}=await q.from("social_accounts").delete().eq("id",Be).eq("user_id",b);if(Se)throw Se},onSuccess:()=>{i.invalidateQueries({queryKey:["social-accounts",b]}),ne.success("Account disconnected")},onError:()=>{ne.error("Failed to disconnect account")}}),X=!w&&!!(S!=null&&S.is_active),ae=(E==null?void 0:E.filter(Be=>Be.platform==="facebook"))||[],le=(E==null?void 0:E.filter(Be=>Be.platform==="instagram"))||[],re=(E==null?void 0:E.filter(Be=>Be.platform==="linkedin"))||[],te=(E==null?void 0:E.filter(Be=>Be.platform==="google_business"))||[],{data:J}=st({queryKey:["mass-email-settings",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:Be,error:Se}=await q.from("mass_email_settings").select("reply_to_email").eq("user_id",n==null?void 0:n.id).maybeSingle();if(Se)throw Se;return Be}}),ce=(Be,Se)=>({queryKey:[Be],queryFn:async()=>{const{data:Ae,error:Ce}=await q.functions.invoke(Se,{body:{action:"status"}});if(Ce)throw Ce;return Ae},staleTime:6e4}),{data:ve}=st(ce("boldtrail-status","boldtrail-sync")),{data:fe}=st(ce("lofty-status","lofty-sync")),{data:ue}=st(ce("fub-status","followupboss-sync")),{data:be}=st(ce("cloze-status","cloze-sync")),{data:Ee}=st(ce("boomtown-status","boomtown-sync")),ke=[X,!!(J!=null&&J.reply_to_email),ae.length>0,le.length>0,re.length>0,!!(ve!=null&&ve.connected),!!(fe!=null&&fe.connected),!!(ue!=null&&ue.connected),!!(be!=null&&be.connected),!!(Ee!=null&&Ee.connected)].filter(Boolean).length,Ie=Be=>{y(Se=>Se===Be?null:Be)},Fe=Be=>{const Se=Be==="facebook"?ae:Be==="instagram"?le:re,Ae=Be==="facebook"?Zp:Be==="instagram"?Ef:ly,Ce=Be==="facebook"?"Facebook":Be==="instagram"?"Instagram":"LinkedIn",qe=Be==="linkedin"?V:()=>W(Be),ze=Be==="linkedin"?u:c;return e.jsxs(je,{className:"border-primary/25 shadow-sm",children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"font-display text-xl",children:["Manage ",Ce]}),e.jsx(Vn,{children:Be==="instagram"?"Connect a Business or Creator account. Personal Instagram accounts are not supported.":`Manage the ${Ce} account used for publishing LevelUp content.`})]}),e.jsxs(Le,{className:"space-y-3",children:[Se.map(Ve=>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(Ii,{src:Ve.profile_picture_url||""}),e.jsx(za,{children:e.jsx(Ae,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:Ve.page_name||Ve.platform_username||`${Ce} account`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected"})]})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive","aria-label":`Disconnect ${Ce}`,children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsxs(ac,{children:["Disconnect ",Ce,"?"]}),e.jsx(ic,{children:"You will need to reconnect this account before publishing again."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:()=>Z.mutate(Ve.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},Ve.id)),e.jsxs($,{variant:"outline",onClick:qe,disabled:ze||w,children:[ze?e.jsx(co,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(cn,{className:"mr-2 h-4 w-4"}),Se.length?`Add another ${Ce} account`:`Connect ${Ce}`]})]})]})},Ne=(()=>{var Be,Se,Ae;switch(v){case"gmail":return e.jsxs(je,{className:"border-primary/25 shadow-sm",children:[e.jsxs(St,{children:[e.jsx(Et,{className:"font-display text-xl",children:"Manage Gmail"}),e.jsx(Vn,{children:"Send personalized emails from contact pages and automatically record the activity."})]}),e.jsxs(Le,{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(ze=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-muted/25 p-3 text-sm",children:[e.jsx(ma,{className:"mt-0.5 h-4 w-4 shrink-0 text-success"}),ze]},ze))}),X?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:S.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"text-destructive",children:[e.jsx(qn,{className:"mr-2 h-4 w-4"}),"Disconnect"]})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Disconnect Gmail?"}),e.jsx(ic,{children:"You will need to reconnect before sending emails from Gmail."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:()=>G.mutate(S.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs($,{onClick:U,disabled:l||A||w,children:[l?e.jsx(co,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(pn,{className:"mr-2 h-4 w-4"}),"Connect Gmail"]})]})]});case"mass-email":return e.jsx(xir,{});case"facebook":return Fe("facebook");case"instagram":return Fe("instagram");case"linkedin":return Fe("linkedin");case"google-business":const Ce=(I==null?void 0:I.connected)===!0,qe=((Be=I==null?void 0:I.locations)==null?void 0:Be.find(ze=>ze.is_primary))??((Se=I==null?void 0:I.locations)==null?void 0:Se[0]);return e.jsxs(je,{className:"border-primary/25 shadow-sm",children:[e.jsxs(St,{children:[e.jsx(Et,{className:"font-display text-xl",children:"Google Business Profile"}),e.jsx(Vn,{children:"Post updates and manage reviews from your Google Business Profile."})]}),e.jsxs(Le,{className:"space-y-3",children:[(I==null?void 0:I.needsReconnect)&&Ce&&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."}),Ce&&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:(qe==null?void 0:qe.location_name)||(I==null?void 0:I.email)||"Google Business"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected"})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive","aria-label":"Disconnect Google Business",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Disconnect Google Business?"}),e.jsx(ic,{children:"You will need to reconnect before posting or syncing reviews again."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:()=>R.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}),(((Ae=I==null?void 0:I.locations)==null?void 0:Ae.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?"}),I.locations.map(ze=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"truncate text-sm",children:ze.location_name||ze.location_id}),ze.is_primary?e.jsx($e,{className:"shrink-0 text-xs",children:"Active"}):e.jsx($,{size:"sm",variant:"outline",className:"shrink-0",disabled:P.isPending,onClick:()=>P.mutate(ze.location_id),children:"Use this"})]},ze.id))]}),Ce&&(I==null?void 0:I.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."]}),Ce&&!(I!=null&&I.missingBusinessScope)&&(I==null?void 0:I.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 ",(I==null?void 0:I.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:D.isPending,onClick:()=>D.mutate(),children:[D.isPending?e.jsx(co,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(co,{className:"mr-2 h-4 w-4"}),"Check again"]})]}),e.jsxs($,{variant:Ce&&!(I!=null&&I.needsReconnect)?"outline":"default",onClick:O,disabled:m||w,children:[m?e.jsx(co,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(cn,{className:"mr-2 h-4 w-4"}),Ce?"Reconnect Google Business":"Connect Google Business"]})]})]});case"boldtrail":return e.jsx(lir,{});case"lofty":return e.jsx(cir,{});case"followupboss":return e.jsx(dir,{});case"cloze":return e.jsx(uir,{});case"boomtown":return e.jsx(mir,{});case"chatgpt":return e.jsxs(je,{className:"border-primary/25 shadow-sm",children:[e.jsxs(St,{children:[e.jsx(Et,{className:"font-display text-xl",children:"ChatGPT"}),e.jsx(Vn,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]}),e.jsx(Le,{children:e.jsxs($,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(Qa,{className:"ml-2 h-4 w-4"})]})})]});case"ses":return t?e.jsx(Zis,{}):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($e,{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"}),ke," services active"]})]}),w&&e.jsx(je,{className:"mt-5 border-warning/40 bg-warning/5",children:e.jsxs(St,{className:"flex flex-row items-start gap-3 space-y-0",children:[e.jsx(jc,{className:"mt-0.5 h-5 w-5 text-warning"}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-base",children:"Connected accounts are hidden"}),e.jsxs(Vn,{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:vir.map(Be=>{const Se=Be.icon,Ae=g===Be.id;return e.jsxs($,{variant:Ae?"secondary":"ghost",className:`shrink-0 justify-start gap-2 ${Ae?"text-primary":"text-muted-foreground"}`,onClick:()=>{x(Be.id),y(null)},children:[e.jsx(Se,{className:"h-4 w-4"}),Be.label]},Be.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($e,{variant:"secondary",className:"hidden sm:flex",children:[e.jsx(gm,{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(vj,{title:"Gmail",description:"Send personal emails and automatically log each touchpoint.",icon:e.jsx(pn,{className:"h-5 w-5"}),connected:X,selected:v==="gmail",onClick:()=>Ie("gmail"),badge:"Priority"}),e.jsx(vj,{title:"Mass Email",description:"Send polished campaigns from a verified sender address.",icon:e.jsx(Zr,{className:"h-5 w-5"}),connected:!!(J!=null&&J.reply_to_email),statusLabel:"Setup required",selected:v==="mass-email",onClick:()=>Ie("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(vj,{title:"BoldTrail",description:"Sync contacts, ownership, tags, notes, and lead details.",icon:e.jsx(x0,{className:"h-5 w-5"}),connected:ve==null?void 0:ve.connected,selected:v==="boldtrail",onClick:()=>Ie("boldtrail")}),e.jsx(vj,{title:"Lofty",description:"Connect Lofty contacts and control sync direction.",icon:e.jsx(x0,{className:"h-5 w-5"}),connected:fe==null?void 0:fe.connected,selected:v==="lofty",onClick:()=>Ie("lofty")}),e.jsx(vj,{title:"Follow Up Boss",description:"Keep Follow Up Boss contacts aligned with LevelUp.",icon:e.jsx(x0,{className:"h-5 w-5"}),connected:ue==null?void 0:ue.connected,selected:v==="followupboss",onClick:()=>Ie("followupboss")}),e.jsx(vj,{title:"Cloze",description:"Sync contacts from your Cloze account or selected segments.",icon:e.jsx(x0,{className:"h-5 w-5"}),connected:be==null?void 0:be.connected,selected:v==="cloze",onClick:()=>Ie("cloze")}),e.jsx(vj,{title:"BoomTown",description:"Import and synchronize your BoomTown contact database.",icon:e.jsx(x0,{className:"h-5 w-5"}),connected:Ee==null?void 0:Ee.connected,selected:v==="boomtown",onClick:()=>Ie("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(vj,{title:"Facebook",description:"Publish to your connected Facebook Pages.",icon:e.jsx(Zp,{className:"h-5 w-5"}),connected:ae.length>0,selected:v==="facebook",onClick:()=>Ie("facebook")}),e.jsx(vj,{title:"Instagram",description:"Schedule content to a Business or Creator account.",icon:e.jsx(Ef,{className:"h-5 w-5"}),connected:le.length>0,selected:v==="instagram",onClick:()=>Ie("instagram")}),e.jsx(vj,{title:"LinkedIn",description:"Share content with your professional network.",icon:e.jsx(ly,{className:"h-5 w-5"}),connected:re.length>0,selected:v==="linkedin",onClick:()=>Ie("linkedin")}),e.jsx(vj,{title:"Google Business",description:"Post updates and manage reviews on your Google Business Profile.",icon:e.jsx(wi,{className:"h-5 w-5"}),connected:te.length>0&&!(I!=null&&I.needsReconnect),statusLabel:I!=null&&I.needsReconnect?"Reconnect":void 0,selected:v==="google-business",onClick:()=>Ie("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(vj,{title:"ChatGPT",description:"Use your LevelUp tools directly from ChatGPT.",icon:e.jsx(A4,{className:"h-5 w-5"}),statusLabel:"View setup",selected:v==="chatgpt",onClick:()=>Ie("chatgpt")}),t&&e.jsx(vj,{title:"Amazon SES",description:"Manage the platform-level mass email delivery service.",icon:e.jsx(JS,{className:"h-5 w-5"}),statusLabel:"Admin only",badge:"Admin",selected:v==="ses",onClick:()=>Ie("ses")})]})]})]})]}),e.jsx(Vy,{open:v!==null,onOpenChange:Be=>{Be||y(null)},children:e.jsxs(uy,{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(I0,{className:"sticky top-0 z-10 border-b bg-background px-5 py-5 pr-12 text-left sm:px-7",children:[e.jsxs(L0,{className:"font-display text-xl",children:[v?bir[v]:"Integration"," settings"]}),e.jsx(IB,{children:"Review the connection and update its settings here."})]}),e.jsx("div",{className:"p-4 sm:p-7",children:Ne})]})})]})})}const jir="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function Nir(){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 v=>{const y=new Uint8Array(await v.slice(0,4).arrayBuffer());return y[0]===80&&y[1]===75&&y[2]===3&&y[3]===4||y[0]===80&&y[1]===75&&y[2]===5&&y[3]===6||y[0]===80&&y[1]===75&&y[2]===7&&y[3]===8},m=v=>{const y=document.createElement("a");y.href=v,y.download="levelup-extension.zip",y.rel="noopener noreferrer",y.target="_blank",document.body.appendChild(y),y.click(),y.remove()},f=async()=>{o(!0);try{if(u){m(`${d}?v=${Date.now()}`);return}const v=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!v.ok)throw new Error(`Download failed (${v.status})`);const y=await v.blob();if(!await h(y)){m(`${d}?v=${Date.now()}`);return}const b=new Blob([y],{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(v){ne.error(v.message||"Download failed")}finally{o(!1)}},g=async()=>{r(!0);try{await q.auth.refreshSession();const{data:v}=await q.auth.getSession();if(!v.session){ne.error("Your session has expired. Please sign in again.");return}const{data:y,error:b}=await q.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${v.session.access_token}`}});if(b)throw b;t(y.code),i(y.expires_in||300);const w=setInterval(()=>{i(S=>S<=1?(clearInterval(w),t(null),0):S-1)},1e3)}catch(v){console.error("generateCode error",v),ne.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),ne.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(Dl,{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(Lz,{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(je,{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(jir,"_blank","noopener,noreferrer"),children:[e.jsx(Lz,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(Ir,{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(je,{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(Za,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs($,{onClick:g,variant:"outline",className:"flex-1",children:[e.jsx(co,{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(ma,{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(co,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(je,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ym,{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 kir(){const[s]=Nc(),t=Zn(),[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"),ne.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ne.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!"),ne.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"),ne.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(je,{className:"w-full max-w-md",children:[e.jsxs(St,{className:"text-center",children:[n==="loading"&&e.jsx(Ct,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Wl,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ju,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Et,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Le,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function Sir(){const s=Zn();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 Cir(){const[s]=Nc(),t=Zn(),[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"),ne.error("Connection failed: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),ne.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 v=g.context;if(v&&typeof v.json=="function"){const y=await v.json();y!=null&&y.error&&(x=y.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)!`),ne.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"),ne.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(je,{className:"w-full max-w-md",children:[e.jsxs(St,{className:"text-center",children:[n==="loading"&&e.jsx(Ct,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Wl,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ju,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Et,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:i})]}),e.jsx(Le,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const Qis=new Date().getFullYear(),Air=Array.from({length:5},(s,t)=>Qis-t);function Eir(){const[s,t]=j.useState(Qis),n=Zn(),{data:r,isLoading:a}=kWs();return a?e.jsx(Vs,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(xn,{className:"h-24"},i))}),e.jsx(xn,{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:Air.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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yn,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Gl,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Agents with Scorecards"}),e.jsx(Vn,{children:"Click to view individual agent scorecards"})]}),e.jsx(Le,{children:!r||r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Gl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:r.map(i=>e.jsxs(An,{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(Ta,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const Tir="00000000-0000-0000-0000-000000000000",Mir=s=>{if(!s)return"—";const[t,n,r]=s.split(/[-/T]/);return`${n}/${r}/${t}`};function Pir(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 Iir={never_started:"Never started",signed_in_empty:"Signed in, empty",started:"Started, gone quiet",active:"Active"};function Lir(){const s=Zt(),[t,n]=j.useState(null),[r,a]=j.useState(""),[i,l]=j.useState(null),{data:o=[]}=st({queryKey:["agent-activation-settings"],queryFn:async()=>{const{data:S,error:A}=await q.from("agent_activation_settings").select("*");if(A)throw A;return S}}),{data:c=[],isLoading:d}=st({queryKey:["brokerage-adoption-stats"],queryFn:async()=>{const{data:S,error:A}=await q.rpc("get_brokerage_adoption_stats");if(A)throw A;return S}}),{data:u}=st({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},[A,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:A,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(A=>A.brokerage_id===S),g=mt({mutationFn:async({brokerageId:S,enabled:A})=>{const{data:E}=await q.from("agent_activation_settings").select("id").eq("brokerage_id",S??Tir).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:A,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:A});if(P)throw P}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-activation-settings"]}),ne.success("Setting saved")},onError:()=>ne.error("Could not save setting")}),x=mt({mutationFn:async S=>{const{data:A,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 A},onSuccess:l,onError:()=>ne.error("Preview failed")}),v=mt({mutationFn:async S=>{const{data:A,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(A!=null&&A.error)throw new Error(A.error);return A},onSuccess:S=>ne.success(`Test email sent to ${S.sent_to}`),onError:S=>ne.error(S.message||"Test send failed")}),y=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(kd,{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(Dm,{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(je,{children:e.jsxs(Le,{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(je,{className:m?"border-emerald-300":"border-amber-300",children:e.jsx(St,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Et,{className:"flex items-center gap-2 text-lg",children:[e.jsx(rf,{className:"h-5 w-5"}),"Master switch"]}),e.jsx(Vn,{children:m?"Activation emails are LIVE for brokerages you enable below.":"OFF worldwide. No activation emails can be sent to anyone."})]}),e.jsx(jn,{checked:m,onCheckedChange:S=>g.mutate({brokerageId:null,enabled:S})})]})})}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"text-lg flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5"})," The sequence"]}),e.jsx(Vn,{children:"Five emails, all sent from LevelUp. Preview any step or send a test to yourself."})]}),e.jsx(Le,{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(Ta,{className:"h-3.5 w-3.5 mr-1"})," Step ",S]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>v.mutate(S),disabled:v.isPending,title:"Send test to my email",children:e.jsx(Zr,{className:"h-3.5 w-3.5"})})]},S))})]}),t?e.jsx(Rir,{brokerage:t,settings:f(t.brokerage_id),masterOn:m,onBack:()=>n(null),onToggle:S=>g.mutate({brokerageId:t.brokerage_id,enabled:S})}):e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:"Brokerage adoption"}),e.jsx(Vn,{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(Le,{children:d?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:y.map(S=>{var I;const A=Pir(S),E=!!((I=f(S.brokerage_id))!=null&&I.enabled);return e.jsxs(An,{className:"cursor-pointer",onClick:()=>n(S),children:[e.jsx(wt,{className:"font-medium",children:S.brokerage_name}),e.jsx(wt,{children:e.jsx($e,{variant:"secondary",className:A.className,children:A.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($e,{variant:E?"default":"outline",children:E?"On":"Off"})})]},S.brokerage_id)})})]})})]}),e.jsx(Os,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:i==null?void 0:i.subject}),e.jsx(Er,{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 Rir({brokerage:s,settings:t,masterOn:n,onBack:r,onToggle:a}){const i=Zt(),[l,o]=j.useState(""),{data:c=[],isLoading:d}=st({queryKey:["brokerage-agent-activation",s.brokerage_id],queryFn:async()=>{const{data:x,error:v}=await q.rpc("get_brokerage_agent_activation",{_brokerage_id:s.brokerage_id});if(v)throw v;return x}}),u=mt({mutationFn:async({userId:x,skip:v})=>{if(v){const{error:y}=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(y)throw y}else{const{error:y}=await q.from("agent_activation_state").update({exited_at:null,exit_reason:null,updated_at:new Date().toISOString()}).eq("user_id",x);if(y)throw y}},onSuccess:()=>{i.invalidateQueries({queryKey:["brokerage-agent-activation",s.brokerage_id]}),ne.success("Agent updated")},onError:()=>ne.error("Update failed")}),h=mt({mutationFn:async x=>{const{data:v,error:y}=await q.functions.invoke("agent-activation-run",{body:{action:"send_now",user_id:x,brokerage_id:s.brokerage_id}});if(y)throw y;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{i.invalidateQueries({queryKey:["brokerage-agent-activation",s.brokerage_id]}),ne.success("Email sent")},onError:x=>ne.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(je,{children:[e.jsxs(St,{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(kd,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:s.brokerage_name}),e.jsxs(Vn,{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(jn,{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(Le,{children:d?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:g.map(x=>{const v=x.exit_reason==="manual_skip";return e.jsxs(An,{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($e,{variant:x.stage==="active"?"default":"secondary",children:v?"Skipped":Iir[x.stage]})}),e.jsx(wt,{className:"text-right",children:x.login_count}),e.jsx(wt,{children:Mir(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($z,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(pn,{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(Zr,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>u.mutate({userId:x.user_id,skip:!v}),title:v?"Include in sequence":"Skip this agent",children:e.jsx(cV,{className:`h-3.5 w-3.5 ${v?"text-red-500":""}`})})]})})]},x.user_id)})})]})})]})}const Jis=new Date().getFullYear(),Dir=Array.from({length:10},(s,t)=>Jis-t);function XAt(){var g;const{userId:s}=Wi(),t=Zn(),r=qu().pathname.startsWith("/mission-control"),[a,i]=j.useState(Jis),{data:l,isLoading:o}=st({queryKey:["agent-profile",s],queryFn:async()=>{const{data:x,error:v}=await q.from("profiles").select("id, name, email").eq("id",s).single();if(v)throw v;return x},enabled:!!s}),{data:c,isLoading:d}=nnt(a,s),{yearStats:u,lifetimeStats:h,showCommission:m}=UUt(a,s),{data:f}=$Ut(a,s);return o?e.jsx(Vs,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(x=>e.jsx(xn,{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(Va,{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:Dir.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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yn,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(su,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Xm(u.totalVolume,!0)})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{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:Xm(u.averagePrice,!0)})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Im,{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(prs,{goals:f,stats:u,year:a,showCommission:m}),e.jsxs(pa,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"transactions",children:"Transactions"}),e.jsx(Xt,{value:"charts",children:"Charts"}),e.jsxs(Xt,{value:"map",children:[e.jsx(ui,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Qt,{value:"transactions",children:e.jsx(Dot,{transactions:c||[],showCommission:m,isLoading:d})}),e.jsx(Qt,{value:"charts",children:e.jsx(Fot,{stats:u,year:a})}),e.jsx(Qt,{value:"map",children:e.jsx(Oot,{transactions:c||[],isLoading:d})})]})]})})}function Fir(){const s=Zt(),[t,n]=j.useState(""),[r,a]=j.useState("all"),[i,l]=j.useState(null);Aae();const{data:o,refetch:c}=st({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}=st({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}=st({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}=st({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&&ne.success("Submitted to Google for indexing")}catch(U){console.error("Google indexing submission failed:",U)}},v=mt({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){ne.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}ne.success(`Submitted ${(R==null?void 0:R.succeeded)||0} URLs to Google (${(R==null?void 0:R.failed)||0} failed)`)},onError:R=>{ne.error("Failed to submit to Google"),console.error(R)}}),y=mt({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"]}),ne.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=mt({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"]}),ne.success(D?"Listing featured":"Listing unfeatured")}}),w=mt({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"]}),ne.success("Listing deleted")}}),S=mt({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(),ne.success("Feature flag updated")}}),A=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:()=>v.mutate(),disabled:v.isPending,className:"gap-2",children:[v.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(cl,{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(jn,{checked:A,onCheckedChange:R=>S.mutate(R)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wi,{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(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zl,{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(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{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(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ta,{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(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hd,{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(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lc,{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(je,{children:e.jsx(Le,{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(pa,{value:r,onValueChange:R=>a(R),children:e.jsxs(ga,{children:[e.jsx(Xt,{value:"all",children:"All"}),e.jsx(Xt,{value:"pending",children:"Pending"}),e.jsx(Xt,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{children:["Listings (",(E==null?void 0:E.length)||0,")"]})}),e.jsx(Le,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:u?e.jsx(An,{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(An,{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(An,{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(wi,{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($e,{variant:"outline",className:P(R.status),children:(V=R.status)==null?void 0:V.replace("_"," ")})}),e.jsx(wt,{className:"text-center",children:e.jsx(jn,{checked:R.is_approved??!1,onCheckedChange:G=>y.mutate({id:R.id,approved:G,slug:R.slug})})}),e.jsx(wt,{className:"text-center",children:e.jsx(jn,{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:Js(new Date(R.created_at),"MMM d, yyyy")}),e.jsx(wt,{children:e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",children:e.jsx(o_,{className:"h-4 w-4"})})}),e.jsxs(Cu,{align:"end",children:[e.jsxs(ja,{onClick:()=>window.open(`/mission-control/listings/${R.id}`,"_blank"),children:[e.jsx(Ta,{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(ei,{className:"h-4 w-4 mr-2"}),R.is_featured?"Unfeature":"Feature"]}),e.jsxs(ja,{className:"text-destructive",onClick:async()=>{await mo("Are you sure you want to delete this listing?")&&w.mutate(R.id)},children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},R.id)})})]})})})]})]}),e.jsx(Os,{open:!!i,onOpenChange:R=>!R&&l(null),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Leads from listing"}),e.jsx(Er,{children:i==null?void 0:i.label})]}),g?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(Ct,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:f.map(R=>{var D;return e.jsxs(An,{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($e,{variant:"outline",children:(D=R.lead_type)==null?void 0:D.replace("_"," ")})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:Js(new Date(R.created_at),"MMM d, yyyy h:mm a")})]},R.id)})})]})]})})]})}function Oir(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function zir(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),{data:l,isLoading:o}=st({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,v,y,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(v=>{var y,b,w,S,A,E;return[Js(new Date(v.created_at),"yyyy-MM-dd HH:mm"),`${v.first_name||""} ${v.last_name||""}`.trim(),v.email,v.phone||"",v.lead_type,v.preferred_date?`${v.preferred_date} ${v.preferred_time||""}`:"",((y=v.listing)==null?void 0:y.property_address)||"",((b=v.listing)==null?void 0:b.city)||"",(w=v.listing)!=null&&w.price?String(v.listing.price):"",((S=v.agent)==null?void 0:S.name)||"",((A=v.agent)==null?void 0:A.email)||"",((E=v.referrer)==null?void 0:E.name)||"",(v.message||"").replace(/[\r\n]+/g," ")]})].map(v=>v.map(y=>`"${String(y).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-${Js(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(ji,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lc,{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(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ea,{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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lc,{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(je,{children:e.jsx(Le,{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(je,{children:[e.jsx(St,{children:e.jsxs(Et,{children:["Leads (",c.length,")"]})}),e.jsx(Le,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:o?e.jsx(An,{children:e.jsx(wt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(An,{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(An,{children:[e.jsxs(wt,{className:"whitespace-nowrap text-sm",children:[Js(new Date(h.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:Js(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(pn,{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(br,{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(Ir,{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(", ")," · ",Oir(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(wt,{children:[e.jsx($e,{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(no,{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 X$={new_listing_alerts:{label:"New Listing Alerts",icon:zy,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:Bz,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:_x,color:"bg-emerald-100 text-emerald-800"}},QAt=[{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 JAt(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function Bir(){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=QAt.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:v,error:y}=await g;f||(y?(console.error(y),t([])):t(v||[]),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(v=>v.email.toLowerCase())).size,x={};return u.forEach(v=>{x[v.lead_type]=(x[v.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=[JAt(b.created_at),((S=X$[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(A=>`"${String(A).replace(/"/g,'""')}"`);g.push(w.join(","))});const x=new Blob([g.join(` `)],{type:"text/csv"}),v=URL.createObjectURL(x),y=document.createElement("a");y.href=v,y.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,y.click(),URL.revokeObjectURL(v)};return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(Dl,{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(br,{to:"/admin",children:e.jsxs($,{variant:"ghost",size:"sm",children:[e.jsx(Va,{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(ji,{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(je,{children:e.jsxs(Le,{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(X$).map(f=>{const g=X$[f],x=g.icon;return e.jsx(je,{children:e.jsxs(Le,{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:QAt.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(X$).map(f=>e.jsx(Ge,{value:f,children:X$[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(je,{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=X$[f.lead_type],x=g==null?void 0:g.icon,v=[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:JAt(f.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs($e,{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:v}),e.jsxs("a",{href:`mailto:${f.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(pn,{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(([y,b])=>`${y}: ${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(Ir,{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 $ir=()=>{var h,m;const[s,t]=j.useState(""),[n,r]=j.useState(null),{data:a,isLoading:i}=st({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:v}=await q.from("profiles").select("id, name, email").in("id",x);return f==null?void 0:f.map(b=>({...b,profiles:(v==null?void 0:v.find(w=>w.id===b.user_id))||null}))}}),l=a==null?void 0:a.filter(f=>{var x,v,y,b,w;const g=s.toLowerCase();return((v=(x=f.profiles)==null?void 0:x.name)==null?void 0:v.toLowerCase().includes(g))||((b=(y=f.profiles)==null?void 0:y.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(ei,{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(Dm,{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(je,{children:e.jsxs(St,{className:"pb-2",children:[e.jsx(Vn,{children:"Total Reviews"}),e.jsx(Et,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(je,{children:e.jsxs(St,{className:"pb-2",children:[e.jsx(Vn,{children:"Average Rating"}),e.jsxs(Et,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(ei,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(je,{children:e.jsxs(St,{className:"pb-2",children:[e.jsx(Vn,{children:"5-Star Reviews"}),e.jsx(Et,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(je,{children:e.jsxs(St,{className:"pb-2",children:[e.jsx(Vn,{children:"Posted to Google"}),e.jsxs(Et,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(Ir,{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(je,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:i?e.jsx(An,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(An,{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(An,{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($e,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx($e,{variant:"outline",children:"No"})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:Js(new Date(f.created_at),"MMM d, yyyy")})]},f.id)})})]})})}),e.jsx(Os,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx($s,{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(pn,{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(Ea,{className:"h-4 w-4"}),Js(new Date(n.created_at),"MMMM d, yyyy 'at' h:mm a")]}),n.posted_to_google?e.jsxs($e,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx($e,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},eEt={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},Uir={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 qir(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),[l,o]=j.useState("7"),{data:c,isLoading:d}=st({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(v=>v.status==="sent"||v.status==="backfilled").length,g=u.filter(v=>v.status==="failed").length,x=new Set(u.map(v=>v.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(Dm,{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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{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(eEt).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(je,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:d?e.jsx(An,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(An,{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(An,{children:[e.jsx(wt,{className:"whitespace-nowrap text-sm",children:Js(new Date(m.created_at),"MMM d, yyyy h:mm a")}),e.jsx(wt,{children:e.jsx($e,{variant:"secondary",children:eEt[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(pn,{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($e,{className:Uir[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 Vir=[{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"}],Hir=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 Gir(){const s=Zt(),{user:t}=_s(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(!1),{data:c,isLoading:d}=st({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}=st({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}=st({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}=st({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}=st({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}}),v=mt({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"]}),ne.success("Settings updated")},onError:P=>{ne.error("Failed to update settings: "+P.message)}}),y=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?ne.success(`${P.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):P.sent!==void 0&&ne.success(`Digest sent! ${P.sent} emails delivered, ${P.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(P){ne.error("Failed to send digest: "+P.message)}finally{r(!1)}},b=async()=>{var P,R,D,O,U,W;if(!(t!=null&&t.email)){ne.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 Z=V==null?void 0:V.resendId,X=V==null?void 0:V.resendDetails,ae=X==null?void 0:X.status,le=((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),re=((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);ne.success(Z?`Preview accepted by email provider (id: ${Z})${ae?`, status check: ${ae}`:""}${le?`, provider: ${le}`:""}${re?` (${re})`:""}. 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){ne.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?ne.info("No failed emails to retry"):P.queued?ne.success(`${P.queued} emails queued for retry!`):ne.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){ne.error("Failed to retry: "+P.message)}finally{o(!1)}},S=f!=null&&f.total?Math.round((f.sent+f.failed)/f.total*100):0,A=((f==null?void 0:f.pending)||0)>0||((f==null?void 0:f.processing)||0)>0,{data:E}=st({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:A?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(pa,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(Nd,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(Xt,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(Gl,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(Qt,{value:"settings",className:"space-y-6",children:[A&&f&&e.jsx(je,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Le,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(Ct,{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(je,{children:e.jsx(Le,{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(Yn,{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(je,{children:e.jsx(Le,{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(Vr,{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(je,{children:e.jsx(Le,{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(ju,{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(je,{children:e.jsx(Le,{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(ca,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.lastSent?Js(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(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(ca,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(Vn,{children:"Configure when the digest is sent"})]}),e.jsxs(Le,{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(jn,{checked:c==null?void 0:c.is_enabled,onCheckedChange:P=>v.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=>v.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=>v.mutate({send_day:parseInt(P)}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Vir.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=>v.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:Hir.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(Ta,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs($,{onClick:y,disabled:n,className:"flex-1",children:[e.jsx(Zr,{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(co,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${x} Failed`]})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Qr,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(Vn,{children:"Choose what to include in the digest"})]}),e.jsxs(Le,{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(Qr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"New Resources"})]}),e.jsx(jn,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:P=>v.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(Yn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Community Highlights"})]}),e.jsx(jn,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:P=>v.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(Gl,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Agent OS Stats"})]}),e.jsx(jn,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:P=>v.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(Ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Upcoming Events"})]}),e.jsx(jn,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:P=>v.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(ph,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Goals Progress"})]}),e.jsx(jn,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:P=>v.mutate({include_goals_progress:P})})]})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Custom Introduction"}),e.jsx(Vn,{children:"Personalize the intro message (optional)"})]}),e.jsx(Le,{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=>v.mutate({custom_intro_text:P.target.value||null}),rows:3})})]})]}),e.jsx(Qt,{value:"stats",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(Vn,{children:"Recent digest emails sent to members"})]}),e.jsx(Le,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:u.map(P=>e.jsxs(An,{children:[e.jsx(wt,{className:"font-medium",children:P.email_sent_to}),e.jsx(wt,{children:Js(new Date(P.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(wt,{children:e.jsx($e,{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($e,{variant:"secondary",children:"Active"}):e.jsx($e,{variant:"outline",children:"Not Started"})})]},P.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(pn,{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 Wir={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 Kir(){var J,ce,ve;const s=Zt(),[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,v]=j.useState(!1),[y,b]=j.useState(""),[w,S]=j.useState(null),{data:A,isLoading:E}=st({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:fe,error:ue}=await q.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(ue)throw ue;const be=(fe==null?void 0:fe.map(Ie=>Ie.user_id))||[],{data:Ee}=await q.from("profiles").select("id, name, email").in("id",be),ke=new Map((Ee==null?void 0:Ee.map(Ie=>[Ie.id,{name:Ie.name,email:Ie.email}]))||[]);return fe==null?void 0:fe.map(Ie=>({...Ie,profile:ke.get(Ie.user_id)||null}))}}),{data:I}=st({queryKey:["all-profiles-for-points",A],queryFn:async()=>{const ue=[];let be=0;for(;;){const{data:Ee,error:ke}=await q.from("profiles").select("id, name, email").order("name").range(be,be+1e3-1);if(ke)throw ke;if(ue.push(...Ee),!Ee||Ee.length<1e3)break;be+=1e3}return ue}}),R=((I==null?void 0:I.filter(fe=>!(A!=null&&A.some(ue=>ue.user_id===fe.id))))||[]).filter(fe=>{var be,Ee;if(!y)return!0;const ue=y.toLowerCase();return((be=fe.name)==null?void 0:be.toLowerCase().includes(ue))||((Ee=fe.email)==null?void 0:Ee.toLowerCase().includes(ue))}),{data:D,isLoading:O}=st({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:fe,error:ue}=await q.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(ue)throw ue;return fe},enabled:!!(r!=null&&r.user_id)&&o}),{data:U}=st({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:fe,error:ue}=await q.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(ue)throw ue;return fe},enabled:!!(r!=null&&r.user_id)}),W=mt({mutationFn:async({userId:fe,points:ue,reason:be})=>{const{error:Ee}=await q.from("agent_points").insert({user_id:fe,points:ue,reason:be});if(Ee)throw Ee;const{data:ke}=await q.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",fe).maybeSingle(),Ie=((ke==null?void 0:ke.total_points)||0)+ue,Fe=((ke==null?void 0:ke.spendable_points)||0)+ue,{error:Ne}=await q.from("agent_attendance_stats").upsert({user_id:fe,total_points:Math.max(0,Ie),spendable_points:Math.max(0,Fe),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(Ne)throw Ne},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),u(""),m(""),ne.success(f?"Points awarded successfully!":"Points deducted successfully!")},onError:fe=>{console.error("Error modifying points:",fe),ne.error("Failed to modify points")}}),V=()=>{if(!r||!d||!h){ne.error("Please fill in all fields");return}const fe=parseInt(d);if(isNaN(fe)||fe<=0){ne.error("Please enter a valid positive number");return}W.mutate({userId:r.user_id,points:f?fe:-fe,reason:h})},G=()=>{if(!w||!d||!h){ne.error("Please fill in all fields");return}const fe=parseInt(d);if(isNaN(fe)||fe<=0){ne.error("Please enter a valid positive number");return}W.mutate({userId:w.id,points:fe,reason:h},{onSuccess:()=>{v(!1),S(null),b("")}})},Z=(fe,ue)=>{a(fe),g(ue),l(!0)},X=fe=>{a(fe),c(!0)},ae=A==null?void 0:A.filter(fe=>{var ke,Ie,Fe,Ne;const ue=((Ie=(ke=fe.profile)==null?void 0:ke.name)==null?void 0:Ie.toLowerCase())||"",be=((Ne=(Fe=fe.profile)==null?void 0:Fe.email)==null?void 0:Ne.toLowerCase())||"",Ee=t.toLowerCase();return ue.includes(Ee)||be.includes(Ee)}),le=(A==null?void 0:A.reduce((fe,ue)=>fe+ue.total_points,0))||0,re=(A==null?void 0:A.length)||0,te=re>0?Math.round(le/re):0;return E?e.jsx(Vs,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(fe=>e.jsx(xn,{className:"h-24"},fe))}),e.jsx(xn,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yn,{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:re}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(je,{children:e.jsxs(Le,{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:le.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zl,{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:fe=>n(fe.target.value),className:"pl-10"})]}),e.jsxs($,{onClick:()=>v(!0),children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Agent Leaderboard"}),e.jsx(Vn,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Le,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:ae.map((fe,ue)=>{var be,Ee,ke,Ie;return e.jsxs(An,{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=(be=fe.profile)==null?void 0:be.name)==null?void 0:Ee.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((ke=fe.profile)==null?void 0:ke.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Ie=fe.profile)==null?void 0:Ie.email})]})]})}),e.jsx(wt,{className:"text-center",children:e.jsxs($e,{variant:"secondary",className:"font-bold",children:[e.jsx(ei,{className:"h-3 w-3 mr-1"}),fe.total_points]})}),e.jsx(wt,{className:"text-center",children:e.jsxs($e,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(dl,{className:"h-3 w-3 mr-1"}),fe.spendable_points||0]})}),e.jsx(wt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Ea,{className:"h-3 w-3 text-muted-foreground"}),fe.total_events_attended]})}),e.jsx(wt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(sh,{className:"h-3 w-3 text-orange-500"}),fe.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:()=>Z(fe,!0),title:"Award points",children:e.jsx(cn,{className:"h-4 w-4 text-green-600"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Z(fe,!1),title:"Deduct points",children:e.jsx(YN,{className:"h-4 w-4 text-red-600"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>X(fe),title:"View history",children:e.jsx(Cw,{className:"h-4 w-4"})})]})})]},fe.user_id)})})]})})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:f?"Award Points":"Deduct Points"}),e.jsxs(Er,{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:fe=>u(fe.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:fe=>m(fe.target.value)})]})]}),e.jsxs(Nr,{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(Os,{open:o,onOpenChange:c,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsxs($s,{children:["Point History: ",(ce=r==null?void 0:r.profile)==null?void 0:ce.name]}),e.jsx(Er,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(pa,{defaultValue:"history",className:"w-full",children:[e.jsxs(ga,{className:"grid w-full grid-cols-2",children:[e.jsx(Xt,{value:"history",children:"Point History"}),e.jsx(Xt,{value:"badges",children:"Badges"})]}),e.jsx(Qt,{value:"history",className:"mt-4",children:O?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(fe=>e.jsx(xn,{className:"h-12"},fe))}):!D||D.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Cw,{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(fe=>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:fe.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Js(new Date(fe.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs($e,{variant:fe.points>=0?"default":"destructive",className:fe.points>=0?"bg-green-100 text-green-800":"",children:[fe.points>=0?"+":"",fe.points]})]},fe.id))})}),e.jsx(Qt,{value:"badges",className:"mt-4",children:!U||U.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Im,{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(fe=>e.jsxs("div",{className:`p-3 rounded-lg ${Wir[fe.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Im,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:fe.badge_name})]}),fe.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:fe.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",Js(new Date(fe.earned_at),"MMM d, yyyy")]})]},fe.id))})})]})]})}),e.jsx(Os,{open:x,onOpenChange:fe=>{v(fe),fe||(S(null),b(""),u(""),m(""))},children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Award Points to New Agent"}),e.jsx(Er,{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:((ve=w.name)==null?void 0:ve.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:fe=>u(fe.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:fe=>m(fe.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:y,onChange:fe=>b(fe.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(Yn,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:y?"No matching agents found":"All agents already have points"})]}):R.slice(0,20).map(fe=>{var ue;return e.jsxs("button",{onClick:()=>S(fe),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=fe.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:fe.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:fe.email})]})]},fe.id)})})]})}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),w&&e.jsxs($,{onClick:G,disabled:W.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function Yir(){const{data:s,isLoading:t}=bDs(),[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:v}=st({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(A=>{S[A.id]={name:A.name||"",email:A.email||""}}),S},enabled:g.length>0}),{data:y}=st({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:A}=await q.from("agent_card_leads").select("card_id").in("card_id",x);return A==null||A.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(A=>{var I,P;const E=v==null?void 0:v[A.user_id];return A.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,A)=>new Date(A.created_at).getTime()-new Date(S.created_at).getTime()):u==="oldest"?w.sort((S,A)=>new Date(S.created_at).getTime()-new Date(A.created_at).getTime()):u==="name"?w.sort((S,A)=>{var E,I;return(((E=v==null?void 0:v[S.user_id])==null?void 0:E.name)||"").localeCompare(((I=v==null?void 0:v[A.user_id])==null?void 0:I.name)||"")}):u==="slug"?w.sort((S,A)=>S.slug.localeCompare(A.slug)):u==="views_desc"?w.sort((S,A)=>{var E,I;return(((E=y==null?void 0:y[A.id])==null?void 0:E.views)||0)-(((I=y==null?void 0:y[S.id])==null?void 0:I.views)||0)}):u==="views_asc"?w.sort((S,A)=>{var E,I;return(((E=y==null?void 0:y[S.id])==null?void 0:E.views)||0)-(((I=y==null?void 0:y[A.id])==null?void 0:I.views)||0)}):u==="leads_desc"?w.sort((S,A)=>{var E,I;return(((E=y==null?void 0:y[A.id])==null?void 0:E.leads)||0)-(((I=y==null?void 0:y[S.id])==null?void 0:I.leads)||0)}):u==="leads_asc"&&w.sort((S,A)=>{var E,I;return(((E=y==null?void 0:y[S.id])==null?void 0:E.leads)||0)-(((I=y==null?void 0:y[A.id])==null?void 0:I.leads)||0)}),w},[s,c,l,u,v]);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(cn,{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(tV,{className:"h-4 w-4"})}),e.jsx($,{variant:m==="grid"?"default":"ghost",size:"sm",onClick:()=>f("grid"),className:"rounded-l-none",children:e.jsx(Xf,{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(xn,{className:"h-48"},w))}):b.length>0?m==="table"?e.jsx(Zir,{cards:b,cardProfiles:v,cardStats:y,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(Xir,{card:w,onEdit:()=>r(w),stats:y==null?void 0:y[w.id]},w.id))}):s&&s.length>0?e.jsx(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Yn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No 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(cn,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(Qir,{open:a,onOpenChange:i}),n&&e.jsx(Jir,{card:n,open:!!n,onOpenChange:w=>!w&&r(null)})]})}function Zir({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(Lg,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(Zf,{className:"h-3 w-3"}):e.jsx(Dy,{className:"h-3 w-3 opacity-40"});return e.jsx(je,{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($e,{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(pi,{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),ne.success("Link copied!")},children:e.jsx(Za,{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(Ir,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function Xir({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),ne.success("Link copied!")};return e.jsx(je,{children:e.jsxs(Le,{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(Ii,{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($e,{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(Ta,{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(Yn,{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(pi,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx($,{variant:"outline",size:"sm",onClick:l,children:e.jsx(Za,{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(Ir,{className:"h-3 w-3"})})})]})]})})}function Qir({open:s,onOpenChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(!1),u=R7t(),h=l.trim(),{data:m}=st({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,v=()=>{if(!n||!a.trim()){ne.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("")}})},y=b=>{var S;r(b),d(!1);const w=m==null?void 0:m.find(A=>A.id===b);w&&(g(w),i(((S=w.name)==null?void 0:S.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Create Agent Card"}),e.jsx(Er,{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(Gd,{open:c,onOpenChange:d,children:[e.jsx(Wd,{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(kw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Dd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(N2,{shouldFilter:!1,children:[e.jsx(k2,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(S2,{children:[e.jsx(C2,{children:"No agents found."}),e.jsx(Rw,{children:(m||[]).map(b=>e.jsxs(h1,{value:b.id,onSelect:y,children:[e.jsx(ma,{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:v,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function Jir({card:s,open:t,onOpenChange:n}){const r=D7t(),{data:a}=F7t(s.id),i=Zt(),[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),[v,y]=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/")){ne.error("Please select an image file");return}if(D.size>5*1024*1024){ne.error("Image must be under 5MB");return}const O=new FileReader;O.onloadend=()=>{f(O.result),h(!0)},O.readAsDataURL(D),R.target.value=""},A=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"]}),ne.success("Photo updated!")}catch(D){ne.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){ne.error("Please enter a valid URL");return}if(R===s.slug){ne.info("No changes to save");return}y(!0);try{const{data:D}=await q.from("agent_cards").select("id").eq("slug",R).neq("id",s.id).maybeSingle();if(D){ne.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"]}),ne.success("Card address updated!")}catch{ne.error("Failed to update card address")}finally{y(!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/")){ne.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:Z}=await q.storage.from("card-logos").upload(G,O,{upsert:!0});if(Z)throw Z;const{data:X}=q.storage.from("card-logos").getPublicUrl(G),ae=X.publicUrl+"?t="+Date.now();w(D==="brokerage_logo_url"?le=>({...le,[D]:ae,brokerage_display_name:""}):le=>({...le,[D]:ae,team_name:""})),ne.success("Logo uploaded!")}catch{ne.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(Os,{open:t,onOpenChange:n,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Edit Agent Card"}),e.jsxs(Er,{children:["/card/",s.slug]})]}),e.jsxs(pa,{defaultValue:"content",children:[e.jsxs(ga,{className:"w-full",children:[e.jsx(Xt,{value:"content",className:"flex-1",children:"Content"}),e.jsx(Xt,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(Xt,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(Xt,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(Qt,{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(jn,{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(Ii,{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(Ct,{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:v||g===s.slug,className:"shrink-0",children:v?"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(bx,{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(bx,{value:[b.team_logo_size||56],onValueChange:([R])=>w(D=>({...D,team_logo_size:R})),min:24,max:120,step:4})]})]})]})]}),e.jsx(Qt,{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(jn,{checked:b[R],onCheckedChange:U=>w(W=>({...W,[R]:U}))})]},R))}),e.jsx(Qt,{value:"blocks",className:"mt-4",children:e.jsx(Yis,{cardId:s.id})}),e.jsx(Qt,{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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{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($e,{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(Gnt,{open:u,onClose:()=>h(!1),imageSrc:m,onCropComplete:A,aspectRatio:1})]})}const qV={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"},Alt={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 Elt(s=!0){return st({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 eor(){const s=Zt();return mt({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"]}),ne.success("Category created successfully")},onError:t=>{ne.error("Failed to create category: "+t.message)}})}function tor(){const s=Zt();return mt({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"]}),ne.success("Category updated successfully")},onError:t=>{ne.error("Failed to update category: "+t.message)}})}function sor(){const s=Zt();return mt({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"]}),ne.success("Category deleted successfully")},onError:t=>{ne.error("Failed to delete category: "+t.message)}})}function eos(s,t=!0){return st({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 nor(s){return st({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 ror(){const s=Zt();return mt({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"]}),ne.success("Product created successfully")},onError:t=>{ne.error("Failed to create product: "+t.message)}})}function aor(){const s=Zt();return mt({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]}),ne.success("Product updated successfully")},onError:t=>{ne.error("Failed to update product: "+t.message)}})}function ior(){const s=Zt();return mt({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"]}),ne.success("Product deleted successfully")},onError:t=>{ne.error("Failed to delete product: "+t.message)}})}function oor(){const s=Zt();return mt({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 lor(){const s=Zt();return mt({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]}),ne.success("Image deleted successfully")},onError:t=>{ne.error("Failed to delete image: "+t.message)}})}function cor(){const s=Zt();return mt({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]}),ne.success("Primary image updated")},onError:t=>{ne.error("Failed to set primary image: "+t.message)}})}function dor(){const s=Zt();return mt({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]}),ne.success("Variant added successfully")}})}function uor(){const s=Zt();return mt({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]}),ne.success("Variant deleted successfully")}})}function hor(){const s=Zt();return mt({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]}),ne.success("Video updated successfully")}})}function mor(s){const{isAdmin:t}=_s();return st({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 por(){const{user:s}=_s();return st({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 gor(s){return st({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 xor(){const s=Zt(),{user:t}=_s();return mt({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"]}),ne.success("Order status updated")},onError:n=>{ne.error("Failed to update order: "+n.message)}})}function yor(){const s=Zt();return mt({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"]}),ne.success("Proof uploaded & customer notified")}})}function vor(){const s=Zt();return mt({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"]}),ne.success("Proof approved")}})}function bor(){const s=Zt();return mt({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"]}),ne.success("Proof rejected - please upload a new proof")}})}function _or(){const{data:s,isLoading:t}=Elt(!1),n=eor(),r=tor(),a=sor(),[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 mo("Are you sure you want to delete this category?")&&await a.mutateAsync(x)};return t?e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(xn,{className:"h-8 w-48"})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(x=>e.jsx(xn,{className:"h-12 w-full"},x))})})]}):e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsx(Et,{children:"Categories"}),e.jsxs(Os,{open:i,onOpenChange:x=>{l(x),x||h()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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(jn,{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(Le,{children:s&&s.length>0?e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:s.map(x=>e.jsxs(An,{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(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(x.id),disabled:a.isPending,children:e.jsx(qn,{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 wor(){var te,J;const{data:s,isLoading:t}=eos(void 0,!1),{data:n}=Elt(!1),r=ror(),a=aor(),i=ior(),l=oor(),o=lor(),c=cor(),d=dor(),u=uor(),h=hor(),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[v,y]=j.useState(!1),[b,w]=j.useState(null),[S,A]=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)},Z=async ce=>{ce.preventDefault();const ve={...P,category_id:P.category_id||null};b?await a.mutateAsync({id:b.id,...ve}):await r.mutateAsync(ve),f(!1),V()},X=async ce=>{await mo("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 ve=ce.target.files[0],fe=ve.name.split(".").pop(),ue=`products/${S.id}/${Date.now()}.${fe}`;try{const{error:be}=await q.storage.from("marketplace").upload(ue,ve);if(be)throw be;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}),ne.success("Image uploaded successfully")}catch(be){ne.error("Failed to upload image: "+be.message)}finally{I(!1)}},le=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}))},re=async()=>{!S||!U||(await h.mutateAsync({productId:S.id,videoUrl:U}),W(""))};return t?e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(xn,{className:"h-8 w-48"})}),e.jsx(Le,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(ce=>e.jsx(xn,{className:"h-64 w-full"},ce))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsx(Et,{children:"Products"}),e.jsxs(Os,{open:m,onOpenChange:ce=>{f(ce),ce||V()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{children:b?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:Z,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(jn,{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(jn,{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(jn,{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(Le,{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 ve,fe;return e.jsxs(je,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[ce.images&&ce.images.length>0?e.jsx("img",{src:((ve=ce.images.find(ue=>ue.is_primary))==null?void 0:ve.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($e,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Le,{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:((fe=ce.category)==null?void 0:fe.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($e,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),ce.requires_proof_approval&&e.jsx($e,{variant:"outline",className:"text-xs",children:"Proof Required"}),ce.variants&&ce.variants.length>0&&e.jsxs($e,{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(pi,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{A(ce),x(!0)},children:[e.jsx(kv,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{A(ce),y(!0)},children:[e.jsx(Cp,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>X(ce.id),children:e.jsx(qn,{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(Os,{open:g,onOpenChange:x,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs($s,{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($e,{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 ve;await c.mutateAsync({imageId:ce.id,productId:S.id}),A({...S,images:(ve=S.images)==null?void 0:ve.map(fe=>({...fe,is_primary:fe.id===ce.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(ei,{className:"h-4 w-4"})}),e.jsx($,{variant:"destructive",size:"icon",onClick:async()=>{var fe;await o.mutateAsync({id:ce.id,productId:S.id});const ve=s==null?void 0:s.find(ue=>ue.id===S.id);ve&&A({...ve,images:(fe=ve.images)==null?void 0:fe.filter(ue=>ue.id!==ce.id)})},disabled:o.isPending,children:e.jsx(qn,{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(kv,{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:re,disabled:!U,children:[e.jsx(fa,{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(Os,{open:v,onOpenChange:y,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsxs($s,{children:["Manage Variants - ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:le,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(qn,{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 jor=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function Nor(){var x,v,y;const{data:s,isLoading:t}=mor(),n=xor(),r=yor(),[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],A=S.name.split(".").pop(),E=`proofs/${a.id}/${w}/${Date.now()}.${A}`;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}),ne.success("Proof uploaded successfully")}catch(I){ne.error("Failed to upload proof: "+I.message)}finally{h(!1)}};return t?e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(xn,{className:"h-8 w-48"})}),e.jsx(Le,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(b=>e.jsx(xn,{className:"h-16 w-full"},b))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Orders"})}),e.jsx(Le,{children:s&&s.length>0?e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:s.map(b=>{var w,S;return e.jsxs(An,{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:Js(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($e,{className:Alt[b.status],children:qV[b.status]})}),e.jsx(wt,{className:"text-right",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(b),children:[e.jsx(Ta,{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(Os,{open:l,onOpenChange:o,children:e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs($s,{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:(v=a.user)==null?void 0:v.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:(y=a.items)==null?void 0:y.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($e,{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:jor.map(b=>e.jsx(Ge,{value:b,children:qV[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(ym,{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($e,{variant:"outline",children:qV[b.status]}),b.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:b.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:Js(new Date(b.created_at),"MMM d, h:mm a")})]},b.id))})]})]})]})})]})}function kor(){const[s,t]=j.useState("products"),n=Zn();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(Ir,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(pa,{value:s,onValueChange:t,children:[e.jsxs(ga,{className:"grid w-full grid-cols-3",children:[e.jsxs(Xt,{value:"products",className:"flex items-center gap-2",children:[e.jsx(ym,{className:"h-4 w-4"}),"Products"]}),e.jsxs(Xt,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(Nv,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(Xt,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(eC,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(Qt,{value:"products",children:e.jsx(wor,{})}),e.jsx(Qt,{value:"categories",children:e.jsx(_or,{})}),e.jsx(Qt,{value:"orders",children:e.jsx(Nor,{})})]})]})})}function tos(){return st({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 Sor(s){return st({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 Cor(s){return st({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 Aor(s){return st({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 Eor(){return st({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 Tor(s){return st({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 Mor(){const s=Zt();return mt({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 Por(){const s=Zt();return mt({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 Ior(){const s=Zt();return mt({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 Lor(){const s=Zt();return mt({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 Ror(){const s=Zt();return mt({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 Dor(){const s=Zt();return mt({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 For(){const s=Zt();return mt({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 Oor(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function lUe(s,t){const n=Oor(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),ne.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),ne.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),ne.error("Failed to download file")}}function sos(){return st({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 zor(){const s=Zt();return mt({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 Bor(){const{user:s}=_s(),[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,v]=j.useState(!1),[y,b]=j.useState(null),[w,S]=j.useState(""),[A,E]=j.useState(""),[I,P]=j.useState(null),[R,D]=j.useState(""),[O,U]=j.useState("file"),[W,V]=j.useState(""),[G,Z]=j.useState(""),[X,ae]=j.useState(""),[le,re]=j.useState(!0),[te,J]=j.useState(null),[ce,ve]=j.useState(!1),[fe,ue]=j.useState(!1),be=j.useRef(null),Ee=j.useRef(null),{data:ke,isLoading:Ie}=tos(),{data:Fe,isLoading:Ne}=Sor(),{data:Be,isLoading:Se}=Eor(),{data:Ae,isLoading:Ce}=sos(),qe=Por(),ze=Ior(),Ve=Lor(),ht=Ror(),Qe=Dor(),at=For(),rt=zor(),[Ke,Je]=j.useState({}),ft=jt=>{jt?(l(jt),c(jt.name),u(jt.description||""),m(jt.icon||"")):(l(null),c(""),u(""),m("")),a(!0)},gt=async()=>{if(!o.trim()){ne.error("Please enter a category name");return}try{i?(await ze.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),ne.success("Category updated successfully")):(await qe.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((ke==null?void 0:ke.length)||0)+1}),ne.success("Category created successfully")),a(!1)}catch(jt){console.error("Error saving category:",jt),ne.error("Failed to save category")}},es=async()=>{if(f)try{await Ve.mutateAsync(f),ne.success("Category deleted successfully"),g(null)}catch(jt){console.error("Error deleting category:",jt),ne.error("Failed to delete category")}},Ht=jt=>{var zs;jt?(b(jt),S(jt.name),E(jt.description||""),P(jt.category_id),D(jt.points_cost.toString()),U(jt.item_type),V(jt.file_url||""),Z(jt.preview_image_url||""),ae(((zs=jt.max_quantity)==null?void 0:zs.toString())||""),re(jt.is_active)):(b(null),S(""),E(""),P(null),D(""),U("file"),V(""),Z(""),ae(""),re(!0)),v(!0)},as=async(jt,zs)=>{zs==="file"?ve(!0):ue(!0);try{const yt=jt.name.split(".").pop(),gs=`${Date.now()}-${Math.random().toString(36).substring(7)}.${yt}`,Ss=`${zs==="file"?"items":"previews"}/${gs}`,{error:Ds}=await q.storage.from("reward-store").upload(Ss,jt);if(Ds)throw Ds;const{data:{publicUrl:Bt}}=q.storage.from("reward-store").getPublicUrl(Ss);zs==="file"?V(Bt):Z(Bt),ne.success("File uploaded successfully")}catch(yt){console.error("Error uploading file:",yt),ne.error("Failed to upload file")}finally{zs==="file"?ve(!1):ue(!1)}},bs=async()=>{if(!w.trim()){ne.error("Please enter an item name");return}if(!R||parseInt(R)<0){ne.error("Please enter a valid points cost");return}try{const jt={name:w,description:A||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:le,created_by:s==null?void 0:s.id};y?(await Qe.mutateAsync({id:y.id,...jt,current_quantity:y.max_quantity!==(X?parseInt(X):null)?X?parseInt(X):null:y.current_quantity}),ne.success("Item updated successfully")):(await ht.mutateAsync(jt),ne.success("Item created successfully")),v(!1)}catch(jt){console.error("Error saving item:",jt),ne.error("Failed to save item")}},Ut=async()=>{if(te)try{await at.mutateAsync(te),ne.success("Item deleted successfully"),J(null)}catch(jt){console.error("Error deleting item:",jt),ne.error("Failed to delete item")}},Ft=async(jt,zs)=>{const yt=Ke[jt];if(yt===void 0||yt===zs.toString())return;const gs=parseInt(yt);if(isNaN(gs)||gs<0){ne.error("Please enter a valid positive number");return}try{await rt.mutateAsync({id:jt,points:gs}),ne.success("Points updated successfully"),Je(Ss=>{const Ds={...Ss};return delete Ds[jt],Ds})}catch(Ss){console.error("Error updating points:",Ss),ne.error("Failed to update points")}};return Ie||Ne||Se||Ce?e.jsx(Vs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{className:"h-8 w-64"}),e.jsx(xn,{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(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ym,{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(jt=>jt.is_active).length)||0," active"]})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Nv,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(ke==null?void 0:ke.length)||0})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ei,{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((jt,zs)=>jt+zs.points_cost,0)/Fe.length):0," pts"]})]})})]}),e.jsxs(pa,{value:t,onValueChange:n,children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"items",children:"Items"}),e.jsx(Xt,{value:"categories",children:"Categories"}),e.jsx(Xt,{value:"purchases",children:"Purchases"}),e.jsx(Xt,{value:"point-settings",children:"Point Settings"})]}),e.jsx(Qt,{value:"items",className:"mt-4",children:e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Et,{children:"Store Items"}),e.jsx(Vn,{children:"Manage rewards that agents can purchase"})]}),e.jsxs($,{onClick:()=>Ht(),children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Le,{children:!Fe||Fe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(dl,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:Fe.map(jt=>e.jsxs(An,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[jt.preview_image_url?e.jsx("img",{src:jt.preview_image_url,alt:jt.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(dl,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:jt.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:jt.description||"No description"})]})]})}),e.jsx(wt,{children:jt.category?e.jsx($e,{variant:"outline",children:jt.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(wt,{className:"text-center",children:e.jsxs($e,{variant:"secondary",className:"font-bold",children:[e.jsx(ei,{className:"h-3 w-3 mr-1"}),jt.points_cost]})}),e.jsx(wt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[jt.item_type==="file"?e.jsx(Qr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Sd,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:jt.item_type})]})}),e.jsx(wt,{className:"text-center",children:jt.max_quantity!==null?e.jsxs("span",{className:jt.current_quantity===0?"text-red-500":"",children:[jt.current_quantity,"/",jt.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(wt,{className:"text-center",children:e.jsx($e,{variant:jt.is_active?"default":"secondary",children:jt.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:()=>Ht(jt),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>J(jt.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},jt.id))})]})})]})}),e.jsx(Qt,{value:"categories",className:"mt-4",children:e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Et,{children:"Categories"}),e.jsx(Vn,{children:"Organize your store items into categories"})]}),e.jsxs($,{onClick:()=>ft(),children:[e.jsx(cn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Le,{children:!ke||ke.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Nv,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:ke.map(jt=>e.jsxs(An,{children:[e.jsxs(wt,{className:"font-medium",children:[jt.icon&&e.jsx("span",{className:"mr-2",children:jt.icon}),jt.name]}),e.jsx(wt,{className:"text-muted-foreground",children:jt.description||"—"}),e.jsx(wt,{className:"text-center",children:(Fe==null?void 0:Fe.filter(zs=>zs.category_id===jt.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:()=>ft(jt),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>g(jt.id),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})})]},jt.id))})]})})]})}),e.jsx(Qt,{value:"purchases",className:"mt-4",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(eC,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(Vn,{children:"View all reward redemptions by agents"})]}),e.jsx(Le,{children:!Be||Be.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(eC,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:Be.map(jt=>{var zs,yt,gs,Ss;return e.jsxs(An,{children:[e.jsx(wt,{className:"text-muted-foreground",children:Js(new Date(jt.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:((zs=jt.user)==null?void 0:zs.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((yt=jt.user)==null?void 0:yt.email)||"—"})]})]})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(gs=jt.item)!=null&&gs.preview_image_url?e.jsx("img",{src:jt.item.preview_image_url,alt:jt.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(dl,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((Ss=jt.item)==null?void 0:Ss.name)||"Deleted item"})]})}),e.jsx(wt,{className:"text-center",children:e.jsxs($e,{variant:"secondary",className:"font-bold",children:[e.jsx(ei,{className:"h-3 w-3 mr-1"}),jt.points_spent]})})]},jt.id)})})]})})]})})]})]}),e.jsx(Os,{open:r,onOpenChange:a,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:i?"Edit Category":"Add Category"}),e.jsx(Er,{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:jt=>c(jt.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:jt=>u(jt.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:jt=>m(jt.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{onClick:gt,disabled:qe.isPending||ze.isPending,children:qe.isPending||ze.isPending?"Saving...":"Save"})]})]})}),e.jsx(Os,{open:x,onOpenChange:v,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:y?"Edit Item":"Add Item"}),e.jsx(Er,{children:y?"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:jt=>S(jt.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:A,onChange:jt=>E(jt.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:jt=>P(jt==="none"?null:jt),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select category"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No category"}),ke==null?void 0:ke.map(jt=>e.jsxs(Ge,{value:jt.id,children:[jt.icon&&`${jt.icon} `,jt.name]},jt.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:jt=>D(jt.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:jt=>ae(jt.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:jt=>V(jt.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 jt;return(jt=be.current)==null?void 0:jt.click()},disabled:ce,children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx("input",{ref:be,type:"file",className:"hidden",onChange:jt=>{var yt;const zs=(yt=jt.target.files)==null?void 0:yt[0];zs&&as(zs,"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:jt=>Z(jt.target.value),placeholder:"Upload an image or paste URL"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>{var jt;return(jt=Ee.current)==null?void 0:jt.click()},disabled:fe,children:e.jsx(Hc,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ee,type:"file",accept:"image/*",className:"hidden",onChange:jt=>{var yt;const zs=(yt=jt.target.files)==null?void 0:yt[0];zs&&as(zs,"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(jn,{id:"itemIsActive",checked:le,onCheckedChange:re}),e.jsx(ee,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx($,{onClick:bs,disabled:ht.isPending||Qe.isPending,children:ht.isPending||Qe.isPending?"Saving...":"Save"})]})]})}),e.jsx(fc,{open:!!f,onOpenChange:()=>g(null),children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Delete Category"}),e.jsx(ic,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:es,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(fc,{open:!!te,onOpenChange:()=>J(null),children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Delete Item"}),e.jsx(ic,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:Ut,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(je,{className:"mt-4",children:[e.jsx(St,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nd,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(Et,{children:"Point Reward Settings"}),e.jsx(Vn,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Le,{children:!Ae||Ae.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Nd,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:Ae.map(jt=>e.jsxs(An,{children:[e.jsx(wt,{children:e.jsx("p",{className:"font-medium",children:jt.action_name})}),e.jsx(wt,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:jt.description})}),e.jsx(wt,{className:"text-center",children:e.jsx(pe,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:Ke[jt.id]??jt.points.toString(),onChange:zs=>Je(yt=>({...yt,[jt.id]:zs.target.value}))})}),e.jsx(wt,{className:"text-right",children:e.jsx($,{size:"sm",variant:"outline",disabled:Ke[jt.id]===void 0||Ke[jt.id]===jt.points.toString()||rt.isPending,onClick:()=>Ft(jt.id,jt.points),children:e.jsx(tl,{className:"h-4 w-4"})})})]},jt.id))})]})})]})]})}const tEt=()=>e.jsxs("svg",{viewBox:"0 0 100 100",className:"h-5 w-5",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("rect",{width:"100",height:"100",rx:"20",fill:"#7D2AE8"}),e.jsx("path",{d:"M50 20C33.43 20 20 33.43 20 50C20 66.57 33.43 80 50 80C66.57 80 80 66.57 80 50C80 33.43 66.57 20 50 20ZM63.5 63.5C58.3 68.7 50 70.6 43.1 67.6C36.2 64.6 32 57.6 32 50C32 42.4 36.2 35.4 43.1 32.4C50 29.4 58.3 31.3 63.5 36.5L59.3 40.7C55.8 37.2 50.7 35.8 46 37.3C41.3 38.8 37.7 42.8 36.6 47.6C35.5 52.4 37 57.4 40.4 60.8C43.8 64.2 48.8 65.7 53.6 64.6C58.4 63.5 62.4 59.9 63.9 55.2L68.7 56.7C66.9 61.3 65.5 61.5 63.5 63.5Z",fill:"white"})]}),sEt=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function $or(){const s=Zt(),[t,n]=j.useState(!1),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""}),{data:d,isLoading:u}=st({queryKey:["canva-integration"],queryFn:async()=>{const{data:b,error:w}=await q.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(w)throw w;return b}}),{data:h}=st({queryKey:["brokerages-list"],queryFn:async()=>{const{data:b,error:w}=await q.from("brokerages").select("id, name").order("name");if(w)throw w;return b}}),{data:m}=st({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:b,error:w}=await q.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(w)throw w;return b}}),f=async()=>{var b;n(!0);try{const{data:w}=await q.auth.getSession(),S=(b=w==null?void 0:w.session)==null?void 0:b.access_token;if(!S)throw new Error("Not authenticated");const I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"get_auth_url"})}),P=await I.json();if(!I.ok||P!=null&&P.error)throw new Error((P==null?void 0:P.error)||"Failed to get authorization URL");if(P!=null&&P.authUrl){localStorage.setItem("canva_code_verifier",P.codeVerifier),localStorage.setItem("canva_oauth_state",P.state);const R=window.open(P.authUrl,"canva-oauth","width=600,height=700,scrollbars=yes,resizable=yes");if(!R){ne.error("Popup was blocked. Please allow popups for this site and try again."),n(!1);return}const D=U=>{var W,V;U.origin===window.location.origin&&(((W=U.data)==null?void 0:W.type)==="canva-oauth-success"?(window.removeEventListener("message",D),ne.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1)):((V=U.data)==null?void 0:V.type)==="canva-oauth-error"&&(window.removeEventListener("message",D),ne.error("Canva connection failed: "+(U.data.error||"Unknown error")),n(!1)))};window.addEventListener("message",D);const O=setInterval(()=>{R.closed&&(clearInterval(O),window.removeEventListener("message",D),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1))},500)}else throw new Error("Failed to get authorization URL")}catch(w){console.error("Canva connect error:",w);const S=(w==null?void 0:w.message)||"";S.includes("CANVA_CLIENT_ID")?ne.error("Canva app credentials not configured yet."):ne.error(S||"Failed to start Canva connection"),n(!1)}},g=mt({mutationFn:async b=>{var R;const{data:w}=await q.auth.getSession(),S=(R=w==null?void 0:w.session)==null?void 0:R.access_token;if(!S)throw new Error("Not authenticated");const I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"disconnect",integrationId:b})}),P=await I.json();if(!I.ok||P!=null&&P.error)throw new Error((P==null?void 0:P.error)||"Failed to disconnect")},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-integration"]}),ne.success("Canva disconnected")},onError:b=>{ne.error(b.message||"Failed to disconnect Canva")}}),x=mt({mutationFn:async b=>{const{error:w}=await q.from("canva_brokerage_folders").insert({brokerage_id:b.brokerage_id,folder_id:b.folder_id.trim(),folder_name:b.folder_name.trim(),folder_type:b.folder_type,description:b.description.trim()||null,sort_order:(m==null?void 0:m.length)||0});if(w)throw w},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ne.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>ne.error("Failed to add folder")}),v=mt({mutationFn:async b=>{const{error:w}=await q.from("canva_brokerage_folders").delete().eq("id",b);if(w)throw w},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ne.success("Folder removed")},onError:()=>ne.error("Failed to remove folder")}),y=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(je,{children:[e.jsx(St,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-accent flex items-center justify-center",children:e.jsx(tEt,{})}),e.jsxs("div",{children:[e.jsxs(Et,{className:"text-lg flex items-center gap-2",children:["Canva Connect",y&&e.jsx($e,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx($e,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(Vn,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(Le,{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(Wl,{className:"h-4 w-4 mt-0.5 text-primary shrink-0"}),e.jsx("span",{children:"OAuth 2.0 + PKCE for secure authorization"})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Wl,{className:"h-4 w-4 mt-0.5 text-primary shrink-0"}),e.jsx("span",{children:"Map brokerage folders to auto-share with agents on connection"})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Wl,{className:"h-4 w-4 mt-0.5 text-primary shrink-0"}),e.jsx("span",{children:"Multiple folders per brokerage (templates, brand assets, listings)"})]}),e.jsxs("div",{className:"mt-4 p-3 rounded-lg bg-muted border border-dashed",children:[e.jsx("p",{className:"text-xs font-medium text-foreground mb-1",children:"Canva App Redirect URL"}),e.jsx("code",{className:"text-xs text-muted-foreground break-all select-all",children:"https://dashboard.relevelup.com/canva-callback.html"})]}),y?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:d.canva_team_id?`Team: ${d.canva_team_id}`:"Canva Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.expires_at?`Token expires ${new Date(d.expires_at).toLocaleDateString()}`:"Platform integration active"})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Disconnect Canva?"}),e.jsx(ic,{children:"This will remove the Canva platform integration. Agents who have already connected will not be affected, but new folder sharing will stop."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:()=>g.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-center justify-between p-3 text-sm font-medium hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nv,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",m&&m.length>0&&e.jsx($e,{variant:"secondary",className:"text-xs",children:m.length})]}),r?e.jsx(xb,{className:"h-4 w-4"}):e.jsx(wl,{className:"h-4 w-4"})]}),r&&e.jsxs("div",{className:"border-t p-3 space-y-2",children:[m&&m.length>0?m.map(b=>{var w,S;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md bg-muted/50 text-sm",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium truncate",children:b.folder_name}),e.jsx($e,{variant:"outline",className:"text-xs shrink-0",children:((w=sEt.find(A=>A.value===b.folder_type))==null?void 0:w.label)||b.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(S=b.brokerages)==null?void 0:S.name," · ID: ",e.jsx("span",{className:"font-mono",children:b.folder_id})]})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0 ml-2",onClick:()=>v.mutate(b.id),children:e.jsx(mr,{className:"h-3.5 w-3.5"})})]},b.id)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"No folders mapped yet"}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx(cn,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs($,{className:"mt-4",onClick:f,disabled:t||u,children:[t?e.jsx(co,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(tEt,{})}),"Connect Canva",e.jsx(Qa,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{children:"Add Brokerage Folder Mapping"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage"}),e.jsxs(ms,{value:o.brokerage_id,onValueChange:b=>c(w=>({...w,brokerage_id:b})),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a brokerage…"})}),e.jsx(hs,{children:h==null?void 0:h.map(b=>e.jsx(Ge,{value:b.id,children:b.name},b.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Canva Folder ID"}),e.jsx(pe,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:b=>c(w=>({...w,folder_id:b.target.value}))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Found in the Canva folder URL: canva.com/folder/",e.jsx("strong",{children:"FOLDER_ID"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Folder Display Name"}),e.jsx(pe,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:b=>c(w=>({...w,folder_name:b.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Folder Type"}),e.jsxs(ms,{value:o.folder_type,onValueChange:b=>c(w=>({...w,folder_type:b})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:sEt.map(b=>e.jsx(Ge,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ee,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(pe,{placeholder:"What's in this folder?",value:o.description,onChange:b=>c(w=>({...w,description:b.target.value}))})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>x.mutate(o),disabled:!o.brokerage_id||!o.folder_id||!o.folder_name||x.isPending,children:[x.isPending?e.jsx(co,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function Uor(){const s=Zn();return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Dm,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(je,{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(Hd,{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(Qa,{className:"h-4 w-4 ml-1"})]})]}),e.jsx($or,{}),e.jsx(Zis,{})]})})}const nEt=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(Zp,{className:t}):s==="instagram"?e.jsx(Ef,{className:t}):s==="linkedin"?e.jsx(ly,{className:t}):s==="google"?e.jsx(pn,{className:t}):null},qor=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function Vor(){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){ne.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(je,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[nEt(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(je,{children:n?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:c.length===0?e.jsx(An,{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(An,{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:[nEt(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($e,{variant:"destructive",className:"gap-1",children:[e.jsx(vl,{className:"h-3 w-3"})," Expired"]}):e.jsx($e,{children:"Active"}):e.jsx($e,{variant:"secondary",children:"Inactive"})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:qor(m.created_at)})]},m.id)})})]})})]})})}const Hor={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 wX(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function Gor(){var O,U,W,V,G;const s=Zt(),[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,v]=j.useState(null),{data:y,isLoading:b}=st({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:Z,error:X}=await q.from("push_notification_settings").select("*").order("setting_key");if(X)throw X;return Z}}),{data:w,isLoading:S}=st({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:Z,error:X}=await q.from("push_subscriptions").select("*",{count:"exact",head:!0});if(X)throw X;return{totalSubscriptions:Z||0}}}),A=mt({mutationFn:async({settingKey:Z,isEnabled:X})=>{const{error:ae}=await q.from("push_notification_settings").update({is_enabled:X}).eq("setting_key",Z);if(ae)throw ae},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),ne.success("Notification setting updated")},onError:Z=>{ne.error("Failed to update setting: "+Z.message)}}),E=j.useMemo(()=>{var Z,X;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((Z=h.serviceWorker)==null?void 0:Z.activeState)??"unknown"} · sub=${(X=h.subscription)!=null&&X.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);j.useEffect(()=>{let Z=!0;const X=async()=>{var te,J,ce,ve,fe,ue,be;const le="serviceWorker"in navigator&&"PushManager"in window,re={isSupported:le,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((te=navigator.serviceWorker)!=null&&te.controller)};if(!le){Z&&m(re);return}try{const{data:Ee,error:ke}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(ke)throw ke;re.vapidPublicKey=Ee==null?void 0:Ee.vapidPublicKey;const Fe=(await navigator.serviceWorker.getRegistrations()).find(Ne=>{var Se,Ae,Ce;return(((Se=Ne.active)==null?void 0:Se.scriptURL)||((Ae=Ne.waiting)==null?void 0:Ae.scriptURL)||((Ce=Ne.installing)==null?void 0:Ce.scriptURL)||"").includes("/sw.js")});if(Fe){re.pushWorkerScriptUrl=((J=Fe.active)==null?void 0:J.scriptURL)||((ce=Fe.waiting)==null?void 0:ce.scriptURL)||((ve=Fe.installing)==null?void 0:ve.scriptURL),re.serviceWorker={scope:Fe.scope,activeState:(fe=Fe.active)==null?void 0:fe.state};const Ne=await Fe.pushManager.getSubscription();if(Ne){const Be=Ne.toJSON();re.subscription={endpoint:Be.endpoint,p256dh:(ue=Be.keys)==null?void 0:ue.p256dh,auth:(be=Be.keys)==null?void 0:be.auth}}}}catch(Ee){re.error=(Ee==null?void 0:Ee.message)||String(Ee)}Z&&m(re)};X();const ae=window.setInterval(X,4e3);return()=>{Z=!1,window.clearInterval(ae)}},[]);const I=async()=>{if(typeof Notification>"u"){ne.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){ne.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),ne.success("Triggered a local notification (not push).")}catch(Z){ne.error(`Local notification failed: ${(Z==null?void 0:Z.message)||String(Z)}`)}},P=async()=>{c(!0),g(null);try{const{data:Z,error:X}=await q.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(X)throw X;g({sent:Z==null?void 0:Z.sent,failed:Z==null?void 0:Z.failed,expiredCleaned:Z==null?void 0:Z.expiredCleaned,vapidPublicKey:Z==null?void 0:Z.vapidPublicKey}),(Z==null?void 0:Z.sent)>0?ne.success(`Test notification sent to ${Z.sent} subscriber(s)`):(Z==null?void 0:Z.failed)>0?ne.warning(`Notification failed for ${Z.failed} subscriber(s). ${Z.expired||0} expired subscriptions cleaned up.`):ne.info("No active subscriptions to send to")}catch(Z){console.error("Error sending test notification:",Z),g({error:(Z==null?void 0:Z.message)||String(Z)}),ne.error("Failed to send test notification: "+(Z.message||"Unknown error"))}finally{c(!1)}},R=async()=>{u(!0),v(null);try{const{data:Z,error:X}=await q.functions.invoke("generate-vapid-keys",{body:{}});if(X)throw X;const ae=Z==null?void 0:Z.publicKey,le=Z==null?void 0:Z.privateKey;if(!ae||!le)throw new Error("generate-vapid-keys did not return keys");v({publicKey:ae,privateKey:le}),ne.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(Z){console.error("Error generating VAPID keys:",Z),ne.error("Failed to generate VAPID keys: "+((Z==null?void 0:Z.message)||"Unknown error"))}finally{u(!1)}},D=mt({mutationFn:async()=>{const{error:Z}=await q.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(Z)throw Z},onSuccess:()=>{ne.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:Z=>{ne.error("Failed to clear subscriptions: "+Z.message)}});return e.jsx(Vs,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Dm,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(Vn,{children:"Current active push notification subscriptions"})]}),e.jsx(Le,{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(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Nd,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(Vn,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Le,{children:b?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:y==null?void 0:y.map(Z=>{const X=Hor[Z.setting_key]||{label:Z.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:Z.description})]})]}),e.jsx(jn,{checked:Z.is_enabled,onCheckedChange:ae=>A.mutate({settingKey:Z.setting_key,isEnabled:ae}),disabled:A.isPending})]},Z.id)})})})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(zy,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(Vn,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Le,{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?wX(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?wX(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?wX(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(V=h.subscription)!=null&&V.p256dh?wX(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(G=h.subscription)!=null&&G.auth?wX(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:Z=>n(Z.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:Z=>a(Z.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:Z=>l(Z.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(Zr,{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(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(qn,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(Vn,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Le,{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(qn,{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 Wor(){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}=yie("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 v=g.map(A=>A.owner_user_id),{data:y,error:b}=await q.from("profiles").select("id, name, email, avatar_url").in("id",v);if(b)throw b;const w=new Map((y==null?void 0:y.map(A=>[A.id,A]))||[]),S=g.map(A=>{const E=w.get(A.owner_user_id);return{owner_user_id:A.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(A.presentation_count),total_views:Number(A.total_views),total_leads:Number(A.total_leads),total_cta_clicks:Number(A.total_cta_clicks)}});n(S),n(S),a({totalPresentations:S.reduce((A,E)=>A+E.presentation_count,0),totalViews:S.reduce((A,E)=>A+E.total_views,0),totalLeads:S.reduce((A,E)=>A+E.total_leads,0),totalCtaClicks:S.reduce((A,E)=>A+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:Yn,color:"text-blue-600"},{label:"Total Presentations",value:r.totalPresentations,icon:vb,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:Ta,color:"text-emerald-600"},{label:"Total Leads",value:r.totalLeads,icon:lc,color:"text-amber-600"},{label:"CTA Clicks",value:r.totalCtaClicks,icon:Pm,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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:g.label}),e.jsx(g.icon,{className:`h-4 w-4 ${g.color}`})]}),e.jsx(Le,{children:i?e.jsx(xn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:g.value.toLocaleString()})})]},g.label))}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Zl,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Le,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((g,x)=>e.jsx(xn,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Mm,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(Mm,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(Mm,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(Mm,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(Mm,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(Mm,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(fi,{children:h.map(g=>{var v,y;const x=g.total_views>0?(g.total_leads/g.total_views*100).toFixed(1):"0.0";return e.jsxs(An,{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:((y=(v=g.name)==null?void 0:v.charAt(0))==null?void 0:y.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($e,{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 cUe=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—",Kor=s=>s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`;function Yor(){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 v=[],y=1e3;for(let S=0;;S+=y){const{data:A,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+y-1);if(E)throw E;if(v.push(...A??[]),!A||A.lengthS.owner_user_id))),w={};for(let S=0;S{w[E.id]={name:E.name??"Unknown",email:E.email??""}})}l(w)}catch(v){console.error(v),s({title:"Error",description:"Failed to load presentation data",variant:"destructive"})}finally{n(!1)}})()},[s]);const d=j.useMemo(()=>{const x=Date.now(),v=x-7*24*60*60*1e3,y=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()>=v).length,thisMonth:r.filter(b=>new Date(b.created_at).getTime()>=y).length}},[r]),u=j.useMemo(()=>{const x=new Map;return r.forEach(v=>{const y=i[v.owner_user_id],b=x.get(v.owner_user_id)??{user_id:v.owner_user_id,name:(y==null?void 0:y.name)??"Unknown",email:(y==null?void 0:y.email)??"",total:0,generated:0,last_activity:v.updated_at};b.total+=1,v.last_generated_at&&(b.generated+=1),new Date(v.updated_at)>new Date(b.last_activity)&&(b.last_activity=v.updated_at),x.set(v.owner_user_id,b)}),Array.from(x.values()).sort((v,y)=>y.total-v.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 v=i[x.owner_user_id];return(x.title??"").toLowerCase().includes(h)||(x.property_address_line1??"").toLowerCase().includes(h)||(x.city??"").toLowerCase().includes(h)||((v==null?void 0:v.name)??"").toLowerCase().includes(h)||((v==null?void 0:v.email)??"").toLowerCase().includes(h)}):r,g=[{label:"Total presentations",value:d.total,icon:Qr,sub:"All time"},{label:"Agents using it",value:d.agents,icon:Yn,sub:"Created at least one"},{label:"PDFs generated",value:d.generated,icon:wn,sub:"Rendered at least once"},{label:"Created last 30 days",value:d.thisMonth,icon:Su,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(Dm,{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(xn,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:x.label}),e.jsx(x.icon,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Le,{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(pa,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"agents",children:["By agent (",m.length,")"]}),e.jsxs(Xt,{value:"all",children:["All presentations (",f.length,")"]})]}),e.jsx(Qt,{value:"agents",children:e.jsx(je,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:[m.map(x=>e.jsxs(An,{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:cUe(x.last_activity)})]},x.user_id)),!t&&m.length===0&&e.jsx(An,{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(Qt,{value:"all",children:e.jsx(je,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:[f.slice(0,300).map(x=>{var v,y;return e.jsxs(An,{children:[e.jsx(wt,{className:"font-medium",children:x.title||"Untitled"}),e.jsxs(wt,{children:[e.jsx("div",{children:((v=i[x.owner_user_id])==null?void 0:v.name)??"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:((y=i[x.owner_user_id])==null?void 0:y.email)??""})]}),e.jsx(wt,{className:"text-sm",children:[x.property_address_line1,x.city,x.state].filter(Boolean).join(", ")||"—"}),e.jsx(wt,{children:Kor(x.list_price)}),e.jsx(wt,{children:e.jsx($e,{variant:x.last_generated_at?"default":"secondary",children:x.last_generated_at?"Generated":x.status||"Draft"})}),e.jsx(wt,{children:cUe(x.created_at)}),e.jsx(wt,{children:cUe(x.last_generated_at)})]},x.id)}),!t&&f.length===0&&e.jsx(An,{children:e.jsx(wt,{colSpan:7,className:"py-10 text-center text-muted-foreground",children:"No presentations found."})})]})]})})})})]})]})})}const ute="listing_revival";function Zor(){const{user:s,loading:t,isAdmin:n}=_s(),{data:r}=st({queryKey:["feature-entitlement",ute,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",ute).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 Xor=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—";function Qor(){var u,h;const{user:s}=_s(),t=Zt(),[n,r]=j.useState(""),a=st({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=st({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:v}=await q.from("feature_entitlements").select("user_id, enabled, tier").eq("feature_key",ute).in("user_id",x.length?x:["00000000-0000-0000-0000-000000000000"]),y=new Map((v??[]).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=y.get(b.id))!=null&&w.enabled)}})}}),l=mt({mutationFn:async({userId:m,enabled:f})=>{const{error:g}=await q.from("feature_entitlements").upsert({user_id:m,feature_key:ute,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:ute,target_user_id:m,action:f?"grant":"revoke",performed_by:s.id})},onSuccess:(m,f)=>{t.invalidateQueries({queryKey:["lr-admin-members"]}),ne.success(f.enabled?"Access granted":"Access revoked")},onError:m=>ne.error(m.message)}),o=st({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:Yn},{label:"Campaigns built",value:c.campaigns,icon:wn},{label:"Seller leads",value:c.leads,icon:By},{label:"Hot leads",value:c.hot,icon:sh}];return e.jsxs(Vs,{title:"Listing Revival Admin",children:[e.jsx(Dm,{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(je,{children:e.jsxs(Le,{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(pa,{defaultValue:"usage",className:"mt-6",children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"usage",children:"Agent usage"}),e.jsx(Xt,{value:"access",children:"Access"})]}),e.jsx(Qt,{value:"usage",className:"mt-4",children:e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Usage by agent"})}),e.jsx(Le,{children:a.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(xn,{className:"h-10 w-full"},m))}):(h=a.data)!=null&&h.length?e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{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(An,{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($e,{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:Xor(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(Qt,{value:"access",className:"mt-4",children:e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Who can use Listing Revival"})}),e.jsxs(Le,{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(xn,{className:"h-10 w-full"},m))}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{className:"text-right",children:"Access"})]})}),e.jsx(fi,{children:(i.data??[]).map(m=>e.jsxs(An,{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(jn,{checked:m.enabled,onCheckedChange:f=>l.mutate({userId:m.user_id,enabled:f})})})]},m.user_id))})]})]})]})})]})]})}function Jor(){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(v=>v.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(v=>[v.id,v]))||[]),x=d.map(v=>{const y=g.get(v.agent_id);return{agent_id:v.agent_id,name:(y==null?void 0:y.name)||"Unknown",email:(y==null?void 0:y.email)||"",avatar_url:(y==null?void 0:y.avatar_url)||null,open_house_count:Number(v.open_house_count),total_visitors:Number(v.total_visitors),total_leads:Number(v.total_leads),active_count:Number(v.active_count)}});x.sort((v,y)=>y.total_visitors-v.total_visitors),n(x),a({totalOpenHouses:x.reduce((v,y)=>v+y.open_house_count,0),totalVisitors:x.reduce((v,y)=>v+y.total_visitors,0),totalLeads:x.reduce((v,y)=>v+y.total_leads,0),activeOpenHouses:x.reduce((v,y)=>v+y.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:Yn,color:"text-blue-600"},{label:"Total Open Houses",value:r.totalOpenHouses,icon:va,color:"text-violet-600"},{label:"Active Now",value:r.activeOpenHouses,icon:Wl,color:"text-emerald-600"},{label:"Total Visitors",value:r.totalVisitors,icon:Ta,color:"text-amber-600"},{label:"Leads Created",value:r.totalLeads,icon:lc,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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Et,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(Le,{children:i?e.jsx(xn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Zl,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Le,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,u)=>e.jsx(xn,{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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{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(An,{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($e,{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($e,{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 elr(){const[s]=Nc(),t=Zn(),[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"),ne.error("Failed to connect: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),ne.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 v=await x.json();v!=null&&v.error&&(g=v.error)}}catch{}throw new Error(g)}if(m!=null&&m.success)r("success"),l(m.message||"Accounts connected successfully!"),ne.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"),ne.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(je,{className:"w-full max-w-md",children:[e.jsxs(St,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[n==="loading"&&e.jsx(Ct,{className:"h-12 w-12 animate-spin text-primary"}),n==="success"&&e.jsx(Wl,{className:"h-12 w-12 text-green-500"}),n==="error"&&e.jsx(ju,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(Et,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:i})]}),e.jsx(Le,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function tlr(){const s=Zt(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState([]),o=j.useRef(null),{data:c,isLoading:d}=st({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=mt({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"]}),ne.success(`${b.sent} email${b.sent>1?"s":""} sent successfully!`),n(""),a(""),l([])},onError:b=>{ne.error("Failed to send: "+b.message)}}),f=mt({mutationFn:async()=>{var A,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=(A=b.user_metadata)==null?void 0:A.name)==null?void 0:E.split(" ")[0]}],test_mode:!0}});if(S)throw S;return w},onSuccess:()=>{ne.success("Test email sent to your inbox!")},onError:b=>{ne.error("Failed to send test: "+b.message)}}),g=mt({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"]}),ne.success(`${b.sent} live lead invite${b.sent===1?"":"s"} sent!`)},onError:b=>{ne.error("Failed to send live lead invites: "+b.message)}}),x=()=>{if(!t.trim()){ne.error("Please enter an email address");return}if(c==null?void 0:c.find(w=>w.email.toLowerCase()===t.trim().toLowerCase())){ne.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:r.trim()||void 0}])},v=b=>{var A;const w=(A=b.target.files)==null?void 0:A[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],Z=V[1];G&&G.includes("@")&&R.push({email:G,first_name:Z||void 0})}l(R),ne.success(`${R.length} entries loaded from CSV`)},S.readAsText(w),o.current&&(o.current.value="")},y=()=>{if(i.length===0){ne.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){ne.error("All emails have already been prospected");return}w.length0&&e.jsxs(je,{className:"border-red-200/50 bg-red-500/[0.02]",children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(bb,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx($e,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(Vn,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(Le,{children:e.jsxs($,{onClick:()=>g.mutate(),disabled:g.isPending,className:"gap-2",children:[g.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),"Send free trial invite to all live leads"]})})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(ph,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(Vn,{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(Ct,{className:"h-3 w-3 animate-spin"}):e.jsx(pn,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Le,{children:e.jsxs(pa,{defaultValue:"single",children:[e.jsxs(ga,{className:"mb-4",children:[e.jsxs(Xt,{value:"single",children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(Xt,{value:"bulk",children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(Qt,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(Qt,{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:v,className:"hidden"}),e.jsxs($,{variant:"outline",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},className:"gap-2",children:[e.jsx(Qr,{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($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Yn,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(mr,{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:y,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(Vn,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Le,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((b,w)=>e.jsx(xn,{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:Js(new Date(b.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:b.status==="converted"?e.jsxs($e,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(Vr,{className:"h-3 w-3 mr-1"}),"Converted"]}):b.status==="live_lead"?e.jsxs($e,{className:"bg-red-500/10 text-red-700 hover:bg-red-500/20 border-0 gap-1",children:[e.jsx(bb,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(ca,{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($e,{variant:"outline",className:"gap-1 font-normal",children:[e.jsx(Qr,{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?Js(new Date(b.converted_at),"MMM d, yyyy"):"—"})]},b.id)})})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ph,{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 v9(s){const t=Zt(),{toast:n}=Bi(),r=st({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=st({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=mt({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=mt({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=mt({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 slr(s){const t=Zt(),{toast:n}=Bi(),r=st({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=mt({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 rEt=(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 Tlt({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=j.useState(rEt(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(rEt(r,n)),t(!1)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(pa,{defaultValue:"basic",className:"w-full",children:[e.jsxs(ga,{className:"grid w-full grid-cols-4",children:[e.jsx(Xt,{value:"basic",children:"Basic Info"}),e.jsx(Xt,{value:"production",children:"Production"}),e.jsx(Xt,{value:"social",children:"Social & Web"}),e.jsx(Xt,{value:"personal",children:"Personal"})]}),e.jsxs(Qt,{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(Qt,{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(Qt,{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(Qt,{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 oFe(){const{user:s}=_s();return st({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 Mlt({value:s,onChange:t}){const{data:n,isLoading:r}=oFe();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(wi,{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(zz,{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(pn,{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 nos({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,v]=j.useState(!1),y=Zt(),{data:b}=oFe();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,A;if(!i){ne.error("This prospect has no email address on file.");return}v(!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)ne.success(`Email sent to ${i}`),y.invalidateQueries({queryKey:["recruit-videos"]}),y.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const R=((A=(S=E==null?void 0:E.results)==null?void 0:S[0])==null?void 0:A.error)||"Failed to send";ne.error(R)}}catch(E){ne.error((E==null?void 0:E.message)||"Failed to send email")}finally{v(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{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(Mlt,{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(Nr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),disabled:x,children:"Cancel"}),e.jsxs($,{onClick:w,disabled:x||!i,children:[x?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function b4(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const QXe=[{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 nlr(s){return st({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 rlr(s){return st({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 ros(){const s=Zt(),{toast:t}=Bi();return mt({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=Zt();return mt({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 ios(s){return st({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 alr(){const s=Zt(),{toast:t}=Bi();return mt({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 ilr(){const s=Zt();return mt({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 olr({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var G;const{data:a=[],isLoading:i}=rlr(s),{data:l=[]}=ios(r),o=ros(),c=f3();aos();const[d,u]=j.useState("idle"),[h,m]=j.useState(0),[f,g]=j.useState(0),[x,v]=j.useState(""),[y,b]=j.useState(""),[w,S]=j.useState(!1),[A,E]=j.useState(null),[I,P]=j.useState(null),[R,D]=j.useState(null),O=((G=l.find(Z=>Z.id===x))==null?void 0:G.script_text)||"",U=()=>{u("idle"),m(0),g(0),v(""),b("")},W=j.useCallback(async(Z,X)=>{u("uploading");try{const ae=`Recruiting: ${t}`,{videoId:le,libraryId:re}=await k6(ae),{uploadUrl:te,apiKey:J}=await S6(le),ce=new XMLHttpRequest;ce.upload.onprogress=Fe=>{Fe.lengthComputable&&m(Fe.loaded/Fe.total*100)},await new Promise((Fe,Ne)=>{ce.onload=()=>ce.status>=200&&ce.status<300?Fe():Ne(new Error("Upload failed")),ce.onerror=()=>Ne(new Error("Upload failed")),ce.open("PUT",te),ce.setRequestHeader("AccessKey",J),ce.send(Z)}),u("processing");let ve=0;const fe=Date.now(),ue=9e4,be=`https://iframe.mediadelivery.net/embed/${re}/${le}`;for(;ve<4&&(await new Promise(Ne=>setTimeout(Ne,3e3)),!(Date.now()-fe>ue));){const Fe=await hk(le);if(ve=Fe.status,g(Fe.encodeProgress||0),ve===5||ve===6)throw new Error("Video processing failed")}const Ee=await hk(le),ke=(Ee.storageSize||Z.size)/(1024*1024),Ie=await c.mutateAsync({bunny_video_id:le,playback_url:Ee.directPlayUrl||be,thumbnail_url:Ee.thumbnailUrl,preview_url:Ee.previewUrl||null,duration_seconds:Ee.length||X,file_size_mb:ke,title:ae,status:ve>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Ie.id,brokerage_id:r,message:y||void 0}),u("done"),ne.success("Video recorded and linked to prospect!"),setTimeout(()=>{S(!1),U()},1500)}catch(ae){ne.error(ae.message||"Failed to upload video"),u("record")}},[s,t,r,y,c,o]),V=Z=>{Z&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${Z}`),ne.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(fa,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(Os,{open:w,onOpenChange:Z=>{!Z&&(d==="uploading"||d==="processing")||(S(Z),Z||U())},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs($s,{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:v,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(Z=>{var X;return e.jsx(Ge,{value:Z.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[Z.title,e.jsx($e,{variant:"outline",className:"text-[9px] ml-1",children:(X=QXe.find(ae=>ae.value===Z.category))==null?void 0:X.label})]})},Z.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:y,onChange:Z=>b(Z.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(fa,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(DT,{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(Ou,{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(Z=>{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:b4(Z.video)?e.jsx("img",{src:b4(Z.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(fa,{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=Z.video)==null?void 0:X.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[Z.view_count>0?e.jsxs($e,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(Ta,{className:"h-2.5 w-2.5 mr-0.5"}),Z.view_count]}):Z.sent_at?e.jsxs($e,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Zr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs($e,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(ca,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Js(new Date(Z.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(Z.share_token),title:"Copy link",children:e.jsx(Za,{className:"h-3 w-3"})}),e.jsxs($,{variant:Z.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var ae;E(Z.id),P(((ae=Z.video)==null?void 0:ae.title)||null),D(Z.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(pn,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:Z.sent_at?"Resend":"Email"})]})]})]},Z.id)})}),A&&e.jsx(nos,{open:!!A,onOpenChange:Z=>{Z||E(null)},recruitVideoId:A,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:I,defaultMessage:R})]})}function llr({brokerageId:s,onSelect:t}){const{data:n=[],isLoading:r}=st({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(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(Qr,{className:"h-4 w-4"}),"Use Template",e.jsx(wl,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(Cu,{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(Ct,{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(P0,{}),e.jsx(_L,{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($e,{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 clr({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=_s(),o=(a||"").split(" ")[0]||"there",[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState("default"),[g,x]=j.useState(!1),[v,y]=j.useState(null),[b,w]=j.useState(!1),S=Zt(),{data:A}=oFe();j.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const O=A!=null&&A.massEmail?"mass_email":A!=null&&A.gmail?"gmail":"default";f(O),y(null),w(!1)}},[s,o,A==null?void 0:A.massEmail,A==null?void 0:A.gmail]);const{data:E=[],isLoading:I}=st({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===v)||null,R=async()=>{var O,U;if(!i){ne.error("This prospect has no email address on file.");return}if(!c.trim()||!u.trim()){ne.error("Subject and message are required.");return}x(!0);try{if(v){const{data:W}=await q.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",v).maybeSingle();let V=W==null?void 0:W.id;if(!V){const{data:ae,error:le}=await q.from("recruit_videos").insert({prospect_id:n,video_id:v,brokerage_id:r,message:u.trim(),created_by:l.id}).select("id").single();if(le)throw le;V=ae.id}const{data:G,error:Z}=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(Z)throw Z;if(((G==null?void 0:G.sent)??0)>0)ne.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";ne.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?(ne.success(`Email sent to ${i}`),S.invalidateQueries({queryKey:["recruit-activities",n]}),S.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):ne.error((W==null?void 0:W.error)||"Failed to send")}}catch(W){ne.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)),ne.success(`Loaded "${O.title}"`)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{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(Mlt,{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(llr,{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(fa,{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:()=>{y(null),w(!1)},children:[e.jsx(mr,{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:b4(P)?e.jsx("img",{src:b4(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(fa,{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(Ct,{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:()=>{y(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:b4(O)?e.jsx("img",{src:b4(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(fa,{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(Nr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsxs($,{onClick:R,disabled:g||!i,children:[g?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function dlr(s){return st({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 aEt=[{value:"call",label:"Phone Call",icon:Da},{value:"email",label:"Email",icon:pn},{value:"text",label:"Text Message",icon:no},{value:"meeting",label:"Meeting",icon:Ea},{value:"note",label:"Note",icon:Qr},{value:"campaign_email",label:"Campaign Email",icon:Zr}];function bj({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 Que({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(Ir,{className:"h-3 w-3 opacity-50"})]}):null}function gp({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 Plt({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=slr((s==null?void 0:s.id)||null),{data:d=[]}=dlr((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),[v,y]=j.useState({}),[b,w]=j.useState(!1);if(!s)return null;const S=()=>{var V,G;y({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)},A=()=>{const V={id:s.id};for(const[G,Z]of Object.entries(v))G==="experience_years"||G==="last_year_transactions"?V[G]=Z?parseInt(Z):null:V[G]=Z||null;i(V),x(!1)},E=()=>x(!1),I=V=>G=>y(Z=>({...Z,[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(Vy,{open:r,onOpenChange:V=>{V||x(!1),a(V)},children:[e.jsx(uy,{className:"w-full sm:max-w-lg p-0",children:e.jsx(go,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(I0,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(L0,{className:"text-xl",children:[s.first_name," ",s.last_name]}),R&&e.jsx($e,{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(mr,{className:"h-4 w-4"})}),e.jsx($,{variant:"default",size:"icon",onClick:A,children:e.jsx(tl,{className:"h-4 w-4"})})]}):e.jsx($,{variant:"ghost",size:"icon",onClick:S,title:"Edit prospect",children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Delete prospect?"}),e.jsx(ic,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{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(pn,{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(pn,{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(ui,{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(pa,{defaultValue:"details",className:"w-full",children:[e.jsxs(ga,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(Xt,{value:"details",className:"text-xs",children:"Details"}),e.jsx(Xt,{value:"production",className:"text-xs",children:"Production"}),e.jsx(Xt,{value:"social",className:"text-xs",children:"Social"}),e.jsx(Xt,{value:"personal",className:"text-xs",children:"Personal"})]}),g?e.jsxs(e.Fragment,{children:[e.jsxs(Qt,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(gp,{label:"First Name",value:v.first_name,onChange:I("first_name")}),e.jsx(gp,{label:"Last Name",value:v.last_name,onChange:I("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(gp,{label:"Email",value:v.email,onChange:I("email"),type:"email"}),e.jsx(gp,{label:"Phone",value:v.phone,onChange:I("phone")})]}),e.jsx(gp,{label:"Current Brokerage",value:v.current_brokerage,onChange:I("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(gp,{label:"License #",value:v.license_number,onChange:I("license_number")}),e.jsx(gp,{label:"Experience (years)",value:v.experience_years,onChange:I("experience_years"),type:"number"})]}),e.jsx(gp,{label:"Address",value:v.address,onChange:I("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(gp,{label:"City",value:v.city,onChange:I("city")}),e.jsx(gp,{label:"State",value:v.state,onChange:I("state")}),e.jsx(gp,{label:"Zip",value:v.zip_code,onChange:I("zip_code")})]}),e.jsx(gp,{label:"Source",value:v.source,onChange:I("source")}),e.jsx(gp,{label:"Referred By",value:v.referred_by,onChange:I("referred_by")}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Notes"}),e.jsx(Rs,{value:v.notes,onChange:V=>y(G=>({...G,notes:V.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(Qt,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(gp,{label:"Annual Production",value:v.annual_production,onChange:I("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(gp,{label:"Last Year Volume",value:v.last_year_volume,onChange:I("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(gp,{label:"Last Year Transactions",value:v.last_year_transactions,onChange:I("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(gp,{label:"Avg Sale Price",value:v.avg_sale_price,onChange:I("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(gp,{label:"Specialties / Niche",value:v.specialties,onChange:I("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(Qt,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(gp,{label:"LinkedIn URL",value:v.linkedin_url,onChange:I("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(gp,{label:"Website URL",value:v.website_url,onChange:I("website_url"),type:"url",placeholder:"https://..."}),e.jsx(gp,{label:"Instagram Handle",value:v.instagram_handle,onChange:I("instagram_handle"),placeholder:"@handle"}),e.jsx(gp,{label:"Facebook URL",value:v.facebook_url,onChange:I("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(Qt,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(gp,{label:"Birthday",value:v.birthday,onChange:I("birthday"),type:"date"}),e.jsx(gp,{label:"Spouse / Partner",value:v.spouse_name,onChange:I("spouse_name")}),e.jsx(gp,{label:"Interests / Hobbies",value:v.interests,onChange:I("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Qt,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(bj,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(bj,{label:"License #",value:s.license_number}),e.jsx(bj,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(bj,{label:"Referred By",value:s.referred_by}),e.jsx(bj,{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(Qt,{value:"production",className:"mt-3",children:O?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(bj,{label:"Annual Production",value:s.annual_production}),e.jsx(bj,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(bj,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(bj,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(bj,{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(Qt,{value:"social",className:"mt-3",children:U?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Que,{label:"LinkedIn",url:s.linkedin_url,icon:ly}),e.jsx(Que,{label:"Website",url:s.website_url,icon:cl}),s.instagram_handle&&e.jsx(Que,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:Ef}),e.jsx(Que,{label:"Facebook",url:s.facebook_url,icon:Zp})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(Qt,{value:"personal",className:"mt-3",children:W?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(bj,{label:"Birthday",value:s.birthday?Js(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:dl}),e.jsx(bj,{label:"Spouse / Partner",value:s.spouse_name,icon:Jo}),e.jsx("div",{className:"col-span-2",children:e.jsx(bj,{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(olr,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:n}),e.jsx(Vc,{}),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(cn,{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:aEt.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,Z)=>new Date(Z.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=aEt.find(re=>re.value===X.activity_type),le=(ae==null?void 0:ae.icon)||Qr;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center",children:e.jsx(le,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children: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:Js(new Date(X.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${X.id}`)}const Z=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(Zr,{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 #",Z.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:Z.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[Z.status==="failed"?e.jsx($e,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs($e,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(Zr,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),Z.opened_at?e.jsxs($e,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(Ta,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",Js(new Date(Z.opened_at),"MMM d, h:mm a")]}):Z.status!=="failed"?e.jsx($e,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,Z.clicked_at&&e.jsxs($e,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(lb,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",Js(new Date(Z.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Js(new Date(Z.sent_at||Z.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${Z.id}`)})})()})]})]})})}),e.jsx(clr,{open:b,onOpenChange:w,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const ulr=["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 Ilt({open:s,onOpenChange:t,brokerageId:n,stages:r}){var D;const{toast:a}=Bi(),i=Zt(),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,v]=j.useState(!1),[y,b]=j.useState("upload"),[w,S]=j.useState(0),A=()=>{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 le={},re=new Set;ae.forEach((ce,ve)=>{const fe=ce.toLowerCase().replace(/[^a-z0-9]/g,"");let ue=null;/^firstname$/.test(fe)||fe==="first"?ue="first_name":/^lastname$/.test(fe)||fe==="last"?ue="last_name":/^email$/.test(fe)||fe==="emailaddress"?ue="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(fe)?ue="phone":/officename|currentbrokerage|brokerage|company/.test(fe)?ue="current_brokerage":/membernumber|licensenumber|license/.test(fe)?ue="license_number":/experienceyears|yearsexperience/.test(fe)?ue="experience_years":/^totalvolume$|annualproduction/.test(fe)?ue="annual_production":/^address$/.test(fe)?ue="address":/^city$/.test(fe)?ue="city":/^state$/.test(fe)?ue="state":/^postalcode$|^zip$|^zipcode$/.test(fe)?ue="zip_code":/listsidevolume|lastyearvolume/.test(fe)?ue="last_year_volume":/^totalcount$|lastyeartransactions/.test(fe)?ue="last_year_transactions":/avgsaleprice|averageprice/.test(fe)?ue="avg_sale_price":/linkedin/.test(fe)?ue="linkedin_url":/website/.test(fe)?ue="website_url":/specialt/.test(fe)?ue="specialties":/referr/.test(fe)?ue="referred_by":/^notes$|^note$/.test(fe)&&(ue="notes"),ue&&!re.has(ue)&&(le[String(ve)]=ue,re.add(ue))}),m(le);const te=X.slice(1).map(ce=>{const ve=I(ce),fe={};return ae.forEach((ue,be)=>{fe[String(be)]=ve[be]||""}),fe});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()=>{v(!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"},Z=G;return Object.entries(h).forEach(([X,ae])=>{var re;const le=(re=V[X])==null?void 0:re.trim();le&&(ae==="experience_years"||ae==="last_year_transactions"?Z[ae]=parseInt(le.replace(/[^0-9.-]/g,""))||null:ae==="annual_production"||ae==="last_year_volume"||ae==="avg_sale_price"?Z[ae]=le.replace(/[^0-9.$,.-]/g,""):Z[ae]=le)}),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(Os,{open:s,onOpenChange:O=>{O||A(),t(O)},children:e.jsxs(Fs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx($s,{children:"Import Prospects from CSV"})}),y==="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(KN,{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"})]}),y==="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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fi,{children:d.map((O,U)=>{var W;return e.jsxs(An,{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 —"}),ulr.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(vl,{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:()=>{A()},children:"Back"}),e.jsx($,{onClick:P,disabled:x||!Object.values(h).includes("first_name"),children:x?"Importing...":`Import ${o.length} Prospects`})]})]}),y==="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(ma,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[w," prospects imported successfully!"]}),e.jsx($,{onClick:()=>{A(),t(!1)},children:"Close"})]})]})})}function oos({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=v9(s),[o,c]=j.useState(!1),[d,u]=j.useState(),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,v]=j.useState(!1),[y,b]=j.useState(null),[w,S]=j.useState(""),[A,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 Z=w.trim().toLowerCase();return(!Z||`${G.first_name} ${G.last_name||""} ${G.current_brokerage||""} ${G.email||""}`.toLowerCase().includes(Z))&&(A==="all"||G.source===A)}),R=G=>P.filter(Z=>Z.stage_id===G),D=(G,Z)=>{b(Z),G.dataTransfer.effectAllowed="move"},O=G=>{G.preventDefault(),G.dataTransfer.dropEffect="move"},U=(G,Z)=>{G.preventDefault(),y&&(i.mutate({id:y,stage_id:Z}),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:A,onValueChange:E,children:[e.jsxs(us,{className:"h-9 w-full sm:w-[190px]",children:[e.jsx(Sw,{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:()=>v(!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(cn,{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||A!=="all")&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{S(""),E("all")},children:"Clear filters"})]}),e.jsxs(go,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(G=>{const Z=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($e,{variant:"secondary",className:"text-xs h-5 px-1.5",children:Z.length})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>W(G.id),children:e.jsx(cn,{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:Z.map(X=>e.jsx(je,{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(zg,{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($e,{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(wi,{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(pn,{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($e,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[X.experience_years,"yr"]})]})]})]})},X.id))})]},G.id)})}),e.jsx(Iae,{orientation:"horizontal"})]}),e.jsx(Tlt,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:G=>a.mutate(G),isSubmitting:a.isPending}),e.jsx(Plt,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:g,onUpdate:G=>{i.mutate(G),m(Z=>Z?{...Z,...G}:null)},onDelete:G=>l.mutate(G)}),e.jsx(Ilt,{open:x,onOpenChange:v,brokerageId:s,stages:t})]})}function JXe({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=v9(s),{user:o}=_s(),c=Zt(),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,v]=j.useState(!1),[y,b]=j.useState(""),[w,S]=j.useState("all"),[A,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,Z]=j.useState(!1),[X,ae]=j.useState(""),le=j.useMemo(()=>{const Ne=new Set;return n.forEach(Be=>{Be.current_brokerage&&Ne.add(Be.current_brokerage)}),Array.from(Ne).sort()},[n]),{data:re=[]}=st({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:Ne,error:Be}=await q.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(Be)throw Be;return Ne}}),{data:te=[]}=st({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Be=[],Se=0;for(;;){const{data:Ae,error:Ce}=await q.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(Se,Se+1e3-1);if(Ce)throw Ce;if(Be=Be.concat(Ae??[]),!Ae||Ae.length<1e3)break;Se+=1e3}return Be}}),J=j.useMemo(()=>{const Ne=new Map;return te.forEach(Be=>{Ne.has(Be.prospect_id)||Ne.set(Be.prospect_id,new Set),Ne.get(Be.prospect_id).add(Be.campaign_id)}),Ne},[te]),ce=Ne=>{R===Ne?U(Be=>Be==="asc"?"desc":"asc"):(D(Ne),U("asc"))},ve=({column:Ne})=>R!==Ne?e.jsx(Dy,{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(Lg,{className:"h-3.5 w-3.5 ml-1 text-primary"}),fe=Ne=>t.find(Be=>Be.id===Ne),ue=j.useMemo(()=>{let Ne=n.filter(Be=>{var ze,Ve,ht;const Se=!y||`${Be.first_name} ${Be.last_name}`.toLowerCase().includes(y.toLowerCase())||((ze=Be.email)==null?void 0:ze.toLowerCase().includes(y.toLowerCase()))||((Ve=Be.current_brokerage)==null?void 0:Ve.toLowerCase().includes(y.toLowerCase())),Ae=w==="all"||Be.stage_id===w,Ce=A==="all"||Be.current_brokerage===A;let qe=!0;return I==="in_campaign"?qe=J.has(Be.id):I==="not_in_campaign"?qe=!J.has(Be.id):I!=="all"&&(qe=((ht=J.get(Be.id))==null?void 0:ht.has(I))??!1),Se&&Ae&&Ce&&qe});return R&&(Ne=[...Ne].sort((Be,Se)=>{var ze,Ve;let Ae=null,Ce=null;switch(R){case"name":Ae=`${Be.first_name} ${Be.last_name||""}`.toLowerCase(),Ce=`${Se.first_name} ${Se.last_name||""}`.toLowerCase();break;case"stage":Ae=((ze=fe(Be.stage_id))==null?void 0:ze.sort_order)??999,Ce=((Ve=fe(Se.stage_id))==null?void 0:Ve.sort_order)??999;break;case"brokerage":Ae=(Be.current_brokerage||"").toLowerCase(),Ce=(Se.current_brokerage||"").toLowerCase();break;case"experience":Ae=Be.experience_years??-1,Ce=Se.experience_years??-1;break;case"production":Ae=(Be.annual_production||"").toLowerCase(),Ce=(Se.annual_production||"").toLowerCase();break;case"source":Ae=(Be.source||"").toLowerCase(),Ce=(Se.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(Ne=>W.has(Ne.id)),Ee=ue.some(Ne=>W.has(Ne.id)),ke=()=>{V(be?new Set:new Set(ue.map(Ne=>Ne.id)))},Ie=Ne=>{V(Be=>{const Se=new Set(Be);return Se.has(Ne)?Se.delete(Ne):Se.add(Ne),Se})},Fe=mt({mutationFn:async()=>{if(!X||!(o!=null&&o.id))throw new Error("Select a campaign");const Ne=new Set(te.filter(Ae=>Ae.campaign_id===X).map(Ae=>Ae.prospect_id)),Be=Array.from(W).filter(Ae=>!Ne.has(Ae)).map(Ae=>({prospect_id:Ae,campaign_id:X,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Be.length===0)throw new Error("All selected prospects are already in this campaign");const{error:Se}=await q.from("recruit_campaign_assignments").insert(Be);if(Se)throw Se;return Be.length},onSuccess:Ne=>{ne.success(`${Ne} prospect(s) added to campaign`),Z(!1),V(new Set),ae(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:Ne=>ne.error(Ne.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:y,onChange:Ne=>b(Ne.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[W.size>0&&e.jsxs($,{variant:"secondary",onClick:()=>Z(!0),className:"gap-1.5",children:[e.jsx(Zr,{className:"h-4 w-4"})," Add ",W.size," to Campaign"]}),e.jsxs($,{variant:"outline",onClick:()=>v(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs($,{onClick:()=>u(!0),children:[e.jsx(cn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Sw,{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(Ne=>e.jsx(Ge,{value:Ne.id,children:Ne.name},Ne.id))]})]}),e.jsxs(ms,{value:A,onValueChange:E,children:[e.jsxs(us,{className:"w-[200px] h-8 text-xs",children:[e.jsx(wi,{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"}),le.map(Ne=>e.jsx(Ge,{value:Ne,children:Ne},Ne))]})]}),e.jsxs(ms,{value:I,onValueChange:P,children:[e.jsxs(us,{className:"w-[200px] h-8 text-xs",children:[e.jsx(pn,{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"}),re.map(Ne=>e.jsxs(Ge,{value:Ne.id,children:["In: ",Ne.name]},Ne.id))]})]}),(w!=="all"||A!=="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(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(ai,{checked:be,onCheckedChange:ke,"aria-label":"Select all",...Ee&&!be?{"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(ve,{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(ve,{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(ve,{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(ve,{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(ve,{column:"production"})]})}),e.jsx(Dt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Dt,{className:"w-[50px]"})]})}),e.jsx(fi,{children:ue.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):ue.map(Ne=>{const Be=fe(Ne.stage_id),Se=J.get(Ne.id),Ae=(Se==null?void 0:Se.size)??0;return e.jsxs(An,{className:"cursor-pointer",onClick:()=>{m(Ne),g(!0)},children:[e.jsx(wt,{onClick:Ce=>Ce.stopPropagation(),children:e.jsx(ai,{checked:W.has(Ne.id),onCheckedChange:()=>Ie(Ne.id),"aria-label":`Select ${Ne.first_name}`})}),e.jsxs(wt,{className:"font-medium",children:[Ne.first_name," ",Ne.last_name]}),e.jsx(wt,{children:Be?e.jsxs($e,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:Be.color,color:Be.color,backgroundColor:`${Be.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:Be.color}}),Be.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(wt,{className:"hidden md:table-cell",children:Ne.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(wi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:Ne.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:[Ne.email&&e.jsx(pn,{className:"h-3.5 w-3.5 text-muted-foreground"}),Ne.phone&&e.jsx(Da,{className:"h-3.5 w-3.5 text-muted-foreground"}),!Ne.email&&!Ne.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(wt,{className:"hidden lg:table-cell",children:Ne.experience_years!=null?`${Ne.experience_years} yr`:"—"}),e.jsx(wt,{className:"hidden lg:table-cell",children:Ne.annual_production||"—"}),e.jsx(wt,{className:"hidden lg:table-cell",children:Ae>0?e.jsxs($e,{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(Ne.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})})})]},Ne.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(Os,{open:G,onOpenChange:Z,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx($s,{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:re.map(Ne=>e.jsxs(Ge,{value:Ne.id,children:[Ne.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",Ne.warmth_level,")"]})]},Ne.id))})]})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>Z(!1),children:"Cancel"}),e.jsx($,{onClick:()=>Fe.mutate(),disabled:!X||Fe.isPending,children:Fe.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(Tlt,{open:d,onOpenChange:u,stages:t,onSubmit:Ne=>a.mutate(Ne),isSubmitting:a.isPending}),e.jsx(Plt,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:g,onUpdate:Ne=>{i.mutate(Ne),m(Be=>Be?{...Be,...Ne}:null)},onDelete:Ne=>l.mutate(Ne)}),e.jsx(Ilt,{open:x,onOpenChange:v,brokerageId:s,stages:t})]})}function los({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=v9(s),a=j.useMemo(()=>{if(!t.length||!n.length)return null;const i=n.length,l=t.find(y=>y.name==="Signed"),o=t.find(y=>y.name==="Onboarded"),c=n.filter(y=>y.stage_id===(l==null?void 0:l.id)||y.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((y,b)=>y+ck(u,new Date(b.created_at)),0)/i):0,m=t.map(y=>({...y,count:n.filter(b=>b.stage_id===y.id).length})),f={};n.forEach(y=>{const b=y.source||"unknown";f[b]=(f[b]||0)+1});const g=Object.entries(f).sort((y,b)=>b[1]-y[1]),x=new Date;x.setDate(x.getDate()-30);const v=n.filter(y=>new Date(y.created_at)>=x).length;return{total:i,signed:c,conversionRate:d,avgDays:h,byStage:m,bySrc:g,recentCount:v}},[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(je,{children:e.jsx(Le,{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(Yn,{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(je,{children:e.jsx(Le,{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(Zl,{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(je,{children:e.jsx(Le,{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(ca,{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(je,{children:e.jsx(Le,{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(ph,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(Le,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Le,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx($e,{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 hlr=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function cos({brokerageId:s}){const{toast:t}=Bi(),{user:n}=_s(),r=Zt(),[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),{data:m=[],isLoading:f}=st({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:S,error:A}=await q.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(A)throw A;return S}}),g=mt({mutationFn:async S=>{if(S.id){const{error:A}=await q.from("recruit_email_templates").update({category:S.category,title:S.title,subject:S.subject,body:S.body}).eq("id",S.id);if(A)throw A}else{const{error:A}=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(A)throw A}},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=mt({mutationFn:async S=>{const{error:A}=await q.from("recruit_email_templates").delete().eq("id",S);if(A)throw A},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"})}),v=(S,A)=>{navigator.clipboard.writeText(S),i(A),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},y=()=>{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:y,size:"sm",className:"gap-1.5",children:[e.jsx(cn,{className:"h-4 w-4"})," New Template"]})]}),f?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ct,{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(pn,{className:"h-4 w-4"})," ",S]}),m.filter(A=>A.category===S).map(A=>{const E=A.brokerage_id!==null;return e.jsxs(je,{className:`transition-all ${l===A.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(St,{className:"pb-2 cursor-pointer",onClick:()=>o(l===A.id?null:A.id),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(Et,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:A.title}),!E&&e.jsx($e,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),E&&e.jsx($e,{className:"text-[10px] shrink-0",children:"Custom"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:["Subject: ",A.subject]})]}),e.jsx($e,{variant:"outline",className:"text-[10px] shrink-0",children:A.category})]})}),l===A.id&&e.jsxs(Le,{className:"pt-0 space-y-3",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subject Line:"}),e.jsx("p",{className:"text-sm mb-3",children:A.subject}),e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Body:"}),e.jsx("pre",{className:"text-sm whitespace-pre-wrap font-sans",children:A.body})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>v(A.subject,A.id+"-s"),children:[a===A.id+"-s"?e.jsx(ma,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Za,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>v(A.body,A.id+"-b"),children:[a===A.id+"-b"?e.jsx(ma,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Za,{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(A),children:[e.jsx(pi,{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 mo("Delete this template?")&&x.mutate(A.id)},children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},A.id)})]},S)),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx($s,{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(A=>({...A,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(A=>({...A,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:hlr.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(A=>({...A,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(A=>({...A,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(Nr,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const iEt={call:Da,email:pn,text:no,meeting:Ea,note:Qr};function dos({brokerageId:s}){const{data:t,isLoading:n}=st({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=W4e(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),v={};x.forEach(S=>{v[S.activity_type]=(v[S.activity_type]||0)+1});const y=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:v,prospectsCreated:y}}).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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Le,{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=iEt[i]||Qr;return e.jsxs($e,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Recent Activity"})}),e.jsx(Le,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=iEt[r.activity_type]||Qr;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:Js(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 uos({brokerageId:s}){const{toast:t}=Bi(),n=Zt(),[r,a]=j.useState(!1),[i,l]=j.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=st({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:v,error:y}=await q.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(y)throw y;return v}}),d=[...new Set(o.map(v=>v.referred_by))],{data:u=[]}=st({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:v}=await q.from("profiles").select("id, name, email").in("id",d);return v||[]},enabled:d.length>0}),h=Object.fromEntries(u.map(v=>[v.id,v])),m=mt({mutationFn:async v=>{const{data:{user:y}}=await q.auth.getUser();if(!y)throw new Error("Not authenticated");const{error:b}=await q.from("recruit_referrals").insert({brokerage_id:s,referred_by:y.id,referee_first_name:v.first_name,referee_last_name:v.last_name||null,referee_email:v.email||null,referee_phone:v.phone||null,referee_current_brokerage:v.current_brokerage||null,notes:v.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:v=>t({title:"Error",description:v.message,variant:"destructive"})}),f=mt({mutationFn:async({id:v,status:y,incentive_status:b})=>{const w={updated_at:new Date().toISOString()};y&&(w.status=y),b&&(w.incentive_status=b);const{error:S}=await q.from("recruit_referrals").update(w).eq("id",v);if(S)throw S},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),g=v=>v==="approved"||v==="signed"?e.jsx(ma,{className:"h-3 w-3"}):v==="rejected"?e.jsx(ju,{className:"h-3 w-3"}):e.jsx(ca,{className:"h-3 w-3"}),x=v=>v==="approved"||v==="signed"||v==="paid"?"bg-green-500/10 text-green-600 border-green-200":v==="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(cn,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(je,{className:"py-12 text-center",children:[e.jsx(lc,{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(v=>{var y;return e.jsx(je,{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:[v.referee_first_name," ",v.referee_last_name]}),e.jsxs($e,{variant:"outline",className:x(v.status),children:[g(v.status)," ",v.status]}),v.incentive_status&&e.jsxs($e,{variant:"outline",className:x(v.incentive_status),children:[e.jsx(dl,{className:"h-3 w-3 mr-1"})," ",v.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[v.referee_email&&e.jsx("p",{children:v.referee_email}),v.referee_phone&&e.jsx("p",{children:v.referee_phone}),v.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",v.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((y=h[v.referred_by])==null?void 0:y.name)||"Unknown"," • ",Js(new Date(v.created_at),"MMM d, yyyy")]})]}),v.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:v.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(ms,{value:v.status,onValueChange:b=>f.mutate({id:v.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:v.incentive_status||"pending",onValueChange:b=>f.mutate({id:v.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"})]})]})]})]})},v.id)})}),e.jsx(Os,{open:r,onOpenChange:a,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:v=>{v.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:v=>l(y=>({...y,first_name:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Last Name"}),e.jsx(pe,{value:i.last_name,onChange:v=>l(y=>({...y,last_name:v.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:v=>l(y=>({...y,email:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:i.phone,onChange:v=>l(y=>({...y,phone:v.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Current Brokerage"}),e.jsx(pe,{value:i.current_brokerage,onChange:v=>l(y=>({...y,current_brokerage:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Notes"}),e.jsx(Rs,{value:i.notes,onChange:v=>l(y=>({...y,notes:v.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 hos({brokerageId:s}){const{toast:t}=Bi(),n=Zt(),[r,a]=j.useState(!1),{data:i}=st({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=[]}=st({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=mt({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=mt({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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(Le,{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(jn,{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(ma,{className:"h-3.5 w-3.5"}):e.jsx(Za,{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(Ir,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(Le,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(lc,{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($e,{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(pn,{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:Js(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 mos({brokerageId:s}){const{toast:t}=Bi(),n=Zt(),[r,a]=j.useState(!1),[i,l]=j.useState({prospect_id:"",title:"",description:"",due_date:Js(Am(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=j.useState("pending"),{data:d=[]}=st({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:A,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 A}}),{data:u=[],isLoading:h}=st({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const A=d.map(P=>P.id);if(!A.length)return[];const{data:E,error:I}=await q.from("recruit_follow_ups").select("*").in("prospect_id",A).order("due_date");if(I)throw I;return E},enabled:d.length>0}),m=Object.fromEntries(d.map(A=>[A.id,A])),f=mt({mutationFn:async A=>{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:A.prospect_id,assigned_to:E.id,title:A.title,description:A.description||null,due_date:new Date(A.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:Js(Am(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:A=>t({title:"Error",description:A.message,variant:"destructive"})}),g=mt({mutationFn:async({id:A,completed:E})=>{const{error:I}=await q.from("recruit_follow_ups").update({completed_at:E?new Date().toISOString():null}).eq("id",A);if(I)throw I},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),x=u.filter(A=>o==="pending"?!A.completed_at:o==="completed"?!!A.completed_at:!0),v=x.filter(A=>!A.completed_at&&R4(new Date(A.due_date))&&!bv(new Date(A.due_date))),y=x.filter(A=>!A.completed_at&&bv(new Date(A.due_date))),b=x.filter(A=>!A.completed_at&&!R4(new Date(A.due_date))&&!bv(new Date(A.due_date))),w=x.filter(A=>!!A.completed_at),S=A=>{const E=m[A.prospect_id],I=!A.completed_at&&R4(new Date(A.due_date))&&!bv(new Date(A.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(ai,{checked:!!A.completed_at,onCheckedChange:P=>g.mutate({id:A.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 ${A.completed_at?"line-through text-muted-foreground":""}`,children:A.title}),A.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:A.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[E&&e.jsxs($e,{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(vl,{className:"h-3 w-3"}):e.jsx(Ea,{className:"h-3 w-3"}),Js(new Date(A.due_date),"MMM d, h:mm a")]}),A.is_automated&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},A.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(A=>e.jsxs($,{size:"sm",variant:o===A?"default":"outline",onClick:()=>c(A),className:"capitalize text-xs",children:[A," ",A==="pending"&&v.length+y.length+b.length>0&&`(${v.length+y.length+b.length})`]},A))}),e.jsxs($,{size:"sm",onClick:()=>a(!0),children:[e.jsx(cn,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&v.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(vl,{className:"h-3.5 w-3.5"})," Overdue (",v.length,")"]}),v.map(S)]}),o!=="completed"&&y.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(ca,{className:"h-3.5 w-3.5"})," Today (",y.length,")"]}),y.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(Ea,{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(ma,{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(Os,{open:r,onOpenChange:a,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:A=>{A.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:A=>l(E=>({...E,prospect_id:A.target.value})),children:[e.jsx("option",{value:"",children:"Select prospect..."}),d.map(A=>e.jsxs("option",{value:A.id,children:[A.first_name," ",A.last_name]},A.id))]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Task *"}),e.jsx(pe,{required:!0,value:i.title,onChange:A=>l(E=>({...E,title:A.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Details"}),e.jsx(Rs,{value:i.description,onChange:A=>l(E=>({...E,description:A.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:A=>l(E=>({...E,due_date:A.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 mlr=[{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=Zt(),[r,a]=j.useState(null),{data:i,isLoading:l}=st({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:v,error:y}=await q.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(y)throw y;return v}}),[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:mlr,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=mt({mutationFn:async()=>{const v={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:y}=await q.from("recruit_landing_page_settings").update(v).eq("id",o.id);if(y)throw y}else{const{error:y}=await q.from("recruit_landing_page_settings").insert(v);if(y)throw y}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:v=>t({title:"Error",description:v.message,variant:"destructive"})}),u=async(v,y)=>{const b=v.name.split(".").pop(),w=`${s}/${y}-${Date.now()}.${b}`,{error:S}=await q.storage.from("recruit-landing").upload(w,v);if(S)throw S;const{data:{publicUrl:A}}=q.storage.from("recruit-landing").getPublicUrl(w);return A},h=async(v,y)=>{var w;const b=(w=v.target.files)==null?void 0:w[0];if(b){a(y);try{const S=await u(b,y);c(A=>({...A,[y]:S})),t({title:"Image uploaded!"})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},m=async v=>{var b;const y=(b=v.target.files)==null?void 0:b[0];if(y){a("gallery");try{const w=await u(y,"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(v,y)=>{var w;const b=(w=v.target.files)==null?void 0:w[0];if(b){a(`testimonial-${y}`);try{const S=await u(b,`testimonial-${y}`);c(A=>{const E=[...A.testimonials];return E[y]={...E[y],photo_url:S},{...A,testimonials:E}})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},{data:g}=st({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:v,error:y}=await q.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(y)throw y;return v}}),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(Ir,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Branding"})}),e.jsx(Le,{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:v=>h(v,"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:v=>c(y=>({...y,primary_color:v.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(pe,{value:o.primary_color,onChange:v=>c(y=>({...y,primary_color:v.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:v=>c(y=>({...y,accent_color:v.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(pe,{value:o.accent_color,onChange:v=>c(y=>({...y,accent_color:v.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Hero Section"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:o.hero_headline,onChange:v=>c(y=>({...y,hero_headline:v.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Subtext"}),e.jsx(Rs,{value:o.hero_subtext,onChange:v=>c(y=>({...y,hero_subtext:v.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:v=>h(v,"hero_image_url")})]}),o.hero_image_url&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(v=>({...v,hero_image_url:null})),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsx(Et,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(v=>({...v,benefits:[...v.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Le,{className:"space-y-3",children:[o.benefits.map((v,y)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(zg,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(pe,{value:v.icon,onChange:b=>{const w=[...o.benefits];w[y]={...v,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:v.title,onChange:b=>{const w=[...o.benefits];w[y]={...v,title:b.target.value},c(S=>({...S,benefits:w}))},placeholder:"Benefit title"}),e.jsx(pe,{value:v.description,onChange:b=>{const w=[...o.benefits];w[y]={...v,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!==y)})),children:e.jsx(qn,{className:"h-3.5 w-3.5 text-destructive"})})]},y)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsx(Et,{className:"text-base",children:"Testimonials"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(v=>({...v,testimonials:[...v.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Le,{className:"space-y-3",children:[o.testimonials.map((v,y)=>{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:[v.photo_url?e.jsx("img",{src:v.photo_url,alt:v.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=v.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-${y}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:w=>f(w,y)})]})]}),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:v.name,onChange:w=>{const S=[...o.testimonials];S[y]={...v,name:w.target.value},c(A=>({...A,testimonials:S}))},placeholder:"Name"}),e.jsx(pe,{value:v.role,onChange:w=>{const S=[...o.testimonials];S[y]={...v,role:w.target.value},c(A=>({...A,testimonials:S}))},placeholder:"Role / Title"})]}),e.jsx(Rs,{value:v.quote,onChange:w=>{const S=[...o.testimonials];S[y]={...v,quote:w.target.value},c(A=>({...A,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,A)=>A!==y)})),children:e.jsx(qn,{className:"h-3.5 w-3.5 text-destructive"})})]},y)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsx(Et,{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(Hc,{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(Le,{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((v,y)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:v,alt:`Gallery ${y+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!==y)})),children:e.jsx(qn,{className:"h-3 w-3"})})]},y))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(wn,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Application Form Style"}),e.jsxs(ms,{value:o.form_style,onValueChange:v=>c(y=>({...y,form_style:v})),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(jc,{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(jn,{checked:o.confidential_messaging,onCheckedChange:v=>c(y=>({...y,confidential_messaging:v}))})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(r2,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(jn,{checked:o.calculator_enabled,onCheckedChange:v=>c(y=>({...y,calculator_enabled:v}))})]}),o.calculator_enabled&&e.jsxs(Le,{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:v=>c(y=>({...y,calculator_config:{...y.calculator_config,headline:v.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:v=>c(y=>({...y,calculator_config:{...y.calculator_config,subtext:v.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:v=>c(y=>({...y,calculator_config:{...y.calculator_config,commission_split_pct:parseFloat(v.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:v=>c(y=>({...y,calculator_config:{...y.calculator_config,cap_amount:parseFloat(v.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:v=>c(y=>({...y,calculator_config:{...y.calculator_config,post_cap_split_pct:parseFloat(v.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:v=>c(y=>({...y,calculator_config:{...y.calculator_config,monthly_fee:parseFloat(v.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:v=>c(y=>({...y,calculator_config:{...y.calculator_config,transaction_fee:parseFloat(v.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(jn,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:v=>c(y=>({...y,calculator_config:{...y.calculator_config,show_email_capture:v}}))})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(a2,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(jn,{checked:o.lead_magnet_enabled,onCheckedChange:v=>c(y=>({...y,lead_magnet_enabled:v}))})]}),o.lead_magnet_enabled&&e.jsxs(Le,{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:v=>c(y=>({...y,lead_magnet_config:{...y.lead_magnet_config,title:v.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:v=>c(y=>({...y,lead_magnet_config:{...y.lead_magnet_config,description:v.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:v=>c(y=>({...y,lead_magnet_config:{...y.lead_magnet_config,button_text:v.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:v=>c(y=>({...y,lead_magnet_config:{...y.lead_magnet_config,pdf_url:v.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 v=>{var b;const y=(b=v.target.files)==null?void 0:b[0];if(y){a("lead_magnet_pdf");try{const w=await u(y,"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(flr,{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 flr({brokerageId:s}){const{data:t=[]}=st({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(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(ji,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Le,{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:[Js(new Date(n.created_at),"MMM d, yyyy h:mm a")," · via ",n.source]})]})},n.id))})})]})}function pos({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,v]=j.useState(""),[y,b]=j.useState(null),[w,S]=j.useState(""),[A,E]=j.useState(0),[I,P]=j.useState(0),[R,D]=j.useState(""),[O,U]=j.useState(""),{data:W}=oFe(),[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[Z,X]=j.useState(null),{prospects:ae,stages:le}=v9(s),re=ros(),te=f3(),{data:J=[]}=st({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:Ne,error:Be}=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(Be)throw Be;return Ne??[]},enabled:o&&d==="pick-video"}),ce=j.useCallback(()=>{u("pick-recipients"),m(new Set(n?[n]:[])),g("all"),v(""),b(null),S(""),E(0),P(0),D(""),U(""),G("default"),X(null)},[n]),ve=Ne=>{!Ne&&(d==="uploading"||d==="processing"||d==="sending")||(c(Ne),Ne||setTimeout(ce,200))},fe=j.useMemo(()=>ae.filter(Ne=>{if(!Ne.email||f!=="all"&&Ne.stage_id!==f)return!1;if(x){const Be=x.toLowerCase();if(!`${Ne.first_name} ${Ne.last_name??""}`.toLowerCase().includes(Be)&&!Ne.email.toLowerCase().includes(Be))return!1}return!0}),[ae,f,x]),ue=Ne=>{m(Be=>{const Se=new Set(Be);return Se.has(Ne)?Se.delete(Ne):Se.add(Ne),Se})},be=()=>{h.size===fe.length?m(new Set):m(new Set(fe.map(Ne=>Ne.id)))},Ee=j.useCallback(async(Ne,Be)=>{u("uploading");try{const Se=`Recruiting blast (${h.size} recipients)`,{videoId:Ae,libraryId:Ce}=await k6(Se),{uploadUrl:qe,apiKey:ze}=await S6(Ae),Ve=new XMLHttpRequest;Ve.upload.onprogress=gt=>{gt.lengthComputable&&E(gt.loaded/gt.total*100)},await new Promise((gt,es)=>{Ve.onload=()=>Ve.status>=200&&Ve.status<300?gt():es(new Error("Upload failed")),Ve.onerror=()=>es(new Error("Upload failed")),Ve.open("PUT",qe),Ve.setRequestHeader("AccessKey",ze),Ve.send(Ne)}),u("processing");const ht=`https://iframe.mediadelivery.net/embed/${Ce}/${Ae}`;let Qe=0;const at=Date.now(),rt=9e4;for(;Qe<4&&(await new Promise(es=>setTimeout(es,3e3)),!(Date.now()-at>rt));){const gt=await hk(Ae);if(Qe=gt.status,P(gt.encodeProgress||0),Qe===5||Qe===6)throw new Error("Video processing failed")}const Ke=await hk(Ae),Je=(Ke.storageSize||Ne.size)/(1024*1024),ft=await te.mutateAsync({bunny_video_id:Ae,playback_url:Ke.directPlayUrl||ht,thumbnail_url:Ke.thumbnailUrl,preview_url:Ke.previewUrl||null,duration_seconds:Ke.length||Be,file_size_mb:Je,title:Se,status:Qe>=4?"ready":"processing",touch_type:"recruiting"});b(ft.id),S(Se),u("compose")}catch(Se){ne.error((Se==null?void 0:Se.message)||"Failed to upload video"),u("pick-video")}},[h.size,te]),ke=j.useCallback(async()=>{if(!(!y||h.size===0)){u("sending");try{const Ne=[];for(const Ae of h){const Ce=await re.mutateAsync({prospect_id:Ae,video_id:y,brokerage_id:s,message:O||void 0});Ne.push(Ce.id)}const{data:Be,error:Se}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:Ne,brokerage_id:s,subject_override:R||void 0,message_override:O||void 0,send_via:V}});if(Se)throw new Error(Se.message);X({sent:(Be==null?void 0:Be.sent)??0,total:(Be==null?void 0:Be.total)??Ne.length}),u("done"),ne.success(`Sent ${(Be==null?void 0:Be.sent)??0} of ${(Be==null?void 0:Be.total)??Ne.length} videos`)}catch(Ne){ne.error((Ne==null?void 0:Ne.message)||"Failed to send"),u("compose")}}},[y,h,s,O,R,V,re]),Ie=h.size,Fe=ae.filter(Ne=>!Ne.email).length;return e.jsxs(Os,{open:o,onOpenChange:ve,children:[t&&e.jsx(jl,{asChild:!0,children:t}),e.jsxs(Fs,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(Us,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Ie>0&&e.jsxs($e,{variant:"secondary",className:"ml-2",children:[e.jsx(Yn,{className:"h-3 w-3 mr-1"}),Ie," ",Ie===1?"recipient":"recipients"]})]})}),d==="pick-recipients"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(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:Ne=>v(Ne.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"}),le.map(Ne=>e.jsx(Ge,{value:Ne.id,children:Ne.name},Ne.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:be,className:"hover:underline",children:[h.size===fe.length&&fe.length>0?"Deselect all":"Select all"," ","(",fe.length,")"]}),Fe>0&&e.jsxs("span",{children:[Fe," prospect(s) hidden — no email on file"]})]}),e.jsx(go,{className:"flex-1 border rounded-md",children:fe.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:fe.map(Ne=>{const Be=h.has(Ne.id),Se=le.find(Ae=>Ae.id===Ne.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:Be,onCheckedChange:()=>ue(Ne.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:[Ne.first_name," ",Ne.last_name]}),Se&&e.jsx($e,{variant:"outline",className:"text-[10px]",style:{borderColor:Se.color,color:Se.color},children:Se.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ne.email," ",Ne.current_brokerage&&`· ${Ne.current_brokerage}`]})]})]},Ne.id)})})}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>ve(!1),children:"Cancel"}),e.jsx($,{disabled:Ie===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(pa,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(ga,{className:"self-start",children:[e.jsxs(Xt,{value:"record",children:[e.jsx(cn,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(Xt,{value:"library",children:[e.jsx(l2,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(Qt,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(nf,{className:"h-12 w-12 mx-auto text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Record a fresh video"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Same video sent to all ",Ie," ",Ie===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs($,{onClick:()=>u("record"),children:[e.jsx(fa,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(Qt,{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(Ne=>e.jsxs("button",{onClick:()=>{b(Ne.id),S(Ne.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:b4(Ne)?e.jsx("img",{src:b4(Ne),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(fa,{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:Ne.title||"Untitled"})})]},Ne.id))})})]}),e.jsx(Nr,{children:e.jsx($,{variant:"outline",onClick:()=>u("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(DT,{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(Ct,{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"?A:I,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?A: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(Vr,{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:Ie})," recipient",Ie===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(pe,{value:R,onChange:Ne=>D(Ne.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:Ne=>U(Ne.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(Mlt,{value:V,onChange:G}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs($,{onClick:ke,disabled:!y||Ie===0,children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"})," Send to ",Ie," ",Ie===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(Ct,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Ie," recipient",Ie===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&Z&&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 ${Z.sent===Z.total?"bg-primary/10":"bg-muted"}`,children:Z.sent===Z.total?e.jsx(Vr,{className:"h-8 w-8 text-primary"}):e.jsx(vl,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[Z.sent," of ",Z.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx($,{onClick:()=>ve(!1),children:"Done"})]})]})]})}function plr(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function glr({video:s}){return s.cta_clicked_at?e.jsx($e,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs($e,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(Ta,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs($e,{variant:"secondary",children:[e.jsx(Zr,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs($e,{variant:"outline",children:[e.jsx(ca,{className:"h-3 w-3 mr-1"}),"Draft"]})}function gos({brokerageId:s}){var w,S,A,E;const{data:t=[],isLoading:n}=nlr(s),{data:r=[]}=ios(s),a=alr(),i=ilr(),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}),v={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},y=j.useCallback(I=>{if(!I)return;const P=`${window.location.origin}/recruit-video/${I}`;navigator.clipboard.writeText(P),ne.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:v.total,icon:fa,color:"text-primary"},{label:"Sent",value:v.sent,icon:Zr,color:"text-blue-500"},{label:"Viewed",value:v.viewed,icon:Ta,color:"text-amber-500"},{label:"CTA Clicked",value:v.ctaClicked,icon:Vr,color:"text-emerald-500"}].map(I=>e.jsx(je,{children:e.jsxs(Le,{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(pa,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"videos",children:[e.jsx(fa,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(Xt,{value:"scripts",children:[e.jsx(Qr,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(Xt,{value:"analytics",children:[e.jsx(Gl,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(Qt,{value:"videos",children:e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Et,{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(pos,{brokerageId:s,trigger:e.jsxs($,{size:"sm",className:"gap-1.5",children:[e.jsx(pn,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Le,{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(fa,{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:[b4(I.video)?e.jsx("img",{src:b4(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(fa,{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:plr(((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(glr,{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:[Js(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:()=>y(I.share_token),title:"Copy share link",children:e.jsx(Za,{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(pn,{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(Ir,{className:"h-4 w-4"})})]})]},I.id)})})})]})}),e.jsx(Qt,{value:"scripts",children:e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Et,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(Os,{open:d,onOpenChange:u,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(cn,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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:QXe.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(Le,{children:r.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Qr,{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=QXe.find(D=>D.value===I.category))==null?void 0:R.label)||I.category;return e.jsx(je,{className:"relative group",children:e.jsxs(Le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx($e,{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(qn,{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($e,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},I.id)})})})]})}),e.jsx(Qt,{value:"analytics",children:e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Le,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:v.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:v.sent,pct:v.total?Math.round(v.sent/v.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:v.viewed,pct:v.sent?Math.round(v.viewed/v.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:v.ctaClicked,pct:v.viewed?Math.round(v.ctaClicked/v.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(Ta,{className:"h-3.5 w-3.5"})," ",I.view_count]}),I.cta_clicked_at&&e.jsx(Vr,{className:"h-4 w-4 text-emerald-500"})]})]},I.id)})})]})]})]})})]}),f&&e.jsx(nos,{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:(A=f.prospect)==null?void 0:A.email,videoTitle:(E=f.video)==null?void 0:E.title,defaultMessage:f.message})]})}function xos({brokerageId:s}){const{toast:t}=Bi(),n=Zt(),{stages:r,prospects:a}=v9(s),[i,l]=j.useState(!1),[o,c]=j.useState({title:"",target_count:"10",target_stage_id:"",period_start:Js(new Date,"yyyy-MM-dd"),period_end:Js(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:u}=st({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=mt({mutationFn:async g=>{const{data:{user:x}}=await q.auth.getUser();if(!x)throw new Error("Not authenticated");const{error:v}=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(v)throw v},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:g=>t({title:"Error",description:g.message,variant:"destructive"})}),m=mt({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(y=>y.id===g.target_stage_id);return{count:a.filter(y=>PS(new Date(y.created_at),{start:new Date(g.period_start),end:new Date(g.period_end)})?g.target_stage_id?y.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(cn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(je,{className:"py-12 text-center",children:[e.jsx(ph,{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:v}=f(g),y=Math.min(100,x/g.target_count*100),b=PS(new Date,{start:new Date(g.period_start),end:new Date(g.period_end)});return e.jsxs(je,{className:b?"":"opacity-60",children:[e.jsx(St,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Et,{className:"text-sm",children:g.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Js(new Date(g.period_start),"MMM d")," – ",Js(new Date(g.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[b?e.jsx($e,{className:"text-[10px]",children:"Active"}):e.jsx($e,{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(qn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Le,{className:"space-y-2",children:[v&&e.jsxs($e,{variant:"outline",className:"text-[10px]",style:{borderColor:v.color,color:v.color},children:["Stage: ",v.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:y,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[y.toFixed(0),"% complete"]})]})]},g.id)})}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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 xlr={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function yos({email:s,mergeValues:t=xlr,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(Os,{open:!0,onOpenChange:()=>r(),children:e.jsxs(Fs,{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($s,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs($e,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(ca,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs($e,{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 Llt({brokerageId:s}){const t=Zt(),{user:n}=_s(),[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}=st({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}=st({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?ne.error(g.message):ne.success("Scheduling link saved!")},m=mt({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]}),ne.success("Recruiting email settings saved!")},onError:g=>ne.error(g.message)}),f=(g,x)=>{c(v=>({...v,merge_fields:{...v.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(Ea,{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(Rm,{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(Xis,{brokerageId:s,onVerifiedSelect:g=>{c(x=>({...x,sender_email:g})),ne.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 vos=fC.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",Jf(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()}}}),oEt=[{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 Wv({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(ry,{children:[e.jsx(ay,{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(vx,{side:"bottom",className:"text-xs",children:a})]})}function ylr({content:s,onChange:t}){const n=z6e({extensions:[B6e.configure({heading:{levels:[1,2,3]}}),vos,U6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),q6e.configure({types:["heading","paragraph"]}),qnt,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(vk,{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(Wv,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:kE,tooltip:"Bold"}),e.jsx(Wv,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:AE,tooltip:"Italic"}),e.jsx(Wv,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:Jz,tooltip:"Underline"}),e.jsx(Wv,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:XJ,tooltip:"Strikethrough"}),e.jsx(Vc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Wv,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:Iq,tooltip:"Heading 1"}),e.jsx(Wv,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:Oz,tooltip:"Heading 2"}),e.jsx(Wv,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:Lq,tooltip:"Heading 3"}),e.jsx(Vc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Wv,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:E0,tooltip:"Bullet List"}),e.jsx(Wv,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:c2,tooltip:"Numbered List"}),e.jsx(Wv,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:d2,tooltip:"Blockquote"}),e.jsx(Wv,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:YN,tooltip:"Divider"}),e.jsx(Vc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Wv,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:RI,tooltip:"Align Left"}),e.jsx(Wv,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:LI,tooltip:"Align Center"}),e.jsx(Wv,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:DI,tooltip:"Align Right"}),e.jsx(Vc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Wv,{onClick:r,active:n.isActive("link"),icon:Sd,tooltip:"Insert Link"}),e.jsx(Vc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Wv,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:FE,tooltip:"Undo"}),e.jsx(Wv,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:RE,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(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(dV,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(Cu,{align:"end",className:"w-56",children:oEt.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(O6e,{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:"}),oEt.map(i=>e.jsx($e,{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 vlr({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(Os,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(Fs,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Zl,{className:"h-5 w-5 text-primary"}),n," — Engagement Stats"]}),e.jsx(Er,{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(Zr,{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(Jue,{icon:pn,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(Jue,{icon:Ta,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(Jue,{icon:Pm,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(Jue,{icon:Al,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(ca,{className:"h-3 w-3"})," Last sent: ",Js(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(je,{className:"overflow-hidden",children:e.jsxs(Le,{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($e,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(pn,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(Ta,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(Pm,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(Al,{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 Jue({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(je,{children:e.jsx(Le,{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 Rlt(s){return st({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 lEt={cold:{icon:Zj,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:JN,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:sh,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function bos({brokerageId:s}){var be,Ee,ke,Ie;const{user:t}=_s(),n=Zt(),[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,v]=j.useState(null),[y,b]=j.useState(null),{data:w={}}=Rlt(s),[S,A]=j.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:E}=st({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(Ne)throw Ne;return Fe}}),{data:I}=st({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Ne)throw Ne;return Fe}}),P={first_name:"Sarah",brokerage_name:((be=I==null?void 0:I.merge_fields)==null?void 0:be.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:((ke=I==null?void 0:I.merge_fields)==null?void 0:ke.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}=st({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(Ne)throw Ne;return Fe}}),{data:U={}}=st({queryKey:["recruit-campaign-emails",s],enabled:D.length>0,queryFn:async()=>{const Fe=D.map(Ae=>Ae.id),{data:Ne,error:Be}=await q.from("recruit_campaign_emails").select("*").in("campaign_id",Fe).order("email_number");if(Be)throw Be;const Se={};return Ne.forEach(Ae=>{Se[Ae.campaign_id]||(Se[Ae.campaign_id]=[]),Se[Ae.campaign_id].push(Ae)}),Se}}),W=Object.values(U).flat().map(Fe=>Fe.id),{data:V=[]}=st({queryKey:["recruit-subject-overrides",s],enabled:W.length>0,queryFn:async()=>{const{data:Fe,error:Ne}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Ne)throw Ne;return Fe}}),G={};V.forEach(Fe=>{G[Fe.campaign_email_id]=Fe.selected_subject_index});const Z=mt({mutationFn:async({campaignEmailId:Fe,selectedIndex:Ne})=>{const{error:Be}=await q.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:Fe,selected_subject_index:Ne,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(Be)throw Be},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),ne.success("Subject line updated for your brokerage")},onError:Fe=>ne.error(Fe.message)}),X=mt({mutationFn:async Fe=>{const{error:Ne}=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(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ne.success("Email template saved!"),l(null)},onError:Fe=>ne.error(Fe.message)}),ae=mt({mutationFn:async()=>{const Fe=S.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:Ne,error:Be}=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(Be)throw Be;const Se=[{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(Se.map(Ce=>({campaign_id:Ne.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 Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ne.success("Campaign created with 4 starter emails!"),m(!1),A({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:Fe=>ne.error(Fe.message)}),le=mt({mutationFn:async Fe=>{const{error:Ne}=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(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),ne.success("Campaign settings saved!"),v(null)},onError:Fe=>ne.error(Fe.message)}),re=mt({mutationFn:async Fe=>{var qe,ze;const{data:Ne}=await q.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",Fe).order("email_number",{ascending:!1}).limit(1),Be=((qe=Ne==null?void 0:Ne[0])==null?void 0:qe.email_number)??0,Se=((ze=Ne==null?void 0:Ne[0])==null?void 0:ze.delay_days)??0,Ae=Be+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:Se+7,is_active:!0});if(Ce)throw Ce},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ne.success("Email added to campaign!")},onError:Fe=>ne.error(Fe.message)}),te=mt({mutationFn:async Fe=>{const{error:Ne}=await q.from("recruit_campaigns").delete().eq("id",Fe);if(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ne.success("Campaign deleted")},onError:Fe=>ne.error(Fe.message)}),J=mt({mutationFn:async Fe=>{const{error:Ne}=await q.from("recruit_campaign_emails").delete().eq("id",Fe);if(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ne.success("Email removed from campaign")},onError:Fe=>ne.error(Fe.message)}),ce=mt({mutationFn:async({emailId:Fe,delay_days:Ne})=>{const{error:Be}=await q.from("recruit_campaign_emails").update({delay_days:Ne,updated_at:new Date().toISOString()}).eq("id",Fe);if(Be)throw Be},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ne.success("Send delay updated")},onError:Fe=>ne.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 ve=D.filter(Fe=>!Fe.brokerage_id),fe=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(Nd,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs($,{size:"sm",onClick:()=>m(!0),className:"gap-1.5",children:[e.jsx(cn,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(je,{className:"border-primary/20 bg-primary/5",children:e.jsx(Le,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(wn,{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(Nd,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),fe.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(Bq,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:fe.map(Fe=>ue(Fe,!0))})]}),ve.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(wn,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:ve.map(Fe=>ue(Fe,!1))})]}),D.length===0&&e.jsx(je,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(pn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No campaigns yet. Create your first campaign to start automated outreach."}),e.jsxs($,{className:"mt-4",onClick:()=>m(!0),children:[e.jsx(cn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(vlr,{open:!!y,onClose:()=>b(null),campaignName:(y==null?void 0:y.name)||"",stat:y&&w[y.id]||null}),o&&e.jsx(yos,{email:o,mergeValues:P,selectedSubjectIndex:G[o.id],onClose:()=>c(null)}),e.jsx(Os,{open:!!i,onOpenChange:Fe=>!Fe&&l(null),children:e.jsxs(Fs,{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($s,{className:"flex items-center gap-2",children:[e.jsx(qI,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(Er,{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:((Ie=i.subject_line_options)==null?void 0:Ie.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(pa,{value:f,onValueChange:Fe=>g(Fe),children:e.jsxs(ga,{className:"h-7",children:[e.jsx(Xt,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(Xt,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),f==="editor"?e.jsx(ylr,{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(Os,{open:h,onOpenChange:m,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(cn,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(Er,{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=>A({...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=>A({...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=>A({...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=>A({...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=>A({...S,goal:Fe.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(y1,{children:[e.jsx(v1,{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(pn,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(wl,{className:"h-3.5 w-3.5"})]})}),e.jsxs(b1,{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=>A({...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=>A({...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=>A({...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(cn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(Os,{open:!!x,onOpenChange:Fe=>!Fe&&v(null),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Nd,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(Er,{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=>v({...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=>v({...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=>v({...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(pn,{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=>v({...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=>v({...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=>v({...x,reply_to_email:Fe.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs($,{className:"w-full",onClick:()=>le.mutate(x),disabled:le.isPending,children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(Os,{open:d,onOpenChange:u,children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Default Recruiting Email Settings"}),e.jsx(Er,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(Llt,{brokerageId:s})]})})]});function ue(Fe,Ne){const Be=lEt[Fe.warmth_level]||lEt.cold,Se=Be.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(je,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(St,{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 ${Be.bg} flex items-center justify-center`,children:e.jsx(Se,{className:`h-5 w-5 ${Be.color}`})}),e.jsxs("div",{children:[e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[Fe.name,e.jsx($e,{variant:Fe.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:Fe.is_active?"Active":"Draft"}),Ne&&e.jsx($e,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),qe&&e.jsxs($e,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(pn,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(Vn,{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:Ve=>{Ve.stopPropagation(),v({...Fe})},children:e.jsx(Nd,{className:"h-4 w-4 text-muted-foreground"})}),Ne&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async Ve=>{Ve.stopPropagation(),await mo("Delete this campaign and all its emails? This cannot be undone.")&&te.mutate(Fe.id)},children:e.jsx(qn,{className:"h-4 w-4"})}),ze&&ze.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(pn,{className:"h-2.5 w-2.5"})," ",ze.sent.toLocaleString()]}),e.jsxs($e,{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(Ta,{className:"h-2.5 w-2.5"})," ",ze.opened.toLocaleString()," (",ze.openRate.toFixed(0),"%)"]}),e.jsxs($e,{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(Pm,{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:Ve=>{Ve.stopPropagation(),b(Fe)},title:"View detailed engagement stats",children:[e.jsx(Gl,{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(pn,{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(xb,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(wl,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Ce&&e.jsxs(Le,{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(pn,{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((Ve,ht)=>{var Qe,at;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[htrt.stopPropagation(),onBlur:rt=>{const Ke=parseInt(rt.target.value)||0;Ke!==Ve.delay_days&&ce.mutate({emailId:Ve.id,delay_days:Ke})},onKeyDown:rt=>{rt.key==="Enter"&&rt.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ca,{className:"h-3 w-3"}),Ve.email_number===1?"Sent immediately":`Day ${Ve.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",R(((Qe=Ve.subject_line_options)==null?void 0:Qe.length)>0&&Ve.subject_line_options[G[Ve.id]??0]||Ve.subject_line)]})]}),((at=Ve.subject_line_options)==null?void 0:at.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(ms,{value:String(G[Ve.id]??0),onValueChange:rt=>Z.mutate({campaignEmailId:Ve.id,selectedIndex:parseInt(rt)}),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:Ve.subject_line_options.map((rt,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(rt)]},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(Ve),children:e.jsx(Ta,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...Ve}),g("editor")},children:e.jsx(pi,{className:"h-4 w-4"})}),Ne&&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 mo("Delete this email from the sequence?")&&J.mutate(Ve.id)},children:e.jsx(qn,{className:"h-4 w-4"})})]})]})})]},Ve.id)})}),Ne&&e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>re.mutate(Fe.id),disabled:re.isPending,children:[e.jsx(cn,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},Fe.id)}}const cEt={active:{icon:Ou,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:Cv,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:Wl,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:ju,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},dEt={sent:{icon:pn,color:"text-blue-500"},opened:{icon:Ta,color:"text-amber-500"},clicked:{icon:Pm,color:"text-green-500"},failed:{icon:Al,color:"text-destructive"}};function _os({brokerageId:s}){var Ie,Fe,Ne,Be,Se;const{user:t}=_s(),n=Zt(),[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,v]=j.useState("all"),[y,b]=j.useState("all"),[w,S]=j.useState(!1),{data:A}=eie(),{data:E={}}=st({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}=st({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}=st({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=[]}=st({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:((Ie=h==null?void 0:h.prospect)==null?void 0:Ie.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:((Ne=P==null?void 0:P.merge_fields)==null?void 0:Ne.city)||(I==null?void 0:I.city)||"Your City",sender_name:((Be=P==null?void 0:P.merge_fields)==null?void 0:Be.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}=st({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let Ce=[],qe=0;for(;;){const{data:ze,error:Ve}=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(Ve)throw Ve;if(Ce=Ce.concat(ze??[]),!ze||ze.length<1e3)break;qe+=1e3}return Ce}}),{data:G=[]}=st({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:Z=[]}=st({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=[]}=st({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let Ce=[],qe=0;for(;;){const{data:ze,error:Ve}=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(Ve)throw Ve;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}`)),le=mt({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]}),ne.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:Ae=>ne.error(Ae.message)}),re=mt({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]}),ne.success("Assignment updated")}}),te=mt({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]}),ne.success(`Wave sent! ${Ae.sent} emails delivered, ${Ae.skipped} skipped, ${Ae.failed} failed`)},onError:Ae=>ne.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:ve={}}=Rlt(s),fe=W.reduce((Ae,Ce)=>Ae+Math.max(0,Ce.current_email_number||0),0),ue=Object.values(ve).reduce((Ae,Ce)=>Ae+Ce.opened,0),be=Object.values(ve).reduce((Ae,Ce)=>Ae+Ce.clicked,0);Object.values(ve).reduce((Ae,Ce)=>Ae+Ce.failed,0);const Ee=fe>0?Math.round(ue/fe*100):0,ke=fe>0?be/fe*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(Qp,{className:"h-4 w-4 mr-1"}),te.isPending?"Sending...":`Send Next Wave (${ce})`]}),e.jsxs($,{onClick:()=>a(!0),children:[e.jsx(Zr,{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(je,{children:e.jsxs(Le,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Yn,{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(je,{children:e.jsxs(Le,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Ou,{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(je,{children:e.jsxs(Le,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(pn,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:fe.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(je,{children:e.jsxs(Le,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Ta,{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(je,{children:e.jsxs(Le,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Pm,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[ke.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",be.toLocaleString(),")"]})]})]})})]}),e.jsxs(pa,{value:d,onValueChange:u,children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"assignments",children:["Active Drips (",J,")"]}),e.jsxs(Xt,{value:"history",children:["Send History (",fe.toLocaleString(),")"]})]}),e.jsx(Qt,{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(je,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Zr,{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 Qe,at,rt,Ke;const Ce=cEt[Ae.status]||cEt.active,qe=Ce.icon,Ve=(E[Ae.campaign_id]||[]).length||4,ht=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($e,{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:[(Qe=Ae.prospect)==null?void 0:Qe.first_name," ",(at=Ae.prospect)==null?void 0:at.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(rt=Ae.prospect)==null?void 0:rt.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Ke=Ae.campaign)==null?void 0:Ke.name," · Email ",Ae.current_email_number,"/",Ve,Ae.next_send_at&&Ae.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(ca,{className:"h-3 w-3 inline"})," Next: ",Js(new Date(Ae.next_send_at),"MMM d, h:mm a"),new Date(Ae.next_send_at)<=new Date&&e.jsx($e,{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:[ht&&e.jsx($,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>m(Ae),children:e.jsx(Ta,{className:"h-3.5 w-3.5"})}),Ae.status==="active"&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>re.mutate({id:Ae.id,newStatus:"paused"}),children:e.jsx(Cv,{className:"h-3.5 w-3.5"})}),Ae.status==="paused"&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>re.mutate({id:Ae.id,newStatus:"active"}),children:e.jsx(Ou,{className:"h-3.5 w-3.5"})}),(Ae.status==="active"||Ae.status==="paused")&&e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>re.mutate({id:Ae.id,newStatus:"cancelled"}),children:e.jsx(ju,{className:"h-3.5 w-3.5"})})]})]},Ae.id)})})}),e.jsxs(Qt,{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:v,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"}),Z.map(Ae=>e.jsx(Ge,{value:Ae.id,children:Ae.name},Ae.id))]})]}),e.jsxs(ms,{value:y,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"||y!=="all")&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{v("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||y==="opened"&&!qe.opened_at||y==="clicked"&&!qe.clicked_at||y==="sent"&&(qe.opened_at||qe.clicked_at))});return Ae.length===0?e.jsx(je,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(pn,{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=Z.find(qe=>qe.id===x))==null?void 0:Ce.name}`]}),e.jsx("div",{className:"space-y-1",children:Ae.map(qe=>{var Qe,at,rt;const ze=dEt[qe.status]||dEt.sent,Ve=ze.icon,ht=(Qe=Z.find(Ke=>{var Je;return Ke.id===((Je=qe.campaign_email)==null?void 0:Je.campaign_id)}))==null?void 0:Qe.name;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(Ve,{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:[(at=qe.prospect)==null?void 0:at.first_name," ",(rt=qe.prospect)==null?void 0:rt.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",qe.email_number]}),ht&&e.jsx($e,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:ht})]}),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(Ta,{className:"h-3 w-3"})," ",Js(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(Pm,{className:"h-3 w-3"})," ",Js(new Date(qe.clicked_at),"MMM d")]}),e.jsx("span",{children:Js(new Date(qe.sent_at),"MMM d, h:mm a")})]})]},qe.id)})})]})})()]})]}),e.jsx(Os,{open:r,onOpenChange:Ae=>{a(Ae),Ae||(g(""),c(new Set),l(""))},children:e.jsxs(Fs,{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($s,{children:"Assign Campaign to Prospects"}),e.jsx(Er,{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:Z.map(Ae=>e.jsx(Ge,{value:Ae.id,children:Ae.name},Ae.id))})]})]}),i&&(()=>{const Ae=f.toLowerCase(),Ce=X.filter(Ve=>`${Ve.first_name} ${Ve.last_name}`.toLowerCase().includes(Ae)||Ve.email.toLowerCase().includes(Ae)),qe=Ce.filter(Ve=>!ae.has(`${Ve.id}-${i}`)),ze=qe.length>0&&qe.every(Ve=>o.has(Ve.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:Ve=>g(Ve.target.value),className:"pl-9 h-9"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(ze){const Ve=new Set(o);qe.forEach(ht=>Ve.delete(ht.id)),c(Ve)}else{const Ve=new Set(o);qe.forEach(ht=>Ve.add(ht.id)),c(Ve)}},children:[e.jsx(Iz,{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(Ve=>{const ht=ae.has(`${Ve.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${ht?"opacity-40":""}`,children:[e.jsx(ai,{checked:o.has(Ve.id),disabled:ht,onCheckedChange:Qe=>{const at=new Set(o);Qe?at.add(Ve.id):at.delete(Ve.id),c(at)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Ve.first_name," ",Ve.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ve.email})]}),ht&&e.jsx($e,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Ve.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(je,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Le,{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:(Se=Z.find(Ae=>Ae.id===i))==null?void 0:Se.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(Nr,{className:"px-6 py-4 border-t",children:[e.jsx($,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>{le.mutate()},disabled:le.isPending||!i||o.size===0,children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),le.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const Ae=U(h);return Ae?e.jsx(yos,{email:Ae,mergeValues:O,selectedSubjectIndex:D[Ae.id],onClose:()=>m(null)}):null})(),e.jsx(b6e,{open:w,onOpenChange:S,hasPending:A==null?void 0:A.hasPendingSes,pendingEmails:A==null?void 0:A.pendingEmails})]})}function wos({brokerageId:s}){const t=Zt(),[n,r]=j.useState([]),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=j.useRef(!1),{data:d,isLoading:u}=st({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:v,error:y}=await q.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(y)throw y;return v},enabled:!!s});j.useEffect(()=>{if(d){if(c.current){c.current=!1;return}r(d.map(v=>({id:v.id,name:v.name,color:v.color,sort_order:v.sort_order}))),i([]),o(!1)}},[d]);const h=mt({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 v=n.filter(b=>b.id&&!b.isNew),y=n.filter(b=>!b.id||b.isNew);for(const b of v){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(y.length>0){const{error:b}=await q.from("recruit_pipeline_stages").insert(y.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]}),ne.success("Pipeline stages saved!"),o(!1)},onError:v=>ne.error(v.message)}),m=(v,y,b)=>{r(w=>w.map((S,A)=>A===v?{...S,[y]:b}:S)),o(!0)},f=()=>{const v=n.length>0?Math.max(...n.map(y=>y.sort_order)):0;r(y=>[...y,{name:"",color:"#6366f1",sort_order:v+1,isNew:!0}]),o(!0)},g=v=>{const y=n[v];y.id&&!y.isNew&&i(b=>[...b,y.id]),r(b=>b.filter((w,S)=>S!==v)),o(!0)},x=(v,y)=>{const b=v+y;if(b<0||b>=n.length)return;const w=[...n];[w[v],w[b]]=[w[b],w[v]],w.forEach((S,A)=>S.sort_order=A+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((v,y)=>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(y,-1),disabled:y===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>x(y,1),disabled:y===n.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(zg,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:v.color,onChange:b=>m(y,"color",b.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(pe,{value:v.name,onChange:b=>m(y,"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:y+1}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(y),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(qn,{className:"h-4 w-4"})})]},v.id||`new-${y}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:f,className:"gap-1",children:[e.jsx(cn,{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 blr({brokerageId:s}){const{data:t=[],isLoading:n}=st({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(Kz,{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($e,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(je,{children:e.jsxs(Le,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Kz,{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(je,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(St,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Et,{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(pn,{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(Ea,{className:"h-3 w-3"}),r.unsubscribed_at&&Js(new Date(r.unsubscribed_at),"MMM d, yyyy")]})]})}),r.unsubscribe_reason&&e.jsx(Le,{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 _lr(){var o;const[s,t]=j.useState(""),[n,r]=j.useState("board"),{data:a=[],isLoading:i}=st({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(wi,{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(pos,{brokerageId:l,trigger:e.jsxs($,{size:"sm",className:"gap-1.5",children:[e.jsx(fa,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(pa,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(ga,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Xt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Xt,{value:"contacts",children:[e.jsx(Yn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Xt,{value:"video-outreach",children:[e.jsx(fa,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Xt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Xt,{value:"referrals",children:"Referrals"}),e.jsx(Xt,{value:"interest",children:"Interest Form"}),e.jsx(Xt,{value:"landing-page",children:"Landing Page"}),e.jsx(Xt,{value:"goals",children:"Goals"}),e.jsx(Xt,{value:"metrics",children:"Metrics"}),e.jsx(Xt,{value:"templates",children:"Email Templates"}),e.jsxs(Xt,{value:"campaigns",children:[e.jsx(pn,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Xt,{value:"drip-assignments",children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(Xt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Xt,{value:"email-settings",children:[e.jsx(Nd,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Xt,{value:"pipeline-stages",children:[e.jsx(YI,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(Xt,{value:"unsubscribed",children:[e.jsx(Kz,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(Qt,{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(Xf,{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(sV,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(oos,{brokerageId:l}):e.jsx(JXe,{brokerageId:l})]}),e.jsx(Qt,{value:"contacts",children:e.jsx(JXe,{brokerageId:l})}),e.jsx(Qt,{value:"video-outreach",children:e.jsx(gos,{brokerageId:l})}),e.jsx(Qt,{value:"follow-ups",children:e.jsx(mos,{brokerageId:l})}),e.jsx(Qt,{value:"referrals",children:e.jsx(uos,{brokerageId:l})}),e.jsx(Qt,{value:"interest",children:e.jsx(hos,{brokerageId:l})}),e.jsx(Qt,{value:"landing-page",children:e.jsx(fos,{brokerageId:l})}),e.jsx(Qt,{value:"goals",children:e.jsx(xos,{brokerageId:l})}),e.jsx(Qt,{value:"metrics",children:e.jsx(los,{brokerageId:l})}),e.jsx(Qt,{value:"templates",children:e.jsx(cos,{brokerageId:l})}),e.jsx(Qt,{value:"campaigns",children:e.jsx(bos,{brokerageId:l})}),e.jsx(Qt,{value:"drip-assignments",children:e.jsx(_os,{brokerageId:l})}),e.jsx(Qt,{value:"activity",children:e.jsx(dos,{brokerageId:l})}),e.jsx(Qt,{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(Llt,{brokerageId:l})]})}),e.jsx(Qt,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(wos,{brokerageId:l})})}),e.jsx(Qt,{value:"unsubscribed",children:e.jsx(blr,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(wi,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}const uEt=()=>{const s=new Date;return new Date(s.getFullYear(),s.getMonth(),s.getDate()).getTime()},Q$=s=>{const t=s.split(/[-/T]/).slice(0,3).map(Number);return new Date(t[0],(t[1]||1)-1,t[2]||1).getTime()},J$=s=>Date.parse(s);async function jX(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 wlr(s){var o;const t=v9(s),n=Rlt(s),r=st({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?jX("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?jX("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([]),jX("recruit_goals","id, title, target_count, target_stage_id, period_start, period_end",g=>g.eq("brokerage_id",s).order("period_end",{ascending:!1})),jX("recruit_campaign_assignments","id, prospect_id, status",g=>g.eq("brokerage_id",s)),jX("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=st({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 ve,fe,ue,be,Ee;const c=t.prospects,d=t.stages,u=((ve=r.data)==null?void 0:ve.followUps)??[],h=((fe=r.data)==null?void 0:fe.activities)??[],m=((ue=r.data)==null?void 0:ue.goals)??[],f=((be=r.data)==null?void 0:be.assignments)??[],g=((Ee=r.data)==null?void 0:Ee.campaigns)??[],x=uEt(),v=x+864e5,y=Date.now()-30*864e5,b=Date.now()-21*864e5,w=new Map(c.map(ke=>[ke.id,ke])),S=u.filter(ke=>!ke.completed_at),A=S.filter(ke=>J$(ke.due_date){const Ie=J$(ke.due_date);return Ie>=x&&Ie{const Ie=w.get(ke.prospect_id);if(!Ie)return[];const Fe=J$(ke.due_date)ke.prospect_id));c.filter(ke=>J$(ke.updated_at)I.push({id:`stalled-${ke.id}`,prospect:ke,title:"No next step scheduled",detail:"No movement in 21+ days",tone:"stalled",dueAt:null}));const R=d.map(ke=>({...ke,count:c.filter(Ie=>Ie.stage_id===ke.id).length,stalled:c.filter(Ie=>Ie.stage_id===ke.id&&J$(Ie.updated_at)Q$(ke.period_start)<=D&&Q$(ke.period_end)>=D)??null,U=O?c.filter(ke=>Q$(ke.created_at)>=Q$(O.period_start)&&Q$(ke.created_at)<=Q$(O.period_end)&&(!O.target_stage_id||ke.stage_id===O.target_stage_id)).length:0,W=Object.values(n.data??{}),V=W.reduce((ke,Ie)=>ke+Ie.sent,0),G=W.reduce((ke,Ie)=>ke+Ie.opened,0),Z=V?Math.round(G/V*100):0,X=new Map((i.data??[]).map(ke=>[ke.id,ke])),ae=a.map(ke=>{var Be;const Ie=h.filter(Se=>Se.created_by===ke),Fe=Ie.filter(Se=>J$(Se.created_at)>=y),Ne=X.get(ke);return{id:ke,name:(Ne==null?void 0:Ne.name)||(Ne==null?void 0:Ne.email)||"Unknown recruiter",email:(Ne==null?void 0:Ne.email)||"",prospects:c.filter(Se=>Se.created_by===ke).length,activities30d:Fe.length,lastActivityAt:((Be=Ie[0])==null?void 0:Be.created_at)??null}}).sort((ke,Ie)=>Ie.activities30d-ke.activities30d),le=new Map;c.forEach(ke=>{const Ie=(ke.source||"Not recorded").replace(/_/g," ");le.set(Ie,(le.get(Ie)??0)+1)});const re=[...le.entries()].sort((ke,Ie)=>Ie[1]-ke[1]).slice(0,6),te=new Set(["signed","onboarded","hired","joined"]),J=new Set(d.filter(ke=>te.has(ke.name.toLowerCase())).map(ke=>ke.id)),ce=c.filter(ke=>ke.stage_id&&J.has(ke.stage_id)).length;return{prospects:c,stages:R,followUps:u,activities:h,priority:I.slice(0,12),overdueCount:A.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:Z,campaignSent:V,activeCampaigns:g.filter(ke=>ke.is_active).length,activeAssignments:f.filter(ke=>ke.status==="active").length,recruiters:ae,sources:re,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 jlr=s=>s.split(/\s+/).filter(Boolean).slice(0,2).map(t=>t[0]).join("").toUpperCase(),Nlr=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`},ehe=({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 klr({brokerageId:s,onNavigate:t,onOpenProspect:n,onAddProspect:r}){var u;const a=wlr(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(xn,{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(xn,{className:"h-[520px] rounded-md"}),e.jsx(xn,{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(ehe,{label:"Active pipeline",value:a.prospects.length,detail:`${a.converted} converted · ${a.conversionRate}% rate`,icon:x0,tone:"bg-primary/10 text-primary",onClick:()=>t("pipeline-board")}),e.jsx(ehe,{label:"Follow-ups due",value:a.overdueCount+a.dueTodayCount,detail:`${a.overdueCount} overdue · ${a.dueTodayCount} today`,icon:kq,tone:a.overdueCount?"bg-destructive/10 text-destructive":"bg-amber-500/10 text-amber-700",onClick:()=>t("pipeline-follow-ups")}),e.jsx(ehe,{label:"Campaign engagement",value:`${a.campaignOpenRate}%`,detail:`${a.campaignSent} sent · ${a.activeAssignments} enrolled`,icon:zq,tone:"bg-emerald-500/10 text-emerald-700",onClick:()=>t("campaigns-manager")}),e.jsx(ehe,{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:ph,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(Vr,{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:jlr(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($e,{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(Qa,{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(Qa,{className:"ml-1.5 h-3.5 w-3.5"})]}),e.jsxs($,{size:"sm",onClick:r,children:[e.jsx(lc,{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 ",Nlr(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(je,{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(je,{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(Zl,{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(Gl,{className:"mr-1.5 h-3.5 w-3.5"}),"Open recruiting analytics"]})]})]})]})}function Slr({brokerageId:s}){const[t,n]=j.useState(""),[r,a]=j.useState("all"),{data:i,isLoading:l}=st({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var v;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(y=>[y.id,y]));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 y of f||[]){const b=h.get(y.prospect_id);b&&x.push({id:`v-${y.id}`,kind:"video",prospect_id:y.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:(v=y.video)!=null&&v.title?`Video: ${y.video.title}`:"Recruiting Video",status:y.cta_clicked_at?"clicked":y.first_viewed_at?"viewed":"sent",sent_at:y.sent_at,opened_at:y.first_viewed_at,clicked_at:y.cta_clicked_at,view_count:y.view_count,share_token:y.share_token})}for(const y of g||[]){if(!y.sent_at)continue;const b=h.get(y.prospect_id);b&&x.push({id:`c-${y.id}`,kind:"campaign",prospect_id:y.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:y.subject||`Email #${y.email_number}`,status:y.status||"sent",sent_at:y.sent_at,opened_at:y.opened_at,clicked_at:y.clicked_at,error:y.error_message})}return x.sort((y,b)=>new Date(b.sent_at).getTime()-new Date(y.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:Zr,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:fa,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:pn,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:Ta,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:Pm,color:"text-emerald-500"}].map(d=>e.jsx(je,{children:e.jsxs(Le,{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(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Et,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pa,{value:r,onValueChange:d=>a(d),children:e.jsxs(ga,{className:"h-8",children:[e.jsx(Xt,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(Xt,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(Xt,{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(Le,{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(pn,{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($e,{variant:"outline",className:"gap-1",children:[e.jsx(fa,{className:"h-3 w-3"}),"Video"]}):e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(pn,{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($e,{variant:"destructive",className:"gap-1",children:[e.jsx(vl,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs($e,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(Pm,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs($e,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"}),"Opened"]}):e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Zr,{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:[Js(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:Js(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(Ta,{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(Ir,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}const hEt={pipeline:[{value:"pipeline-board",label:"Board",icon:Xf},{value:"pipeline-table",label:"Table",icon:sV},{value:"pipeline-contacts",label:"Contacts",icon:Yn},{value:"pipeline-follow-ups",label:"Follow-ups",icon:Fg},{value:"pipeline-referrals",label:"Referrals",icon:lV}],outreach:[{value:"outreach-video",label:"Video outreach",icon:fa},{value:"outreach-templates",label:"Email templates",icon:Bq},{value:"outreach-sent",label:"Sent emails",icon:pn}],campaigns:[{value:"campaigns-manager",label:"Campaigns",icon:pn},{value:"campaigns-assignments",label:"Drip assignments",icon:Zr}],assets:[{value:"assets-landing",label:"Landing page",icon:kN},{value:"assets-interest",label:"Interest form",icon:Fg}],reporting:[{value:"reporting-metrics",label:"Analytics",icon:Gl},{value:"reporting-goals",label:"Goals",icon:ph},{value:"reporting-activity",label:"Recruiter activity",icon:Yn}],settings:[{value:"settings-email",label:"Email settings",icon:Nd},{value:"settings-stages",label:"Pipeline stages",icon:YI}]},jos=[{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"}],Clr=s=>{var t;return((t=jos.find(n=>s===n.value||s.startsWith(`${n.value}-`)))==null?void 0:t.value)??"command"};function Alr(){var I;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=_s(),r=t||((I=s[0])==null?void 0:I.id)||"",a=v9(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,v]=j.useState(""),y=Clr(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),A=P=>{m(P),g(!0),v("")},E=P=>l(P==="command"?"command":hEt[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(wi,{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(lV,{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=>v(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:()=>A(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(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsxs($,{className:"bg-recruit-gold text-recruit-navy hover:bg-recruit-gold/90",children:[e.jsx(cn,{className:"mr-1.5 h-4 w-4"}),"New prospect ",e.jsx(wl,{className:"ml-2 h-3.5 w-3.5"})]})}),e.jsxs(Cu,{align:"end",children:[e.jsxs(ja,{onSelect:()=>c(!0),children:[e.jsx(cn,{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:jos.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",y===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(wi,{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))})]})]}),y!=="command"&&e.jsx("div",{className:"mb-5 overflow-x-auto pb-1",children:e.jsx(pa,{value:i,onValueChange:l,children:e.jsx(ga,{className:"h-auto min-w-max rounded-md border bg-card p-1",children:hEt[y].map(P=>{const R=P.icon;return e.jsxs(Xt,{value:P.value,className:"gap-1.5",children:[e.jsx(R,{className:"h-3.5 w-3.5"}),P.label]},P.value)})})})}),y==="command"&&r&&e.jsx(klr,{brokerageId:r,onNavigate:S,onOpenProspect:A,onAddProspect:()=>c(!0)}),i==="pipeline-board"&&e.jsx(oos,{brokerageId:r}),(i==="pipeline-table"||i==="pipeline-contacts")&&e.jsx(JXe,{brokerageId:r}),i==="pipeline-follow-ups"&&e.jsx(mos,{brokerageId:r}),i==="pipeline-referrals"&&e.jsx(uos,{brokerageId:r}),i==="outreach-video"&&e.jsx(gos,{brokerageId:r}),i==="outreach-templates"&&e.jsx(cos,{brokerageId:r}),i==="outreach-sent"&&e.jsx(Slr,{brokerageId:r}),i==="campaigns-manager"&&e.jsx(bos,{brokerageId:r}),i==="campaigns-assignments"&&e.jsx(_os,{brokerageId:r}),i==="assets-landing"&&e.jsx(fos,{brokerageId:r}),i==="assets-interest"&&e.jsx(hos,{brokerageId:r}),i==="reporting-metrics"&&e.jsx(los,{brokerageId:r}),i==="reporting-goals"&&e.jsx(xos,{brokerageId:r}),i==="reporting-activity"&&e.jsx(dos,{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(Llt,{brokerageId:r})]}),i==="settings-stages"&&e.jsx("div",{className:"max-w-3xl rounded-md border bg-card p-5",children:e.jsx(wos,{brokerageId:r})})]}),e.jsx(Tlt,{open:o,onOpenChange:c,stages:a.stages,onSubmit:P=>a.addProspect.mutate(P),isSubmitting:a.addProspect.isPending}),e.jsx(Ilt,{open:d,onOpenChange:u,brokerageId:r,stages:a.stages}),e.jsx(Plt,{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 Elr=[{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"}],Tlr=({brokerageId:s,agentUserId:t,readOnly:n})=>{const{toast:r}=Bi(),{data:a}=kRn(s,t),{saveRecord:i}=ZRe(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:Elr.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"]})]})},Mlr=({brokerageId:s,agentUserId:t})=>{const{data:n=[]}=SRn(s,t),{data:r=[]}=kXt(s,t),{addNote:a,deleteNote:i}=ZRe(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(jc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-medium",children:"Private notes"}),e.jsx($e,{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(qn,{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(rf,{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))]})]})]})},mEt=s=>s.split(/\s+/).filter(Boolean).slice(0,2).map(t=>t[0]).join("").toUpperCase(),Nos=s=>s?s.split(/[-/T]/).slice(0,3).join("/"):null,Plr=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"},the=({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"})})]}),Ilr=({brokerageId:s,agentUserId:t})=>{const{data:n=[]}=kXt(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:Nos(r.created_at)})]})]},r.id))]})]})},Llr=({brokerageId:s})=>{var O,U;const{toast:t}=Bi(),{data:n=[],isLoading:r}=jXt(s),{data:a=[]}=wXt(s),{assignTemplate:i,removeAssignment:l}=ZRe(s),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,v]=j.useState(null),[y,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:A}=NXt((O=S==null?void 0:S.assignment)==null?void 0:O.id),E=(A==null?void 0:A.steps)||[],I=E.filter(dE).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(the,{label:"In progress",value:R.inProgress,icon:x0,active:d==="in_progress",tone:"bg-primary/10 text-primary",onClick:()=>u(d==="in_progress"?"all":"in_progress")}),e.jsx(the,{label:"Finished",value:R.finished,icon:Vr,active:d==="finished",tone:"bg-emerald-500/10 text-emerald-700",onClick:()=>u(d==="finished"?"all":"finished")}),e.jsx(the,{label:"Waiting on review",value:R.needsReview,icon:kq,active:d==="review",tone:"bg-amber-500/10 text-amber-700",onClick:()=>u(d==="review"?"all":"review")}),e.jsx(the,{label:"Overdue steps",value:R.overdue,icon:Al,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=Plr(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(Ii,{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:mEt(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($e,{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(Va,{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(Ii,{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:mEt(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 ${Nos(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(qn,{className:"mr-2 h-4 w-4"}),"Remove checklist"]}):e.jsxs($,{onClick:()=>{var W,V;v(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(Ou,{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(Al,{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(pa,{defaultValue:"checklist",className:"space-y-4",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(ga,{className:"grid h-auto min-w-[500px] grid-cols-4 rounded-md border bg-muted/40 p-1",children:[e.jsx(Xt,{value:"checklist",children:"Checklist"}),e.jsx(Xt,{value:"record",children:"Record"}),e.jsx(Xt,{value:"notes",children:"Notes & activity"}),e.jsx(Xt,{value:"documents",children:"Documents"})]})}),e.jsx(Qt,{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(fYe,{brokerageId:s,agentUserId:S.agentId,steps:E,documents:(A==null?void 0:A.documents)||[],mode:"manager"}),e.jsx(Ilr,{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(Qt,{value:"record",children:e.jsx(Tlr,{brokerageId:s,agentUserId:S.agentId})}),e.jsx(Qt,{value:"notes",children:e.jsx(Mlr,{brokerageId:s,agentUserId:S.agentId})}),e.jsx(Qt,{value:"documents",children:S.assignment?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex items-center gap-2",children:[e.jsx(Dz,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"font-['Outfit'] font-semibold",children:"Onboarding documents"})]}),e.jsx(fYe,{brokerageId:s,agentUserId:S.agentId,steps:E,documents:(A==null?void 0:A.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(GN,{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(Os,{open:!!x,onOpenChange:W=>!W&&v(null),children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Start onboarding"}),e.jsxs(Er,{children:["Pick the flow for ",x==null?void 0:x.name,". Later flow edits will not change this checklist."]})]}),e.jsxs(ms,{value:y,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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>v(null),children:"Cancel"}),e.jsxs($,{disabled:!y||!x,onClick:async()=>{if(x)try{await i.mutateAsync({agentUserId:x.agentId,templateId:y}),t({title:"Onboarding started"}),v(null)}catch(W){t({title:"Could not start",description:W.message,variant:"destructive"})}},children:[e.jsx(nP,{className:"mr-2 h-4 w-4"}),"Start"]})]})]})})]})},Rlr=s=>s==="document"?Qr:s==="form"?l_:qj,Dlr=({brokerageId:s})=>{var W,V;const{toast:t}=Bi(),{data:n=[],isLoading:r}=wXt(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}=CRn(s),{data:x=[]}=st({queryKey:["brokerage-form-templates",s],queryFn:async()=>{const{data:G,error:Z}=await q.from("form_templates").select("id, name").eq("brokerage_id",s).eq("is_archived",!1).order("name");if(Z)throw Z;return G||[]}}),[v,y]=j.useState(!1),[b,w]=j.useState(""),[S,A]=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,Z)=>{const X=[...c],ae=G+Z;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(je,{className:"rounded-none border-0 border-r shadow-none",children:[e.jsxs(St,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Et,{className:"text-base",children:"Onboarding flows"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>y(!0),children:e.jsx(cn,{className:"h-4 w-4"})})]}),e.jsx(Vn,{children:"Reusable checklists for new agents"})]}),e.jsxs(Le,{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($e,{variant:"secondary",className:"gap-1",children:[e.jsx(ei,{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(je,{className:"rounded-none border-0 shadow-none",children:o?e.jsxs(e.Fragment,{children:[e.jsx(St,{children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(Et,{children:o.name}),e.jsx(Vn,{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(ei,{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(cn,{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(qn,{className:"h-4 w-4"})})]})]})}),e.jsxs(Le,{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,Z)=>{const X=Rlr(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($e,{variant:"outline",className:"capitalize",children:G.step_type}),e.jsx($e,{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(Z,-1),"aria-label":"Move up",children:e.jsx(Zf,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>U(Z,1),"aria-label":"Move down",children:e.jsx(Lg,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>{R(G),I(!0)},"aria-label":"Edit step",children:e.jsx(pi,{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(qn,{className:"h-4 w-4"})})]})]},G.id)})]})]}):e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Fg,{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(Os,{open:v,onOpenChange:y,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"New onboarding flow"}),e.jsx(Er,{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=>A(G.target.value),rows:3})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx($,{disabled:!b.trim(),onClick:async()=>{const G=await d.mutateAsync({name:b.trim(),description:S});i(G.id),w(""),A(""),y(!1)},children:"Create"})]})]})}),e.jsx(Os,{open:E,onOpenChange:I,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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(Nr,{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"})]})]})})]})},Flr=()=>{const{user:s,isBrokerageManager:t,isAdmin:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=_s(),o=Zn(),[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(wi,{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(pa,{defaultValue:"board",className:"space-y-4",children:[e.jsxs(ga,{className:"grid h-10 w-full max-w-sm grid-cols-2 rounded-md border bg-muted/40 p-1",children:[e.jsx(Xt,{value:"board",children:"Agents"}),e.jsx(Xt,{value:"flows",children:"Flows"})]}),e.jsx(Qt,{value:"board",children:e.jsx(Llr,{brokerageId:u})}),e.jsx(Qt,{value:"flows",children:e.jsx(Dlr,{brokerageId:u})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(wi,{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},Olr={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 zlr({dealId:s}){const{data:t=[]}=SLs(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:Olr[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 Blr({brokerageId:s,deal:t,open:n,onOpenChange:r}){const{data:a=[]}=Mzt(s),i=ALs(),[l,o]=j.useState("");if(!t)return null;const c=VHe(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}}),ne.success("Checklist added to this file")}catch(u){ne.error(u.message||"Could not apply checklist")}};return e.jsx(Vy,{open:n,onOpenChange:r,children:e.jsxs(uy,{className:"w-full overflow-y-auto sm:max-w-xl",children:[e.jsxs(I0,{className:"text-left",children:[e.jsx(L0,{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($e,{variant:"secondary",children:t.agent_name||"Agent"}),t.stage_name&&e.jsx($e,{variant:"outline",children:t.stage_name}),e.jsx($e,{variant:c==="compliant"?"default":"outline",children:Tzt[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(pa,{defaultValue:"checklist",className:"mt-5",children:[e.jsxs(ga,{className:"grid w-full grid-cols-3",children:[e.jsx(Xt,{value:"checklist",children:"Checklist"}),e.jsx(Xt,{value:"messages",children:"Messages"}),e.jsx(Xt,{value:"audit",children:"Audit trail"})]}),e.jsxs(Qt,{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(Lrs,{dealId:t.deal_id,canReview:!0})]}),e.jsx(Qt,{value:"messages",className:"mt-4",children:e.jsx(Rrs,{dealId:t.deal_id,brokerageId:s,role:"staff",counterpartName:t.agent_name})}),e.jsx(Qt,{value:"audit",className:"mt-4",children:e.jsx(zlr,{dealId:t.deal_id})})]})]})})}function $lr({metrics:s}){const t=[{label:"Active transactions",value:String(s.activeDeals),caption:`${s.closedThisYear} closed this year`,icon:wi,tint:"bg-blue-500/10 text-blue-600"},{label:"Pipeline volume",value:Gf(s.pipelineVolume),caption:`${Gf(s.closedVolumeThisYear)} closed YTD`,icon:Zl,tint:"bg-indigo-500/10 text-indigo-600"},{label:"Projected commission",value:Gf(s.pipelineGci),caption:"Gross on active files",icon:su,tint:"bg-emerald-500/10 text-emerald-600"},{label:"Est. brokerage share",value:Gf(s.brokerageShare),caption:`${Gf(s.closedCompanyDollarYtd)} company dollar YTD`,icon:qJ,tint:"bg-teal-500/10 text-teal-600"},{label:"Closing soon",value:String(s.closingNext30),caption:`${s.closingThisMonth} this month`,icon:Su,tint:"bg-amber-500/10 text-amber-600"}],n=[{label:"Files awaiting review",value:s.needsReview,icon:Dz,tint:"text-blue-600"},{label:"Changes requested",value:s.changesRequested,icon:FJ,tint:"text-destructive"},{label:"Overdue items",value:s.overdueItems,icon:Al,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(je,{className:"border-border/60",children:e.jsx(Le,{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(je,{className:"border-border/60",children:e.jsx(Le,{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 Ulr({outlook:s}){const t=s.some(n=>n.deals>0);return e.jsxs(je,{className:"border-border/60",children:[e.jsxs(St,{className:"pb-2",children:[e.jsx(Et,{className:"text-base",children:"Closing outlook"}),e.jsx(Vn,{children:"Expected closings over the next 6 months"})]}),e.jsx(Le,{className:"pt-2",children:t?e.jsx("div",{className:"h-[220px] w-full",children:e.jsx(j_,{width:"100%",height:"100%",children:e.jsxs(PK,{data:s,margin:{top:8,right:8,left:0,bottom:0},children:[e.jsx(pT,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--border))"}),e.jsx(Cb,{dataKey:"label",tickLine:!1,axisLine:!1,fontSize:11,stroke:"hsl(var(--muted-foreground))"}),e.jsx(Ab,{tickLine:!1,axisLine:!1,fontSize:11,stroke:"hsl(var(--muted-foreground))",tickFormatter:n=>Gf(Number(n)),width:54}),e.jsx(kg,{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[`${Gf(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(Dw,{dataKey:"volume",radius:[6,6,0,0],children:s.map(n=>e.jsx(KB,{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 qlr({agents:s,totalVolume:t,selectedAgentId:n,onSelectAgent:r}){return s.length===0?null:e.jsxs(je,{className:"border-border/60",children:[e.jsxs(St,{className:"pb-2",children:[e.jsx(Et,{className:"text-base",children:"Agent production"}),e.jsx(Vn,{children:"Company-visible transactions by agent — tap a row to filter the board"})]}),e.jsx(Le,{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(Ii,{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:Gf(a.volume)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground tabular-nums",children:[Gf(a.gci)," GCI"]})]})]},a.userId)})})]})}const fEt={ownerUserId:"",dealName:"",dealType:"buyer",stageId:"",propertyAddress:"",city:"",state:"",zipCode:"",contractDate:"",targetCloseDate:"",actualCloseDate:"",price:"",commissionPercentage:"",notes:""};function Vlr({brokerageId:s,open:t,onOpenChange:n}){const[r,a]=j.useState(fEt),[i,l]=j.useState(""),{data:o=[],isLoading:c}=LLs(t?s:null),{data:d=[],isLoading:u}=RLs(r.ownerUserId||null),h=DLs();j.useEffect(()=>{t||(a(fEt),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(A=>({...A,[w]:S})),g=r.price?Number(r.price):null,x=r.commissionPercentage?Number(r.commissionPercentage):null,v=g!=null&&x!=null&&Number.isFinite(g)&&Number.isFinite(x)?Math.round(g*(x/100)*100)/100:null,y=!!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);ne.success(`Deal added to ${(w==null?void 0:w.name)||"the agent"}'s pipeline.`),n(!1)}catch(w){ne.error((w==null?void 0:w.message)||"Could not add the deal.")}};return e.jsx(Os,{open:t,onOpenChange:n,children:e.jsxs(Fs,{className:"max-h-[90vh] max-w-2xl overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Add a deal for an agent"}),e.jsx(Er,{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)}),v!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Expected commission: $",v.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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs($,{onClick:b,disabled:!y,children:[h.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Add deal"]})]})]})})}const Hlr={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 Glr({brokerageId:s,canAddDeals:t=!1}){const{data:n=[],isLoading:r}=Ntt(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),[v,y]=j.useState(!1),b=j.useMemo(()=>Wrr(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]),A=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=VHe(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=[...A],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},[A,m]);return r?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ct,{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:()=>y(!0),children:[e.jsx(cn,{className:"mr-2 h-4 w-4"}),"Add deal"]})}),t&&e.jsx(Vlr,{brokerageId:s,open:v,onOpenChange:y}),n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx($lr,{metrics:b}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx(Ulr,{outlook:b.outlook}),e.jsx(qlr,{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(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Nv,{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=VHe(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($e,{variant:"destructive",className:"gap-1 text-[10px]",children:[e.jsx(Al,{className:"h-3 w-3"})," ",I.overdue_items," overdue"]}),e.jsx("span",{className:`rounded-full px-2 py-0.5 text-[11px] font-medium ${Hlr[P]}`,children:Tzt[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(Blr,{brokerageId:s,deal:g,open:!!g,onOpenChange:I=>!I&&x(null)})]})}const pEt=[{value:"any",label:"Any deal type"},{value:"listing",label:"Listing"},{value:"buyer",label:"Buyer"},{value:"lease",label:"Lease"},{value:"referral",label:"Referral"}];function Wlr({brokerageId:s}){var b,w;const{data:t=[],isLoading:n}=Mzt(s),r=wLs(),a=jLs(),[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=[]}=_Ls(o),u=NLs(),h=kLs(),[m,f]=j.useState(!1),[g,x]=j.useState(null),v=async()=>{try{const S=await r.mutateAsync({brokerage_id:s,name:"New checklist",deal_type:null,is_active:!0});l(S)}catch(S){ne.error(S.message||"Could not create checklist")}},y=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(A){ne.error(A.message||"Could not save item")}};return n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Ct,{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(je,{children:[e.jsxs(St,{className:"flex-row items-center justify-between space-y-0",children:[e.jsx(Et,{className:"text-base",children:"Checklists"}),e.jsx($,{size:"sm",variant:"outline",onClick:v,children:e.jsx(cn,{className:"h-4 w-4"})})]}),e.jsx(Le,{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 A;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:(A=pEt.find(E=>E.value===(S.deal_type||"any")))==null?void 0:A.label})]},S.id)})})]}),c?e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-lg",children:"Checklist details"}),e.jsx(Vn,{children:"Applied automatically when a deal becomes company-visible."})]}),e.jsxs(Le,{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:pEt.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(cn,{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 A;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($e,{variant:"secondary",className:"text-[10px]",children:((A=SEe.find(E=>E.value===S.phase))==null?void 0:A.label)||S.phase}),S.requires_document&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:"Document"}),S.required_for_closing&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:"Required to close"}),S.due_anchor&&e.jsxs($e,{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(qn,{className:"h-4 w-4 text-destructive"})})]},S.id)})})]}),e.jsxs($,{variant:"outline",className:"text-destructive",onClick:async()=>{await mo(`Delete "${c.name}"?`)&&(a.mutate({id:c.id,brokerageId:s}),l(null))},children:[e.jsx(qn,{className:"mr-2 h-4 w-4"})," Delete checklist"]})]})]}):e.jsx(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Qr,{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(Os,{open:m,onOpenChange:f,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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(A=>({...A,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(A=>({...A,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(A=>({...A,phase:S})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:SEe.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(A=>({...A,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(A=>({...A,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(jn,{checked:(g==null?void 0:g.requires_document)??!0,onCheckedChange:S=>x(A=>({...A,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(jn,{checked:(g==null?void 0:g.required_for_closing)??!0,onCheckedChange:S=>x(A=>({...A,required_for_closing:S}))})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsxs($,{onClick:y,disabled:!((w=g==null?void 0:g.title)!=null&&w.trim())||u.isPending,children:[u.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Save"]})]})]})})]})}function Klr({brokerageId:s}){const{data:t,isLoading:n}=vLs(s),r=bLs(),{data:a=[]}=gLs(s),i=xLs(),l=yLs(),[o,c]=j.useState(["contract","closing","closed"]),[d,u]=j.useState(!0),[h,m]=j.useState(!0),[f,g]=j.useState(""),[x,v]=j.useState(!1);j.useEffect(()=>{t&&(c(t.visible_phases||[]),u(t.include_contract_dated_deals),m(t.is_enabled))},[t]);const y=S=>c(A=>A.includes(S)?A.filter(E=>E!==S):[...A,S]),b=async()=>{try{await r.mutateAsync({brokerage_id:s,visible_phases:o,include_contract_dated_deals:d,is_enabled:h}),ne.success("Compliance settings saved")}catch(S){ne.error(S.message||"Could not save settings")}},w=async()=>{const S=f.trim().toLowerCase();if(S){v(!0);try{const{data:A,error:E}=await q.from("profiles").select("id, email").ilike("email",S).maybeSingle();if(E)throw E;if(!A){ne.error("No LevelUp account found with that email");return}await i.mutateAsync({brokerageId:s,userId:A.id}),g(""),ne.success("Transaction admin added")}catch(A){ne.error(A.message||"Could not add transaction admin")}finally{v(!1)}}};return n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-lg",children:"What the company can see"}),e.jsx(Vn,{children:"Agent leads, consultations and early conversations stay private. Deals become visible to compliance once they reach one of the phases below."})]}),e.jsxs(Le,{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(jn,{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:SEe.map(S=>e.jsx("button",{type:"button",onClick:()=>y(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(jn,{checked:d,onCheckedChange:u})]}),e.jsxs($,{onClick:b,disabled:r.isPending,children:[r.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Save settings"]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Rm,{className:"h-4 w-4"})," Transaction admins"]}),e.jsx(Vn,{children:"Give staff compliance-only access — deals, documents, checklists and notes. No recruiting or billing."})]}),e.jsxs(Le,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(lc,{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($e,{variant:"secondary",className:"text-[10px]",children:"Compliance"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>l.mutate({id:S.id,brokerageId:s}),children:e.jsx(qn,{className:"h-4 w-4 text-destructive"})})]})]},S.id))})]})]})]})}const Ylr=()=>{const{user:s,isBrokerageManager:t,isAdmin:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=_s(),o=Zn(),{data:c=[],isLoading:d}=jtt(),[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(wi,{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(pa,{defaultValue:"board",className:"space-y-4",children:[e.jsxs(ga,{className:`grid w-full ${f?"max-w-lg grid-cols-3":"max-w-xs grid-cols-1"}`,children:[e.jsx(Xt,{value:"board",children:"Transactions"}),f&&e.jsx(Xt,{value:"checklists",children:"Checklists"}),f&&e.jsx(Xt,{value:"settings",children:"Settings"})]}),e.jsx(Qt,{value:"board",children:e.jsx(Glr,{brokerageId:g,canAddDeals:f||m})}),f&&e.jsx(Qt,{value:"checklists",children:e.jsx(Wlr,{brokerageId:g})}),f&&e.jsx(Qt,{value:"settings",children:e.jsx(Klr,{brokerageId:g})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(wi,{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},Ane=q,dUe={draft:"Draft",approved:"Approved",paid:"Paid",void:"Void"},i_=s=>{const t=Number(s);return Number.isFinite(t)?t:0};function CW(s){const t=i_(s.gross_commission),n=i_(s.referral_amount)>0?i_(s.referral_amount):t*i_(s.referral_fee_pct)/100,r=Math.max(0,t-n),a=r*(100-i_(s.agent_split_pct))/100,i=r*i_(s.franchise_fee_pct)/100,l=i_(s.transaction_fee),o=(s.line_items||[]).reduce((u,h)=>u+i_(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 Zlr(s,t){const n=i_(s.brokerage_split_pct),r=(t==null?void 0:t.agent_split_pct)!=null?i_(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:kW(s),gross_commission:SW(s),agent_split_pct:r,franchise_fee_pct:s.franchise_fee_pct!=null?i_(s.franchise_fee_pct):i_(t==null?void 0:t.franchise_fee_pct),transaction_fee:s.transaction_fee!=null?i_(s.transaction_fee):i_(t==null?void 0:t.transaction_fee),referral_fee_pct:i_(t==null?void 0:t.referral_fee_pct),referral_amount:0,referral_payee:null,line_items:[],notes:null}}function kos(s){return st({queryKey:["disbursements",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await Ane.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 Xlr(s){const t=Zt(),{user:n}=_s();return mt({mutationFn:async r=>{const a=CW(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 Ane.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 Ane.from("brokerage_disbursements").insert(i);if(l)throw l}},onSuccess:()=>{t.invalidateQueries({queryKey:["disbursements",s]}),ne.success("Disbursement saved")},onError:r=>ne.error(r.message||"Could not save the disbursement")})}function Qlr(s){const t=Zt(),{user:n}=_s();return mt({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 Ane.from("brokerage_disbursements").update(i).eq("id",r);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["disbursements",s]}),onError:r=>ne.error(r.message||"Could not update the status")})}function Jlr(s){const t=Zt();return mt({mutationFn:async n=>{const{error:r}=await Ane.from("brokerage_disbursements").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["disbursements",s]}),ne.success("Disbursement removed")},onError:n=>ne.error(n.message||"Could not remove the disbursement")})}function Sos(s){return st({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 LPe=q;function ecr(s){return st({queryKey:["ops-follow-ups",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await LPe.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 LPe.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 tcr(s){return st({queryKey:["ops-help-requests",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await LPe.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 LPe.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 t3=q,Cos=[{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"}],RPe=Object.fromEntries(Cos.map(s=>[s.value,s.label])),eQe={todo:"To do",in_progress:"In progress",done:"Done"},scr={low:"Low",medium:"Medium",high:"High",urgent:"Urgent"};function ncr(s){return st({queryKey:["ops-tasks",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await t3.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 rcr(s){const t=Zt(),{user:n}=_s();return mt({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 t3.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 t3.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"]}),ne.success("Task saved")},onError:r=>ne.error(r.message||"Could not save task")})}function acr(s){const t=Zt();return mt({mutationFn:async({id:n,status:r})=>{const{error:a}=await t3.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=>ne.error(n.message||"Could not update task")})}function icr(s){const t=Zt();return mt({mutationFn:async n=>{const{error:r}=await t3.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"]}),ne.success("Task removed")},onError:n=>ne.error(n.message||"Could not remove task")})}function ocr(s){const t=Zt(),{user:n}=_s();return mt({mutationFn:async r=>{const{error:a}=await t3.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]}),ne.success("Dismissed")},onError:r=>ne.error(r.message||"Could not dismiss")})}function lcr(s){return st({queryKey:["ops-task-comments",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await t3.from("brokerage_operations_task_comments").select("*").eq("task_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function ccr(){const s=Zt(),{user:t}=_s();return mt({mutationFn:async({taskId:n,body:r})=>{const{error:a}=await t3.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=>ne.error(n.message||"Could not add note")})}function dcr(s){const{user:t}=_s();return st({queryKey:["ops-digest-prefs",s,t==null?void 0:t.id],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await t3.from("brokerage_operations_digest_prefs").select("*").eq("brokerage_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})}function ucr(s){const t=Zt(),{user:n}=_s();return mt({mutationFn:async r=>{const{error:a}=await t3.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]}),ne.success("Notification settings saved")},onError:r=>ne.error(r.message||"Could not save settings")})}const hcr={license:"License renewal",eo:"E&O insurance",anniversary:"Work anniversary",birthday:"Birthday"},Aos=864e5,Eos=()=>{const s=new Date;return{y:s.getFullYear(),m:s.getMonth()+1,d:s.getDate()}},hq=(s,t,n)=>Date.UTC(s,t-1,n),Dlt=s=>{const t=MC(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},DPe=s=>String(s).padStart(2,"0");function gEt(s){const t=MC(s||"");if(!t)return null;const n=Eos(),r=Math.round((hq(t.y,t.m,t.d)-hq(n.y,n.m,n.d))/Aos);return{dueDate:`${t.y}-${DPe(t.m)}-${DPe(t.d)}`,daysUntil:r,expired:r<0}}function xEt(s){const t=MC(s||"");if(!t)return null;const n=Eos();let r=n.y;hq(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=gEt(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=gEt(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=xEt(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=xEt(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 mcr(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 fcr=864e5;function NX(s){const t=MC(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)/fcr)}function pcr(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:NX(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:NX(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=NX(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"})}),Tos(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=NX(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=NX(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 gcr={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"},xcr=s=>(s||"?").split(" ").map(t=>t[0]).filter(Boolean).slice(0,2).join("").toUpperCase();function ycr({items:s,loading:t,onDismiss:n,onTrack:r}){const a=Zn(),[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(xn,{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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{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(je,{children:[e.jsxs(St,{className:"flex-row items-start justify-between gap-3 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Et,{className:"text-base",children:"What needs your attention"}),e.jsx(Vn,{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:RPe[h]||h},h))]})]})]}),e.jsx(Le,{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(Vr,{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(Ii,{src:h.avatarUrl,alt:""}),e.jsx(za,{className:"text-xs",children:xcr(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($e,{variant:"outline",className:Pt("text-[10px]",gcr[h.priority]),children:RPe[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(Al,{className:"h-3 w-3"}):e.jsx(Su,{className:"h-3 w-3"}),Dlt(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(TJ,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Dismiss",onClick:()=>n(h),children:e.jsx(mr,{className:"h-4 w-4"})})]})]},h.key))})]})]})}const she=["todo","in_progress","done"],vcr={urgent:"bg-destructive",high:"bg-amber-500",medium:"bg-primary/60",low:"bg-muted-foreground/40"};function bcr({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 v;return x?((v=t.find(y=>y.id===x))==null?void 0:v.name)||"Team member":"Unassigned"},f=j.useMemo(()=>Array.from(new Set(s.map(x=>x.category))),[s]);if(n)return e.jsx(xn,{className:"h-72 w-full"});const g=(x,v)=>{const y=she.indexOf(x.status),b=she[y+v];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:RPe[x]||x},x))]})]}),e.jsxs($,{className:"ml-auto",onClick:r,children:[e.jsx(cn,{className:"mr-2 h-4 w-4"})," New task"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:she.map(x=>{const v=h.filter(y=>y.status===x);return e.jsxs(je,{className:"flex flex-col",children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"flex items-center justify-between text-sm",children:[eQe[x],e.jsx($e,{variant:"secondary",children:v.length})]})}),e.jsxs(Le,{className:"space-y-2",children:[v.length===0&&e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"Nothing here"}),v.map(y=>{const b=!!y.due_date&&y.status!=="done"&&y.due_datea(y),children:[e.jsx("p",{className:"truncate font-medium",children:y.title}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[RPe[y.category]||y.category," · ",m(y.assignee_user_id)]})]}),e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Cu,{align:"end",children:[e.jsxs(ja,{onClick:()=>a(y),children:[e.jsx(pi,{className:"mr-2 h-4 w-4"})," Edit"]}),she.filter(w=>w!==y.status).map(w=>e.jsxs(ja,{onClick:()=>i(y,w),children:["Move to ",eQe[w]]},w)),e.jsxs(ja,{className:"text-destructive",onClick:()=>l(y),children:[e.jsx(qn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),y.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(Su,{className:"h-3 w-3"})," ",Dlt(y.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(y,-1),children:e.jsx(Va,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"outline",className:"flex-1",disabled:x==="done",onClick:()=>g(y,1),children:e.jsx(Qa,{className:"h-4 w-4"})})]})]},y.id)})]})]},x)})})]})}const _cr=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],yEt=(s,t,n)=>`${s}-${String(t+1).padStart(2,"0")}-${String(n).padStart(2,"0")}`;function wcr({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=yEt(r.getFullYear(),r.getMonth(),r.getDate()),v=l?d.get(l)||[]:[],y=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(je,{children:[e.jsxs(St,{className:"flex-row items-center justify-between space-y-0",children:[e.jsxs("div",{children:[e.jsx(Et,{className:"text-base",children:g}),e.jsx(Vn,{children:"Closings, renewals and due dates in one place."})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"icon",variant:"outline",onClick:()=>y(-1),children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"outline",onClick:()=>y(1),children:e.jsx(Di,{className:"h-4 w-4"})})]})]}),e.jsxs(Le,{children:[e.jsx("div",{className:"grid grid-cols-7 gap-1 text-center text-xs text-muted-foreground",children:_cr.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=yEt(a.y,a.m,b),A=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:A.slice(0,4).map(E=>e.jsx("span",{className:Pt("h-1.5 w-1.5 rounded-full",E.tone)},E.id))}),A.length>0&&e.jsxs("span",{className:"mt-auto text-[10px] text-muted-foreground",children:[A.length," item",A.length===1?"":"s"]})]},S)})})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{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(Vn,{children:l?`${v.length} item${v.length===1?"":"s"}`:"Select a date to see what is happening."})]}),e.jsxs(Le,{className:"space-y-2",children:[l&&v.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing scheduled."}),v.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($e,{variant:"outline",children:[e.jsx("span",{className:"mr-1 h-2 w-2 rounded-full bg-emerald-500"})," Closings"]}),e.jsxs($e,{variant:"outline",children:[e.jsx("span",{className:"mr-1 h-2 w-2 rounded-full bg-amber-500"})," Action items"]}),e.jsxs($e,{variant:"outline",children:[e.jsx("span",{className:"mr-1 h-2 w-2 rounded-full bg-primary"})," Tasks"]})]})})]})]})]})}function jcr({taskId:s,people:t}){const{data:n=[]}=lcr(s),r=ccr(),[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 vEt={title:"",description:"",category:"general",status:"todo",priority:"medium",due_date:null,assignee_user_id:null};function Ncr({open:s,onOpenChange:t,task:n,initial:r,people:a,onSave:i,saving:l}){const[o,c]=j.useState(vEt);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}:{...vEt,...r||{}})},[s,n,r]);const d=u=>c(h=>({...h,...u}));return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-h-[90vh] max-w-lg overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:n?"Edit task":"New task"}),e.jsx(Er,{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:Cos.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(scr).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(eQe).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(jcr,{taskId:n.id,people:a})]}),e.jsxs(Nr,{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 kcr=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Scr({brokerageId:s}){const{data:t}=dcr(s),n=ucr(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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Weekly summary"}),e.jsx(Vn,{children:"Off by default. Turn it on and you alone get a weekly rundown of what is open, due and overdue."})]}),e.jsxs(Le,{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(jn,{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(jn,{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:kcr.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 Ccr=()=>{const{user:s,rolesLoading:t,isBrokerageManager:n,isAdmin:r,brokerageId:a,managedBrokerages:i,selectedBrokerageId:l,setSelectedBrokerageId:o}=_s(),c=Zn(),{data:d=[],isLoading:u}=jtt(),[h,m]=j.useState(!1),f=d.length>0,g=n||r,x=j.useMemo(()=>{var be;return l||(i.length>0?i[0].id:null)||((be=d[0])==null?void 0:be.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:v=[],isLoading:y}=Ntt(x),{data:b=[]}=kos(x),{data:w=[]}=Sos(x),{data:S=[]}=jXt(x),{data:A=[]}=ecr(x),{data:E=[]}=tcr(x),{data:I=[],isLoading:P}=ncr(x),R=rcr(x),D=acr(x),O=icr(x),U=ocr(x),[W,V]=j.useState(!1),[G,Z]=j.useState(null),[X,ae]=j.useState(null),le=j.useMemo(()=>S.map(be=>({id:be.agentId,name:be.name})),[S]),re=be=>{var Ee;return be?((Ee=le.find(ke=>ke.id===be))==null?void 0:Ee.name)??null:null},te=j.useMemo(()=>pcr({complianceDeals:v,disbursements:b,agentRecords:w,renewalAgents:S.map(be=>({agentId:be.agentId,name:be.name,avatarUrl:be.avatarUrl})),roster:S.map(be=>({agentId:be.agentId,name:be.name,avatarUrl:be.avatarUrl,overdue:be.overdue,needsReview:be.needsReview})),followUps:A,helpRequests:E,tasks:I,nameFor:re}),[v,b,w,S,A,E,I]),J=j.useMemo(()=>v.filter(be=>be.target_close_date).map(be=>({id:be.deal_id,label:be.property_address||be.deal_name,date:be.target_close_date})),[v]),ce=()=>{Z(null),ae(null),V(!0)},ve=be=>{Z(null),ae(be),V(!0)},fe=be=>{Z(be),ae(null),V(!0)},ue=be=>U.mutate({sourceType:be.sourceType,sourceId:be.sourceId,title:be.title,category:be.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(wi,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{placeholder:"Select brokerage"})]}),e.jsx(hs,{children:i.map(be=>e.jsx(Ge,{value:be.id,children:be.name},be.id))})]})]}),x?e.jsxs(pa,{defaultValue:"today",className:"space-y-4",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(ga,{className:"grid h-auto min-w-[460px] grid-cols-4",children:[e.jsx(Xt,{value:"today",children:"Today"}),e.jsx(Xt,{value:"tasks",children:"Task board"}),e.jsx(Xt,{value:"calendar",children:"Calendar"}),e.jsx(Xt,{value:"notifications",children:"Notifications"})]})}),e.jsx(Qt,{value:"today",children:e.jsx(ycr,{items:te,loading:y,onDismiss:ue,onTrack:ve})}),e.jsx(Qt,{value:"tasks",children:e.jsx(bcr,{tasks:I,people:le,loading:P,onNew:ce,onEdit:fe,onStatus:(be,Ee)=>D.mutate({id:be.id,status:Ee}),onDelete:be=>O.mutate(be.id)})}),e.jsx(Qt,{value:"calendar",children:e.jsx(wcr,{items:te,tasks:I,closings:J})}),e.jsx(Qt,{value:"notifications",children:e.jsx(Scr,{brokerageId:x})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(wi,{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(Ncr,{open:W,onOpenChange:V,task:G,initial:X,people:le,saving:R.isPending,onSave:be=>R.mutate(be,{onSuccess:()=>V(!1)})})]})}):null},bEt="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 uUe(s,t){return t?`https://${t}`:s?`https://${s}.thelocalmove.com`:null}function Mos(){const{user:s,isAdmin:t,isBrokerageManager:n,managedBrokerages:r,brokerageId:a,selectedBrokerageId:i}=_s(),{data:l=[]}=Eae(),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=st({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(bEt).eq("agent_id",s.id).order("created_at",{ascending:!0}),d.length||u.length?q.from("lead_sites").select(bEt).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 y,b,w;const f=((y=h.data)==null?void 0:y.own)||[],g=((b=h.data)==null?void 0:b.org)||[],x=[],v=f.find(S=>S.is_active)||f[0]||null;v?x.push({kind:"agent",id:v.id,ownerId:null,name:v.site_title||"My website",kindLabel:"My agent site",slug:v.subdomain_slug,customDomain:v.custom_domain,isActive:!!v.is_active,logoUrl:null,brandColor:v.brand_color,editPath:`/my-website/${v.id}/edit`,publicUrl:uUe(v.subdomain_slug,v.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 A=g.find(E=>E.owner_type==="brokerage"&&E.brokerage_id===S.id)||null;x.push({kind:"brokerage",id:(A==null?void 0:A.id)??null,ownerId:S.id,name:(A==null?void 0:A.org_name)||(A==null?void 0:A.site_title)||S.name,kindLabel:"Company site",slug:(A==null?void 0:A.subdomain_slug)??null,customDomain:(A==null?void 0:A.custom_domain)??null,isActive:!!(A!=null&&A.is_active),logoUrl:(A==null?void 0:A.org_logo_url)??null,brandColor:(A==null?void 0:A.brand_color)??null,editPath:"/brokerage/website",publicUrl:uUe((A==null?void 0:A.subdomain_slug)??null,(A==null?void 0:A.custom_domain)??null),exists:!!A})}for(const S of o){const A=g.find(E=>E.owner_type==="team"&&E.team_id===S.teamId)||null;x.push({kind:"team",id:(A==null?void 0:A.id)??null,ownerId:S.teamId,name:(A==null?void 0:A.org_name)||(A==null?void 0:A.site_title)||((w=S.team)==null?void 0:w.name)||"My team",kindLabel:"Team site",slug:(A==null?void 0:A.subdomain_slug)??null,customDomain:(A==null?void 0:A.custom_domain)??null,isActive:!!(A!=null&&A.is_active),logoUrl:(A==null?void 0:A.org_logo_url)??null,brandColor:(A==null?void 0:A.brand_color)??null,editPath:`/team/website?teamId=${S.teamId}`,publicUrl:uUe((A==null?void 0:A.subdomain_slug)??null,(A==null?void 0:A.custom_domain)??null),exists:!!A})}return x},[h.data,c,o]);return{websites:m,isLoading:h.isLoading,ledTeams:o,hasOrgSites:m.some(f=>f.kind!=="agent")}}const Acr={agent:cl,brokerage:wi,team:Yn};function Ecr({site:s}){const t=Zn(),n=Acr[s.kind],r=s.customDomain||(s.slug?`${s.slug}.thelocalmove.com`:null);return e.jsx(je,{className:"overflow-hidden transition-shadow hover:shadow-md",children:e.jsxs(Le,{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($e,{children:"Live"}):e.jsx($e,{variant:"secondary",children:"Private preview"}):e.jsx($e,{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(Ir,{className:"mr-2 h-4 w-4"})," View"]})}),e.jsx($,{onClick:()=>t(s.editPath),children:s.exists?e.jsxs(e.Fragment,{children:[e.jsx(pi,{className:"mr-2 h-4 w-4"})," Edit site"]}):e.jsxs(e.Fragment,{children:[e.jsx(cn,{className:"mr-2 h-4 w-4"})," Create site"]})})]})]})})}function Tcr(){const{websites:s,isLoading:t}=Mos();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(Ecr,{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(br,{to:"/website-apps",className:"underline",children:"Website Apps"})]})]})})})}const _Et={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 qSr(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=_Et[n]||_Et.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 Pos=[{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 Ios(s){return(s==null?void 0:s.orgProfile)||{}}function VSr(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 HSr(s){var n;if((s==null?void 0:s.ownerType)!=="team")return null;const t=(n=Ios(s).affiliation)==null?void 0:n.trim();return t||null}function GSr(s){const t=Ios(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 Mcr=10*1024*1024;function hUe({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/")){ne.error("Please choose an image file");return}if(g.size>Mcr){ne.error("Image must be under 10MB");return}u(!0);try{const x=(g.name.split(".").pop()||"png").toLowerCase(),v=`org-sites/${i}/${a}-${Date.now()}.${x}`,{error:y}=await q.storage.from("agent-uploads").upload(v,g,{upsert:!0,contentType:g.type});if(y)throw y;const{data:b}=q.storage.from("agent-uploads").getPublicUrl(v);r(b.publicUrl),ne.success(`${s} uploaded`)}catch(x){ne.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 v;g.preventDefault(),m(!1);const x=(v=g.dataTransfer.files)==null?void 0:v[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(Hc,{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(Ct,{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 v;const x=(v=g.target.files)==null?void 0:v[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(qn,{className:"h-4 w-4"})})]})]})}const Pcr="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 Icr(s){const{brokerageId:t,teamId:n}=s;return st({queryKey:["org-site",t,n],enabled:!!(t||n),queryFn:async()=>{let r=q.from("lead_sites").select(Pcr).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 Lcr(s){return st({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 Rcr(s){const t=Zt();return mt({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]}),ne.success(n?`${n} agent${n===1?"":"s"} added to the roster.`:"Roster is already up to date.")},onError:n=>ne.error(n.message||"Could not refresh the roster.")})}function Dcr(s){const t=Zt();return mt({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=>ne.error(n.message||"Could not save that change.")})}function Fcr(s){const t=Zt();return mt({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"]}),ne.success("Saved.")},onError:n=>ne.error(n.message||"Could not save the website.")})}function nhe(s){return s.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40)}function Flt({brokerageId:s,teamId:t,orgLabel:n="brokerage"}){const{data:r,isLoading:a,refetch:i}=Icr({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(zcr,{site:r,orgLabel:n}):e.jsx(Ocr,{brokerageId:s,teamId:t,orgLabel:n,onCreated:()=>i()})}function Ocr({brokerageId:s,teamId:t,orgLabel:n,onCreated:r}){const{user:a}=_s(),[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 v=!1;return(async()=>{if(t){const{data:S}=await q.from("teams").select("name, description, avatar_url, brokerage_id").eq("id",t).maybeSingle();if(v||!S)return;const A=S.name||"";A&&(l(P=>P||A),c(P=>P||nhe(A)));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(v)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:y},{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(v)return;const w=(b==null?void 0:b.name)||"";w&&(l(S=>S||w),c(S=>S||nhe(w))),g({logo:(y==null?void 0:y.logo_url)||null,primary:(y==null?void 0:y.primary_color)||null,accent:(y==null?void 0:y.accent_color)||null,legalName:(y==null?void 0:y.legal_name)||null,license:(y==null?void 0:y.license_number)||null,about:null,affiliation:null})})(),()=>{v=!0}},[s,t]);const x=async()=>{if(!a||!s&&!t)return;if(!i.trim()||!o.trim()){ne.error(`Add a ${n} name and web address.`);return}m(!0);const{error:v}=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),v){ne.error(v.message.includes("duplicate")?"That web address is taken — try another.":v.message);return}ne.success("Website created as a private preview."),r()};return e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(cl,{className:"h-5 w-5"})," Create your ",n," website"]}),e.jsxs(Vn,{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(Le,{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:v=>{l(v.target.value),o||c(nhe(v.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:v=>c(nhe(v.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:Pos.map(v=>e.jsxs("button",{type:"button",onClick:()=>u(v.key),className:`rounded-lg border p-4 text-left transition-colors ${d===v.key?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("p",{className:"font-medium",children:v.label}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:v.description})]},v.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 zcr({site:s,orgLabel:t}){var X;const{isAdmin:n}=_s(),r=Fcr(s.id),{data:a=[],isLoading:i}=Lcr(s.id),l=Rcr(s.id),o=Dcr(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),[v,y]=j.useState(s.org_logo_dark_url||null),[b,w]=j.useState(s.org_profile||{}),S=(ae,le)=>w(re=>({...re,[ae]:le})),A=b.offices||[],E=(ae,le)=>S("offices",A.map((re,te)=>te===ae?{...re,...le}:re)),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`,Z=`${G}?previewSlug=${s.subdomain_slug}`;return e.jsxs("div",{className:"space-y-6",children:[e.jsx(je,{children:e.jsxs(St,{className:"flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsxs(Et,{className:"flex flex-wrap items-center gap-2",children:[s.org_name||s.site_title,e.jsx($e,{variant:s.is_active?"default":"secondary",children:s.is_active?"Live":"Preview"}),e.jsx($e,{variant:"outline",children:s.org_tier==="pro"?"Pro (IDX)":"Essential"})]}),e.jsx(Vn,{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:Z,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{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(jn,{checked:s.is_active,onCheckedChange:ae=>r.mutate({is_active:ae})})]})]})]})}),e.jsxs(pa,{defaultValue:"brand",children:[e.jsxs(ga,{className:"h-auto flex-wrap justify-start gap-1",children:[e.jsx(Xt,{value:"brand",children:"Identity"}),e.jsx(Xt,{value:"story",children:"Story"}),e.jsx(Xt,{value:"offices",children:"Offices"}),e.jsx(Xt,{value:"social",children:"Social"}),e.jsxs(Xt,{value:"agents",children:["Agents (",a.length,")"]}),e.jsx(Xt,{value:"domain",children:"Address"}),e.jsx(Xt,{value:"plan",children:"Plan"})]}),e.jsx(Qt,{value:"brand",className:"mt-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Brand & content"}),e.jsx(Vn,{children:"The look adapts to your colors, logo and chosen design."})]}),e.jsxs(Le,{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(hUe,{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(hUe,{label:"Logo for dark backgrounds",hint:"Optional — used in the footer and dark headers.",value:v,onChange:y,slot:"logo-dark",siteId:s.id,dark:!0})]}),e.jsx(hUe,{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:Pos.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:v||null,org_profile:b,brand_color:P,accent_color:D}),disabled:r.isPending,children:r.isPending?"Saving…":"Save changes"})]})]})}),e.jsx(Qt,{value:"story",className:"mt-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Your story"}),e.jsxs(Vn,{children:["This is your ",t," speaking — not any individual agent. It fills the About page and the homepage numbers."]})]}),e.jsxs(Le,{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,le)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:ae.value,onChange:re=>S("stats",I.map((te,J)=>J===le?{...te,value:re.target.value}:te)),placeholder:"$412M",className:"max-w-[140px]"}),e.jsx(pe,{value:ae.label,onChange:re=>S("stats",I.map((te,J)=>J===le?{...te,label:re.target.value}:te)),placeholder:"Sold last year"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>S("stats",I.filter((re,te)=>te!==le)),children:e.jsx(qn,{className:"h-4 w-4"})})]},le)),I.length<4&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>S("stats",[...I,{label:"",value:""}]),children:[e.jsx(cn,{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(Qt,{value:"offices",className:"mt-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Offices"}),e.jsx(Vn,{children:"These appear on your contact page and in the footer. The first one is your main office."})]}),e.jsxs(Le,{className:"space-y-5",children:[A.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No offices yet — add your main office so visitors can reach you."}),A.map((ae,le)=>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:le===0?"Main office":`Office ${le+1}`}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>S("offices",A.filter((re,te)=>te!==le)),children:e.jsx(qn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(pe,{value:ae.name||"",onChange:re=>E(le,{name:re.target.value}),placeholder:"Office name"}),e.jsx(pe,{value:ae.phone||"",onChange:re=>E(le,{phone:re.target.value}),placeholder:"Phone"}),e.jsx(pe,{value:ae.email||"",onChange:re=>E(le,{email:re.target.value}),placeholder:"Email"}),e.jsx(pe,{value:ae.hours||"",onChange:re=>E(le,{hours:re.target.value}),placeholder:"Mon–Fri 9–5"}),e.jsx(pe,{value:ae.address||"",onChange:re=>E(le,{address:re.target.value}),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(pe,{value:ae.city||"",onChange:re=>E(le,{city:re.target.value}),placeholder:"City"}),e.jsx(pe,{value:ae.state||"",onChange:re=>E(le,{state:re.target.value}),placeholder:"ST"}),e.jsx(pe,{value:ae.zip||"",onChange:re=>E(le,{zip:re.target.value}),placeholder:"ZIP"})]})]})]},le)),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>S("offices",[...A,{}]),children:[e.jsx(cn,{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(Qt,{value:"social",className:"mt-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Social profiles"}),e.jsxs(Vn,{children:["Your ",t," accounts — linked in the footer and on the contact page."]})]}),e.jsxs(Le,{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(Qt,{value:"agents",className:"mt-6",children:e.jsxs(je,{children:[e.jsxs(St,{className:"flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Et,{children:"Agent roster"}),e.jsx(Vn,{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(co,{className:`mr-2 h-4 w-4 ${l.isPending?"animate-spin":""}`})," Refresh from LevelUp"]})]}),e.jsx(Le,{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 le,re,te,J;return e.jsxs("div",{className:"flex flex-wrap items-center gap-4 rounded-lg border p-4",children:[(le=ae.profile)!=null&&le.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:((re=ae.profile)==null?void 0:re.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(ei,{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(Ta,{className:"mr-2 h-4 w-4"}):e.jsx(Nx,{className:"mr-2 h-4 w-4"}),ae.is_visible?"Shown":"Hidden"]})]},ae.id)})})]})}),e.jsx(Qt,{value:"domain",className:"mt-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Web address"}),e.jsx(Vn,{children:"Use the free address or point your own domain at the site."})]}),e.jsxs(Le,{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(Qt,{value:"plan",className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsxs(je,{className:s.org_tier==="essential"?"border-primary":"",children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Essential"}),e.jsx(Vn,{children:"Everything except live MLS search."})]}),e.jsxs(Le,{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(je,{className:s.org_tier==="pro"?"border-primary":"",children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-4 w-4"})," Pro"]}),e.jsx(Vn,{children:"Everything in Essential, plus live MLS."})]}),e.jsxs(Le,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Admin: plan control"}),e.jsx(Vn,{children:"Switch this site between Essential and Pro."})]}),e.jsxs(Le,{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 wEt={agent:cl,brokerage:wi,team:Yn};function Los({current:s,className:t}){const n=Zn(),{websites:r}=Mos();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=wEt[(a==null?void 0:a.kind)||"agent"];return e.jsx("div",{className:t,children:e.jsxs(Bu,{children:[e.jsx($u,{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(kw,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})}),e.jsxs(Cu,{align:"start",className:"w-[320px]",children:[e.jsx(_L,{children:"Switch website"}),r.map(l=>{const o=wEt[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($e,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Preview"}):e.jsx($e,{variant:"outline",className:"shrink-0 text-[10px]",children:"Not created"}),c&&e.jsx(ma,{className:"h-4 w-4 shrink-0"})]},`${l.kind}-${l.ownerId||"me"}`)}),e.jsx(P0,{}),e.jsxs(ja,{onSelect:()=>n("/websites"),className:"gap-3",children:[e.jsx(Xf,{className:"h-4 w-4 text-muted-foreground"})," See all my websites"]})]})]})})}function Bcr(){const s=Zn(),[t]=Nc(),{data:n=[],isLoading:r}=Eae(),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(Los,{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(Flt,{teamId:l.teamId,orgLabel:"team"}):e.jsx(je,{children:e.jsx(Le,{className:"p-8 text-center text-sm text-muted-foreground",children:"Only team leaders can build a team website."})})]})})}function $cr(){const{user:s,isAdmin:t,isBrokerageManager:n,rolesLoading:r,brokerageId:a,managedBrokerages:i,selectedBrokerageId:l}=_s(),o=Zn(),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(Los,{current:{kind:"brokerage",ownerId:c}}),e.jsx(Flt,{brokerageId:c,orgLabel:"brokerage"})]})})}const jEt={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 Ucr({open:s,onOpenChange:t,plan:n,onSave:r,saving:a}){const[i,l]=j.useState(jEt);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}:jEt)},[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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-h-[90vh] overflow-y-auto sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsx($s,{children:n?"Edit commission plan":"New commission plan"}),e.jsx(Er,{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(jn,{checked:i.is_active,onCheckedChange:d=>o("is_active",d)})]})]}),e.jsxs(Nr,{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 NEt=()=>new Date().toISOString().slice(0,10);function qcr({open:s,onOpenChange:t,agent:n,plans:r,onAssign:a,saving:i}){const[l,o]=j.useState(""),[c,d]=j.useState(NEt()),[u,h]=j.useState(""),[m,f]=j.useState("");return j.useEffect(()=>{var g,x,v,y,b;s&&(o(((g=n==null?void 0:n.plan)==null?void 0:g.id)||((x=r[0])==null?void 0:x.id)||""),d(((v=n==null?void 0:n.assignment)==null?void 0:v.start_date)||NEt()),h(((y=n==null?void 0:n.assignment)==null?void 0:y.anniversary_date)||""),f(((b=n==null?void 0:n.assignment)==null?void 0:b.notes)||""))},[s,n,r]),e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs($s,{children:[n!=null&&n.assignment?"Change plan":"Assign plan"," — ",n==null?void 0:n.name]}),e.jsx(Er,{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(Nr,{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 lFe=q,_Ae={monthly_fee:"Monthly desk fee",transaction_fee:"Transaction fee",adjustment:"Adjustment",payment:"Payment received"};function Vcr(s){return st({queryKey:["fee-ledger",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await lFe.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 Hcr(s){const t=Zt(),{user:n}=_s();return mt({mutationFn:async r=>{const{error:a}=await lFe.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]}),ne.success("Ledger entry added")},onError:r=>ne.error(r.message||"Could not add entry")})}function Gcr(s){const t=Zt();return mt({mutationFn:async n=>{const{error:r}=await lFe.from("agent_fee_ledger").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),ne.success("Entry removed")},onError:n=>ne.error(n.message||"Could not remove entry")})}function Wcr(s){const t=Zt(),{user:n}=_s();return mt({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 lFe.from("agent_fee_ledger").insert(l);if(o)throw o;return l.length},onSuccess:r=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),ne.success(r?`Posted ${r} desk fee${r===1?"":"s"}`:"All desk fees already posted")},onError:r=>ne.error(r.message||"Could not post desk fees")})}const Kcr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ros(s,t){return s.filter(n=>{const r=MC(n.actual_close_date);return!!r&&r.y===t})}function Dos(s,t,n,r=[]){const a=Ros(s,n),i=Array.from({length:12},(c,d)=>({key:`${n}-${String(d+1).padStart(2,"0")}`,label:Kcr[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=kW(c),u=SW(c),h=Cne(c),m=Math.max(0,u-h);o.volume+=d,o.gci+=u,o.companyDollar+=h,o.agentShare+=m;const f=MC(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 Ycr=[64,110,113],mUe=[42,76,100],MM=[110,118,125],_j=s=>`$${Math.round(s).toLocaleString("en-US")}`,kEt=s=>{const t=MC(s);return t?`${String(t.m).padStart(2,"0")}/${String(t.d).padStart(2,"0")}/${String(t.y).slice(2)}`:"—"},SEt=(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 Zcr(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(...mUe),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(...MM);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((y,b)=>{const w=SW(b),S=Cne(b);return y.volume+=kW(b),y.gci+=w,y.company+=S,y.agent+=Math.max(0,w-S),y},{volume:0,gci:0,company:0,agent:0}),c=s.ledger.filter(y=>y.entry_type!=="payment").reduce((y,b)=>y+(Number(b.amount)||0),0),d=s.ledger.filter(y=>y.entry_type==="payment").reduce((y,b)=>y+Math.abs(Number(b.amount)||0),0),u=c-d,h=[{label:"Closed sides",value:String(s.deals.length)},{label:"Volume",value:_j(o.volume)},{label:"Gross commission",value:_j(o.gci)},{label:"Agent share",value:_j(o.agent)}],m=(n-a*2-18)/4;if(h.forEach((y,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(...MM),t.text(y.label,w+10,i+17),t.setFontSize(13),t.setFont("helvetica","bold"),t.setTextColor(...mUe),t.text(y.value,w+10,i+36),t.setFont("helvetica","normal")}),i+=72,s.capAmount){const y=Math.min(100,(s.capProgress||0)/s.capAmount*100);t.setFontSize(9),t.setTextColor(...MM),t.text(`Cap progress: ${_j(s.capProgress||0)} of ${_j(s.capAmount)} (${Math.round(y)}%)`,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(...Ycr),t.roundedRect(a,i+6,Math.max(2,b*y/100),7,3.5,3.5,"F"),i+=34}const f=y=>{i>r-120&&(t.addPage(),i=60),t.setFont("helvetica","bold"),t.setFontSize(11),t.setTextColor(...mUe),t.text(y,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(...MM),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(...MM),t.text("No closed transactions in this period.",a,i),i+=18,t.setTextColor(30,34,38)),s.deals.slice().sort((y,b)=>(y.actual_close_date||"").localeCompare(b.actual_close_date||"")).forEach(y=>{i>r-90&&(t.addPage(),i=60);const b=SW(y),w=Math.max(0,b-Cne(y));t.text(kEt(y.actual_close_date),x[0],i),t.text(SEt(t,y.property_address||y.deal_name||"Transaction",205),x[1],i),t.text(_j(kW(y)),x[2],i,{align:"right"}),t.text(_j(b),x[3],i,{align:"right"}),t.text(_j(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(_j(o.volume),x[2],i,{align:"right"}),t.text(_j(o.gci),x[3],i,{align:"right"}),t.text(_j(o.agent),n-a,i,{align:"right"}),t.setFont("helvetica","normal"),i+=34,f("Fees & payments"),t.setFontSize(8),t.setTextColor(...MM),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(...MM),t.text("No fees or payments recorded.",a,i),i+=18,t.setTextColor(30,34,38)),s.ledger.slice().sort((y,b)=>(y.entry_date||"").localeCompare(b.entry_date||"")).forEach(y=>{i>r-90&&(t.addPage(),i=60);const b=Number(y.amount)||0,w=y.entry_type==="payment",S=_Ae[y.entry_type]||y.entry_type;t.text(kEt(y.entry_date),x[0],i),t.text(SEt(t,y.note?`${S} — ${y.note}`:S,330),x[1],i),t.text(`${w?"-":""}${_j(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(_j(u),n-a,i,{align:"right"});const v=t.getNumberOfPages();for(let y=1;y<=v;y++)t.setPage(y),t.setFont("helvetica","normal"),t.setFontSize(8),t.setTextColor(...MM),t.text("Estimated figures based on recorded transactions and plan terms. Not an accounting document.",a,r-28),t.text(`Page ${y} of ${v}`,n-a,r-28,{align:"right"});return t}function Xcr(s){const t=Zcr(s),n=s.agentName.replace(/[^a-z0-9]+/gi,"-").toLowerCase();t.save(`statement-${n}-${s.year}.pdf`)}const CEt=s=>`$${Math.round(s).toLocaleString()}`;function Qcr({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=MC(f.actual_close_date);g&&m.add(g.y)}),Array.from(m).sort((f,g)=>g-f)},[s,i]),d=j.useMemo(()=>Dos(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 v,y,b;const f=n.find(w=>w.agentId===m),g=d.agents.find(w=>w.userId===m),x=Ros(s,Number(l)).filter(w=>w.owner_user_id===m);Xcr({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:((v=f==null?void 0:f.plan)==null?void 0:v.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:((y=f==null?void 0:f.plan)==null?void 0:y.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(xn,{className:"h-24 w-full rounded-xl"}),e.jsx(xn,{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:Gf(d.volume)},{label:"Gross commission",value:Gf(d.gci)},{label:"Company dollar",value:Gf(d.companyDollar),accent:!0}].map(m=>e.jsx(je,{className:"border-border/60",children:e.jsxs(Le,{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(je,{className:"border-border/60",children:[e.jsxs(St,{className:"pb-2",children:[e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(Zl,{className:"h-4 w-4 text-teal-600"})," Company dollar by month"]}),e.jsx(Vn,{children:"Brokerage split, franchise fees and transaction fees on closed deals"})]}),e.jsx(Le,{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:Gf(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}: ${CEt(m.companyDollar)} from ${m.deals} closed`}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:m.label})]},m.key))})})]}),e.jsxs(je,{className:"border-border/60",children:[e.jsxs(St,{className:"pb-2",children:[e.jsx(Et,{className:"text-base",children:"Agent production & statements"}),e.jsx(Vn,{children:"Download a per-agent statement with closed deals, fees and balance"})]}),e.jsx(Le,{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(Ii,{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:Gf(m.volume)}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:Gf(m.gci)}),e.jsx("td",{className:"py-2.5 text-right font-medium tabular-nums text-teal-700",children:Gf(m.companyDollar)}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:m.balance>0?e.jsx($e,{variant:"outline",className:"border-amber-300 text-amber-700",children:CEt(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(a2,{className:"mr-1.5 h-4 w-4"})," Statement"]})})]},m.userId))})]})})})]})]})}const AEt=s=>`$${Math.round(s).toLocaleString()}`,Jcr=()=>new Date().toISOString().slice(0,10),edr=()=>new Date().toISOString().slice(0,7);function tdr({brokerageId:s,ledger:t,roster:n,loading:r}){const a=Hcr(s),i=Gcr(s),l=Wcr(s),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState("adjustment"),[f,g]=j.useState(""),[x,v]=j.useState(Jcr()),[y,b]=j.useState(""),[w,S]=j.useState(edr()),[A,E]=j.useState("all"),I=V=>{var G;return((G=n.find(Z=>Z.agentId===V))==null?void 0:G.name)||"Agent"},P=j.useMemo(()=>{const V=new Map;return t.forEach(G=>{const Z=Number(G.amount)||0,X=G.entry_type==="payment"?-Math.abs(Z):Z;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(()=>A==="all"?t:t.filter(V=>V.agent_user_id===A),[t,A]),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:y},{onSuccess:()=>{c(!1),g(""),b("")}})};return r?e.jsx(xn,{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(je,{className:"border-border/60",children:e.jsxs(Le,{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:Gf(R)})]})}),e.jsx(je,{className:"border-border/60",children:e.jsxs(Le,{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:Gf(D)})]})}),e.jsx(je,{className:"border-border/60",children:e.jsxs(Le,{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(je,{className:"border-border/60",children:[e.jsx(St,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(Et,{className:"text-base",children:"Fee ledger"}),e.jsx(Vn,{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(vv,{className:"mr-1.5 h-4 w-4"})," Post desk fees"]}),e.jsxs($,{size:"sm",onClick:()=>c(!0),children:[e.jsx(cn,{className:"mr-1.5 h-4 w-4"})," Add entry"]})]})]})}),e.jsxs(Le,{className:"space-y-3",children:[e.jsxs(ms,{value:A,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)?` · ${AEt(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($e,{variant:V.entry_type==="payment"?"secondary":"outline",children:_Ae[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"?"-":"",AEt(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(qn,{className:"h-4 w-4"})})})]},V.id))})]})})]})]}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Fs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Add ledger entry"}),e.jsx(Er,{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(_Ae).map(V=>e.jsx(Ge,{value:V,children:_Ae[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=>v(V.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Note (optional)"}),e.jsx(Rs,{rows:2,value:y,onChange:V=>b(V.target.value)})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:W,disabled:a.isPending||!d||!f,children:"Add entry"})]})]})})]})}const sdr={license:AJ,eo:Rm,anniversary:kx,birthday:Rg},ndr=[30,60,90,180];function rdr({records:s,roster:t,deals:n,loading:r}){const[a,i]=j.useState(90),l=j.useMemo(()=>t.map(v=>({agentId:v.agentId,name:v.name,avatarUrl:v.avatarUrl})),[t]),o=j.useMemo(()=>Tos(s,l,a),[s,l,a]),c=o.filter(v=>v.expired),d=o.filter(v=>!v.expired&&(v.kind==="license"||v.kind==="eo")),u=o.filter(v=>v.kind==="anniversary"||v.kind==="birthday"),h=j.useMemo(()=>{const v=new Map(s.map(y=>[y.agent_user_id,y]));return t.filter(y=>{const b=v.get(y.agentId);return!(b!=null&&b.license_expiration)||!(b!=null&&b.eo_expiration)})},[s,t]),m=new Date().getFullYear(),f=j.useMemo(()=>Dos(n,[],m,l).agents,[n,l,m]),g=j.useMemo(()=>mcr(s,l,f),[s,l,f]);if(r)return e.jsx("div",{className:"space-y-3",children:Array.from({length:3}).map((v,y)=>e.jsx(xn,{className:"h-32 w-full rounded-xl"},y))});const x=(v,y)=>{const b=sdr[v.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(Ii,{src:v.avatarUrl||void 0,alt:v.agentName}),e.jsx(za,{className:"text-[10px]",children:v.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:v.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"}),hcr[v.kind],v.detail?` · ${v.detail}`:""]})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("p",{className:"text-xs font-medium tabular-nums",children:Dlt(v.dueDate)}),v.expired?e.jsxs($e,{variant:"destructive",className:"mt-0.5 h-5 text-[10px]",children:[Math.abs(v.daysUntil)," days overdue"]}):e.jsx("p",{className:`text-[11px] ${v.daysUntil<=30?"font-medium text-amber-600":"text-muted-foreground"}`,children:v.daysUntil===0?"Today":`in ${v.daysUntil} days`})]})]},`${v.agentId}-${v.kind}-${y}`)};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(je,{className:"border-border/60",children:e.jsxs(Le,{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(Al,{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(je,{className:"border-border/60",children:e.jsxs(Le,{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(Su,{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(je,{className:"border-border/60",children:e.jsxs(Le,{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(Rm,{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:"}),ndr.map(v=>e.jsxs($,{size:"sm",variant:a===v?"default":"outline",onClick:()=>i(v),children:[v," days"]},v))]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs(je,{className:"border-border/60",children:[e.jsxs(St,{className:"pb-2",children:[e.jsx(Et,{className:"text-base",children:"License & E&O renewals"}),e.jsx(Vn,{children:"Expired items first, then everything due inside your window"})]}),e.jsx(Le,{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(je,{className:"border-border/60",children:[e.jsxs(St,{className:"pb-2",children:[e.jsx(Et,{className:"text-base",children:"Anniversaries & birthdays"}),e.jsx(Vn,{children:"Reach out before the day — retention lives here"})]}),e.jsx(Le,{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(je,{className:"border-border/60",children:[e.jsxs(St,{className:"pb-2",children:[e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(ph,{className:"h-4 w-4 text-teal-600"})," Production goals — ",m]}),e.jsx(Vn,{children:"Goal amounts come from each agent's record; progress uses closed volume this year"})]}),e.jsx(Le,{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(v=>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(Ii,{src:v.avatarUrl||void 0,alt:v.name}),e.jsx(za,{className:"text-[10px]",children:v.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:v.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[Gf(v.volume)," of ",Gf(v.goal)," · ",v.closedDeals," closed"]})]}),e.jsxs("span",{className:"shrink-0 text-sm font-semibold tabular-nums",children:[Math.round(v.pct),"%"]})]}),e.jsx(Yi,{value:Math.min(100,v.pct),className:"mt-2 h-1.5"})]},v.agentId))})]})]})}const rhe=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString()}`;function adr({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(()=>CW(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(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"max-h-[90vh] max-w-3xl overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:l.id?"Edit disbursement":"New disbursement"}),e.jsx(Er,{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(cn,{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(qn,{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:rhe(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:rhe(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:rhe(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:rhe(c.agentNet)})]})]}),e.jsxs(Nr,{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 fUe=[42,76,100],EEt=[64,110,113],pUe=[110,118,125],ahe=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString("en-US")}`,TEt=s=>{const t=MC(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 idr(s){const t=s.disbursement,n=CW(t),r=new Go({unit:"pt",format:"letter"}),a=r.internal.pageSize.getWidth(),i=r.internal.pageSize.getHeight(),l=48;r.setFillColor(...fUe),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 ${TEt(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(...pUe),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",TEt(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",ahe(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(...fUe),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?EEt:[25,30,35];r.setTextColor(g[0],g[1],g[2]),r.text(h,l,o),r.text(ahe(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(...fUe),r.text(`Pay to ${s.brokerageName}`,l+14,o),r.text(ahe(n.companyDollar+n.otherCharges),a-l-14,o,{align:"right"}),o+=24,r.setTextColor(...EEt),r.text(`Pay to ${s.agentName}`,l+14,o),r.text(ahe(n.agentNet),a-l-14,o,{align:"right"}),r.setFont("helvetica","normal"),o+=52,t.notes&&(r.setFontSize(9),r.setTextColor(...pUe),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(...pUe),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 odr(s){const t=(s.disbursement.property_address||s.agentName||"cda").replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,48);idr(s).save(`cda-${t}.pdf`)}const ldr=s=>{const t=s==null?"":String(s);return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t},vR=s=>Math.round(s*100)/100,cdr=["Date","Ref Number","Name","Account","Memo","Debit","Credit"];function ddr(s,t){const n=[];return s.forEach((r,a)=>{const i=CW(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:vR(i.gross)}),i.referral>0&&n.push({date:l,refNumber:o,name:r.referral_payee||"Referral partner",account:"Referral Fees",memo:d,debit:vR(i.referral),credit:""}),i.agentNet!==0&&n.push({date:l,refNumber:o,name:c,account:"Agent Commission Expense",memo:d,debit:vR(i.agentNet),credit:""}),i.franchiseFee>0&&n.push({date:l,refNumber:o,name:c,account:"Franchise Fees",memo:d,debit:vR(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?vR(-m):"",credit:m>0?vR(m):""})});const u=vR(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 udr(s){const t=[cdr.join(",")];return s.forEach(n=>t.push([n.date,n.refNumber,n.name,n.account,n.memo,n.debit,n.credit].map(ldr).join(","))),t.join(` `)}function hdr(s,t,n=`quickbooks-disbursements-${new Date().toISOString().slice(0,10)}.csv`){const r=new Blob([udr(ddr(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 mdr={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"},gUe=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString()}`,fdr=s=>{const t=MC(s);return t?`${t.m}/${t.d}/${String(t.y).slice(2)}`:"—"};function pdr({brokerageId:s,disbursements:t,deals:n,roster:r,brokerageName:a,loading:i}){const l=Xlr(s),o=Qlr(s),c=Jlr(s),[d,u]=j.useState(null),[h,m]=j.useState("all"),f=w=>{var S;return((S=r.find(A=>A.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,A)=>{const E=CW(A);return S.gross+=E.gross,S.company+=E.companyDollar+E.otherCharges,S.agent+=E.agentNet,A.status==="draft"&&(S.pending+=1),S},{gross:0,company:0,agent:0,pending:0}),[t]),v=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]),y=w=>{var A;const S=((A=r.find(E=>E.agentId===w.owner_user_id))==null?void 0:A.plan)||null;u(Zlr(w,S))},b=()=>{var w,S,A,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:((A=(S=r[0])==null?void 0:S.plan)==null?void 0:A.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(xn,{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(je,{className:"border-border/60",children:e.jsxs(Le,{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:Gf(x.gross)})]})}),e.jsx(je,{className:"border-border/60",children:e.jsxs(Le,{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:Gf(x.company)})]})}),e.jsx(je,{className:"border-border/60",children:e.jsxs(Le,{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:Gf(x.agent)})]})}),e.jsx(je,{className:"border-border/60",children:e.jsxs(Le,{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})]})})]}),v.length>0&&e.jsxs(je,{className:"border-border/60",children:[e.jsxs(St,{className:"pb-2",children:[e.jsx(Et,{className:"text-base",children:"Closed deals without a disbursement"}),e.jsx(Vn,{children:"Start a CDA prefilled from the deal and the agent's commission plan"})]}),e.jsx(Le,{className:"flex flex-wrap gap-2 pt-2",children:v.map(w=>e.jsxs($,{size:"sm",variant:"outline",onClick:()=>y(w),children:[e.jsx(Gq,{className:"mr-1.5 h-3.5 w-3.5"}),w.property_address||w.deal_name]},w.deal_id))})]}),e.jsxs(je,{className:"border-border/60",children:[e.jsxs(St,{className:"flex flex-row flex-wrap items-center justify-between gap-3 pb-2",children:[e.jsxs("div",{children:[e.jsx(Et,{className:"text-base",children:"Disbursement authorizations"}),e.jsx(Vn,{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(dUe).map(w=>e.jsx(Ge,{value:w,children:dUe[w]},w))]})]}),e.jsxs($,{size:"sm",variant:"outline",disabled:!g.length,onClick:()=>hdr(g,f),children:[e.jsx(ji,{className:"mr-1.5 h-4 w-4"})," QuickBooks CSV"]}),e.jsxs($,{size:"sm",disabled:!r.length,onClick:()=>u(b()),children:[e.jsx(cn,{className:"mr-1.5 h-4 w-4"})," New CDA"]})]})]}),e.jsxs(Le,{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=CW(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 ",fdr(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:gUe(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:gUe(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:gUe(S.agentNet)})]}),e.jsx($e,{variant:"secondary",className:mdr[w.status],children:dUe[w.status]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>odr({disbursement:w,brokerageName:a,agentName:f(w.agent_user_id)}),children:[e.jsx(Qr,{className:"mr-1.5 h-3.5 w-3.5"})," CDA"]}),e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{size:"icon",variant:"ghost",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Cu,{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(Vr,{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(t7,{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(qn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]},w.id)})]})]}),e.jsx(adr,{open:!!d,onOpenChange:w=>!w&&u(null),draft:d,roster:r,saving:l.isPending,onSave:w=>l.mutate(w,{onSuccess:()=>u(null)})})]})}const ihe=s=>`$${Math.round(s).toLocaleString()}`,gdr=()=>{var G;const{brokerageId:s,managedBrokerages:t,selectedBrokerageId:n}=_s(),r=j.useMemo(()=>{var Z;return n||((Z=t[0])==null?void 0:Z.id)||s},[n,t,s]),{data:a=[],isLoading:i}=cQn(r,!0),{data:l=[],isLoading:o}=hQn(r),c=dQn(r),d=mQn(r),u=fQn(r),{data:h=[],isLoading:m}=Ntt(r),{data:f=[],isLoading:g}=Vcr(r),{data:x=[],isLoading:v}=Sos(r),{data:y=[],isLoading:b}=kos(r),w=((G=t.find(Z=>Z.id===r))==null?void 0:G.name)||"Brokerage",[S,A]=j.useState(!1),[E,I]=j.useState(null),[P,R]=j.useState(!1),[D,O]=j.useState(null),U=a.filter(Z=>Z.is_active),W=l.filter(Z=>Z.assignment),V=W.reduce((Z,X)=>{var ae;return Z+(((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(je,{className:"border-border/60",children:e.jsxs(Le,{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(Aw,{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(je,{className:"border-border/60",children:e.jsxs(Le,{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(Yn,{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(je,{className:"border-border/60",children:e.jsxs(Le,{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(t7,{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:Gf(V)}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"expected across assigned agents"})]})]})})]}),e.jsxs(pa,{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(ga,{children:[e.jsx(Xt,{value:"agents",children:"Agents"}),e.jsx(Xt,{value:"plans",children:"Plans"}),e.jsx(Xt,{value:"company",children:"Company dollar"}),e.jsx(Xt,{value:"ledger",children:"Fees & statements"}),e.jsx(Xt,{value:"disbursements",children:"Disbursements"}),e.jsx(Xt,{value:"renewals",children:"Renewals & goals"})]})}),e.jsxs($,{size:"sm",onClick:()=>{I(null),A(!0)},children:[e.jsx(cn,{className:"mr-1.5 h-4 w-4"})," New plan"]})]}),e.jsx(Qt,{value:"agents",className:"space-y-2",children:e.jsxs(je,{className:"border-border/60",children:[e.jsxs(St,{className:"pb-2",children:[e.jsx(Et,{className:"text-base",children:"Agent plans & cap progress"}),e.jsx(Vn,{children:"Assign a plan to each agent — their new deals inherit the splits and fees automatically"})]}),e.jsx(Le,{className:"space-y-1 pt-2",children:o?Array.from({length:4}).map((Z,X)=>e.jsx(xn,{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(Z=>{var ae;const X=(ae=Z.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(Ii,{src:Z.avatarUrl||void 0,alt:Z.name}),e.jsx(za,{className:"text-[11px]",children:Z.name.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:Z.name}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:Z.email})]})]}),e.jsx("div",{className:"min-w-0 flex-1",children:Z.plan?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx($e,{variant:"secondary",className:"font-medium",children:Z.plan.name}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[Z.plan.agent_split_pct,"/",Math.max(0,100-Z.plan.agent_split_pct),Z.plan.cap_amount?` · ${Gf(Z.plan.cap_amount)} cap`:" · no cap"]})]}),Z.plan.cap_amount&&Z.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:[ihe(Z.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(Z),R(!0)},children:Z.assignment?"Change plan":"Assign plan"}),Z.assignment&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",title:"Remove plan",onClick:()=>u.mutate(Z.assignment.id),children:e.jsx(cV,{className:"h-4 w-4"})})]})]},Z.agentId)})})]})}),e.jsx(Qt,{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((Z,X)=>e.jsx(xn,{className:"h-44 w-full rounded-xl"},X))}):a.length===0?e.jsx(je,{className:"border-dashed",children:e.jsxs(Le,{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(Aw,{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),A(!0)},children:[e.jsx(cn,{className:"mr-1.5 h-4 w-4"})," Create plan"]})]})}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:a.map(Z=>e.jsxs(je,{className:`border-border/60 ${Z.is_active?"":"opacity-60"}`,children:[e.jsx(St,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx(Et,{className:"text-base",children:Z.name}),Z.description&&e.jsx(Vn,{className:"mt-1",children:Z.description})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!Z.is_active&&e.jsx($e,{variant:"outline",children:"Retired"}),e.jsxs($e,{variant:"secondary",children:["v",Z.version_no]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{I(Z),A(!0)},children:e.jsx(pi,{className:"h-4 w-4"})})]})]})}),e.jsxs(Le,{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:[Z.agent_split_pct,"/",Math.max(0,100-Z.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:Z.cap_amount?ihe(Z.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:Z.monthly_fee?ihe(Z.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:Z.transaction_fee?ihe(Z.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:Z.franchise_fee_pct?`${Z.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:Z.team_split_pct?`${Z.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)===Z.id}).length})]})]})]},Z.id))})}),e.jsx(Qt,{value:"company",children:e.jsx(Qcr,{deals:h,ledger:f,roster:l,brokerageName:w,loading:m||o})}),e.jsx(Qt,{value:"ledger",children:e.jsx(tdr,{brokerageId:r,ledger:f,roster:l,loading:g||o})}),e.jsx(Qt,{value:"renewals",children:e.jsx(rdr,{records:x,roster:l,deals:h,loading:v||o})}),e.jsx(Qt,{value:"disbursements",children:e.jsx(pdr,{brokerageId:r,disbursements:y,deals:h,roster:l,brokerageName:w,loading:b||o})})]})]}),e.jsx(Ucr,{open:S,onOpenChange:A,plan:E,saving:c.isPending,onSave:Z=>c.mutate(Z,{onSuccess:()=>A(!1)})}),e.jsx(qcr,{open:P,onOpenChange:R,agent:D,plans:U,saving:d.isPending,onAssign:Z=>d.mutate(Z,{onSuccess:()=>R(!1)})})]})};function xdr(){const[s,t]=j.useState(""),{data:n,isLoading:r}=st({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(y=>y.brokerage_id===f.id),x=h.filter(y=>y.brokerage_id===f.id),v=g.length>0?g.reduce((y,b)=>b.created_at>y?b.created_at:y,g[0].created_at):null;return{brokerage_id:f.id,brokerage_name:f.name,total_items:g.length,videos:g.filter(y=>y.content_type==="video").length,pdfs:g.filter(y=>y.content_type==="pdf").length,links:g.filter(y=>y.content_type==="link"||y.content_type==="canva_link").length,events:g.filter(y=>y.content_type==="event").length,graphics:g.filter(y=>y.content_type==="graphic").length,latest_item_date:v,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(Dm,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(Le,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(Le,{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(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(Le,{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(je,{children:e.jsx(Le,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(An,{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(fa,{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(Qr,{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(nu,{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(Wc,{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(Hc,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Dt,{className:"text-center",children:"Categories"}),e.jsx(Dt,{children:"Last Upload"})]})}),e.jsx(fi,{children:r?e.jsx(An,{children:e.jsx(wt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(An,{children:e.jsx(wt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(An,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wi,{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($e,{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:Js(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const ydr=[{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:"📉"}],MEt=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(Ef,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(Ef,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(Zp,{className:"h-4 w-4"})}],vdr=[{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:"📰"}],PEt=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),IEt={"luxury-dark":jrt,"modern-clean":Nrt,"bold-colorful":krt,editorial:Srt};function bdr(){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"]),[v,y]=j.useState("luxury-dark"),[b,w]=j.useState(!1),[S,A]=j.useState(""),[E,I]=j.useState(""),[P,R]=j.useState(""),[D,O]=j.useState(!1),[U,W]=j.useState(!1),[V,G]=j.useState([]),[Z,X]=j.useState("search"),ae=j.useRef({});j.useEffect(()=>{(async()=>{const{data:{user:Ee}}=await q.auth.getUser();if(!Ee)return;const{data:ke}=await q.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",Ee.id).single();if(ke){A(ke.name||""),R(ke.avatar_url||"");const Ie=ke.brokerages;I((Ie==null?void 0:Ie.name)||"")}})()},[]);const le=async()=>{var be;if(s.trim()){i(!0),o([]);try{const{data:Ee,error:ke}=await q.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(ke)throw ke;if(Ee.error)throw new Error(Ee.error);o(Ee.listings||[]),((be=Ee.listings)==null?void 0:be.length)===0&&ne.info("No listings found. Try a different search.")}catch(Ee){ne.error(Ee.message||"Search failed")}finally{i(!1)}}},re=be=>{var Ee;d(be),h(0),X("customize"),be.soldDate||(Ee=be.status)!=null&&Ee.toLowerCase().includes("sold")?f("just-sold"):f("just-listed")},te=be=>{x(Ee=>Ee.includes(be)?Ee.filter(ke=>ke!==be):[...Ee,be])},J=j.useCallback(async()=>{if(!(!c||g.length===0)){O(!0),G([]),X("generate");try{await new Promise(Ee=>setTimeout(Ee,500));const be=[];for(const Ee of g){const ke=`${v}-${Ee}`,Ie=ae.current[ke];if(!Ie)continue;const Fe=yI[Ee],Ne=await RG(Ie,{width:Fe.width,height:Fe.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});be.push({format:Ee,imageUrl:Ne})}G(be),ne.success(`Generated ${be.length} social post${be.length>1?"s":""}!`)}catch(be){ne.error(be.message||"Generation failed")}finally{O(!1)}}},[c,g,v,u,b,S,E,P,m]),ce=async()=>{if(!(!c||g.length===0)){O(!0),G([]),X("generate");try{const be={...c,photos:c.photos.length>0?[c.photos[u]]:[]},Ee=[];for(const ke of g){const{data:Ie,error:Fe}=await q.functions.invoke("generate-listing-social-post",{body:{listing:be,postType:m,format:ke,branding:b?{enabled:!0,agentName:S,brokerage:E}:{enabled:!1}}});if(Fe)throw Fe;if(Ie.error)throw new Error(Ie.error);Ee.push({format:ke,imageUrl:Ie.imageUrl})}G(Ee),ne.success(`Generated ${Ee.length} AI post${Ee.length>1?"s":""}!`)}catch(be){ne.error(be.message||"AI generation failed")}finally{O(!1)}}},ve=()=>U?ce():J(),fe=(be,Ee)=>{var Ie;const ke=document.createElement("a");ke.href=be,ke.download=`${((Ie=c==null?void 0:c.address)==null?void 0:Ie.replace(/\s+/g,"-"))||"listing"}-${m}-${Ee}.png`,document.body.appendChild(ke),ke.click(),document.body.removeChild(ke)},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(Dm,{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 ${Z==="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 ${Z==="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(wn,{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 ${Z==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Hc,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),Z==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(DUt,{})]}),e.jsx(Vn,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Le,{className:"space-y-4",children:[e.jsx(pa,{value:n,onValueChange:be=>r(be),children:e.jsxs(ga,{children:[e.jsxs(Xt,{value:"address",children:[e.jsx(ui,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Xt,{value:"mls",children:[e.jsx(Cp,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:s,onChange:be=>t(be.target.value),placeholder:n==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:be=>be.key==="Enter"&&le()}),e.jsxs($,{onClick:le,disabled:a||!s.trim(),children:[a?e.jsx(Ct,{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((be,Ee)=>{var ke;return e.jsx(je,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>re(be),children:e.jsx(Le,{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:(ke=be.photos)!=null&&ke[0]?e.jsx("img",{src:be.photos[0],alt:be.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:PEt(be.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:be.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[be.city,", ",be.state," ",be.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[be.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(C4,{className:"h-3 w-3"})," ",be.bedrooms]}),be.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(C0,{className:"h-3 w-3"})," ",be.bathrooms]}),be.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(qz,{className:"h-3 w-3"})," ",be.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($e,{variant:"outline",className:"text-[10px]",children:be.mlsNumber}),e.jsx($e,{variant:"outline",className:"text-[10px]",children:be.status})]})]})]})})},be.mlsNumber||Ee)})})]})]}),Z==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(je,{className:"lg:col-span-1",children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-base",children:"Selected Listing"})}),e.jsxs(Le,{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(be=>Math.max(0,be-1)),disabled:u===0,children:e.jsx(kd,{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(be=>Math.min(c.photos.length-1,be+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:PEt(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(Sx,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(je,{className:"lg:col-span-2",children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(Vn,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Le,{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(yd,{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(jn,{checked:U,onCheckedChange:W}),U&&e.jsx(Qx,{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(yd,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:vdr.map(be=>e.jsxs("button",{onClick:()=>y(be.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${v===be.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:be.preview}),e.jsx("span",{className:"text-sm font-medium",children:be.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:be.description})]},be.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:ydr.map(be=>e.jsxs("button",{onClick:()=>f(be.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${m===be.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:be.icon})," ",be.label]},be.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:MEt.map(be=>e.jsxs("button",{onClick:()=>te(be.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${g.includes(be.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[be.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:be.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:be.dimensions})]})]},be.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(jn,{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:be=>A(be.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:be=>I(be.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*(yI[g[0]||"instagram-square"].height/yI[g[0]||"instagram-square"].width)},children:(()=>{const be=IEt[v],Ee=g[0]||"instagram-square";return e.jsx(be,{...ue,format:Ee})})()})})]}),e.jsx($,{onClick:ve,disabled:g.length===0||D,size:"lg",className:"w-full gap-2",children:D?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin"})," Generating ",g.length," post",g.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[U?e.jsx(Qx,{className:"h-5 w-5"}):e.jsx(wn,{className:"h-5 w-5"}),"Generate ",g.length," Social Post",g.length>1?"s":"",U&&e.jsx($e,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),Z==="generate"&&e.jsxs("div",{className:"space-y-4",children:[D&&e.jsx(je,{children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Ct,{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(Sx,{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((be,Ee)=>{const ke=MEt.find(Ie=>Ie.value===be.format);return e.jsxs(je,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:be.imageUrl,alt:`${be.format} social post`,className:"w-full rounded"})}),e.jsxs(Le,{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:[ke==null?void 0:ke.icon,e.jsx("span",{className:"text-sm font-medium",children:ke==null?void 0:ke.label})]}),e.jsx($e,{variant:"outline",className:"text-[10px]",children:ke==null?void 0:ke.dimensions})]}),e.jsxs($,{size:"sm",className:"w-full gap-1.5",onClick:()=>fe(be.imageUrl,be.format),children:[e.jsx(ji,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ee)})})]})]}),Z==="generate"&&!U&&c&&ue&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:g.map(be=>{const Ee=IEt[v],ke=yI[be];return e.jsx("div",{style:{width:ke.width,height:ke.height},children:e.jsx(Ee,{ref:Ie=>{ae.current[`${v}-${be}`]=Ie},...ue,format:be})},`${v}-${be}`)})})]})})}function _dr(){return st({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 wdr(s){return st({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 jdr(){const s=Zt();return mt({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 Fos(){const s=Zt();return mt({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 Ndr(){const s=Zt();return mt({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 kdr(){const s=Zt();return mt({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 Sdr(){const s=Zt();return mt({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 Cdr(){const s=Zt();return mt({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 Adr(){const s=Zt();return mt({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 Edr(){const s=Zt();return mt({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 Tdr(){const s=Zt();return mt({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 Mdr(){return st({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 Pdr(s){return st({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 Oos(s){return st({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 Idr(){const s=Zt();return mt({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 Ldr(){const{user:s}=_s(),t=Zn(),{data:n,isLoading:r}=_dr(),a=jdr(),i=Fos(),l=Ndr(),[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});ne.success("Course created"),c(!1),u(""),m(""),g(!0),t(`/admin/lms/${b.id}`)}catch{ne.error("Failed to create course")}},v=async b=>{try{await i.mutateAsync({id:b.id,is_published:!b.is_published}),ne.success(b.is_published?"Course unpublished":"Course published")}catch{ne.error("Failed to update course")}},y=async b=>{if(await mo("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(b),ne.success("Course deleted")}catch{ne.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(af,{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(Gl,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs($,{onClick:()=>c(!0),children:[e.jsx(cn,{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(je,{className:"animate-pulse",children:e.jsxs(St,{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||[],A=S.length===0?"No access set":S.some(P=>P.access_type==="all")?"All agents":`${S.length} rule(s)`;return e.jsxs(je,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${b.id}`),children:[e.jsx(St,{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(Et,{className:"text-base truncate",children:b.title}),b.description&&e.jsx(Vn,{className:"mt-1 line-clamp-2",children:b.description})]}),e.jsx($e,{variant:b.is_published?"default":"secondary",className:"ml-2 shrink-0",children:b.is_published?"Published":"Draft"})]})}),e.jsxs(Le,{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(_x,{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(c2,{className:"h-3.5 w-3.5"}):e.jsx(Zz,{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(Yn,{className:"h-3.5 w-3.5"}),A]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsxs($,{size:"sm",variant:"ghost",onClick:P=>{P.stopPropagation(),v(b)},children:[b.is_published?e.jsx(Nx,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ta,{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(),y(b.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"})]})]})]},b.id)})}):e.jsx(je,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(_x,{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(cn,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Create New Course"}),e.jsx(Er,{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(jn,{checked:f,onCheckedChange:g})]})]}),e.jsxs(Nr,{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 Rdr(){const{courseId:s}=Wi(),t=Zn(),{data:n,isLoading:r}=wdr(s),a=Fos(),i=kdr(),l=Sdr(),o=Cdr(),c=Adr(),d=Edr(),u=Tdr(),{data:h}=st({queryKey:["all-brokerages"],queryFn:async()=>{const{data:at}=await q.from("brokerages").select("id, name").order("name");return at||[]}}),[m,f]=j.useState(null),[g,x]=j.useState(!1),[v,y]=j.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[b,w]=j.useState(null),[S,A]=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),[Z,X]=j.useState(!1),[ae,le]=j.useState(""),[re,te]=j.useState(""),[J,ce]=j.useState(""),[ve,fe]=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(Va,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const ue=n.modules||[],be=n.access||[],Ee=be.some(at=>at.access_type==="all"),ke=be.filter(at=>at.access_type==="brokerage").map(at=>at.brokerage_id),Ie=(h||[]).filter(at=>at.name.toLowerCase().includes(ae.toLowerCase())),Fe=at=>{const rt=new Set(E);rt.has(at)?rt.delete(at):rt.add(at),I(rt)},Ne=async()=>{if(!P)return null;W(!0),O(0);try{const{data:at,error:rt}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:P.name}});if(rt)throw new Error(rt.message);const{videoId:Ke,libraryId:Je}=at,{data:ft,error:gt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ke,libraryId:Je}});if(gt)throw new Error(gt.message);const es=new XMLHttpRequest;return await new Promise((Ht,as)=>{es.upload.onprogress=bs=>{bs.lengthComputable&&O(Math.round(bs.loaded/bs.total*100))},es.onload=()=>es.status>=200&&es.status<300?Ht():as(new Error(`Upload failed: ${es.status}`)),es.onerror=()=>as(new Error("Upload failed")),es.open("PUT",ft.uploadUrl),es.setRequestHeader("AccessKey",ft.apiKey),es.send(P)}),`https://iframe.mediadelivery.net/embed/${Je}/${Ke}`}catch(at){return console.error("Bunny upload error:",at),ne.error("Video upload failed"),null}finally{W(!1),O(0)}},Be=async()=>{if(v.title.trim())try{let at=v.video_url.trim()||void 0;if(P){const rt=await Ne();if(!rt)return;at=rt}await i.mutateAsync({course_id:n.id,title:v.title.trim(),description:v.description.trim()||void 0,video_url:at,text_content:v.text_content.trim()||void 0,duration_minutes:v.duration_minutes?parseInt(v.duration_minutes):void 0,sort_order:ue.length}),ne.success("Module added"),x(!1),y({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),R(null)}catch{ne.error("Failed to add module")}},Se=async()=>{if(m)try{let at=v.video_url.trim()||null;if(P){const rt=await Ne();if(!rt)return;at=rt}await l.mutateAsync({id:m.id,title:v.title.trim(),description:v.description.trim()||null,video_url:at,text_content:v.text_content.trim()||null,duration_minutes:v.duration_minutes?parseInt(v.duration_minutes):null}),ne.success("Module updated"),f(null),R(null)}catch{ne.error("Failed to update")}},Ae=async at=>{if(await mo("Delete this module?"))try{await o.mutateAsync(at),ne.success("Module deleted")}catch{ne.error("Failed to delete")}},Ce=async at=>{if(S.title.trim())try{await c.mutateAsync({module_id:at,title:S.title.trim(),resource_type:S.resource_type,url:S.url.trim()||void 0}),ne.success("Resource added"),w(null),A({title:"",resource_type:"link",url:""})}catch{ne.error("Failed to add resource")}},qe=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[{access_type:"all"}]}),ne.success("Access updated: All brokerages / all agents")}catch{ne.error("Failed to update access")}},ze=async at=>{const rt=be.filter(gt=>gt.access_type==="brokerage").map(gt=>gt.brokerage_id),Ke=rt.includes(at);let Je;Ke?Je=rt.filter(gt=>gt!==at):Je=[...rt,at];const ft=Je.map(gt=>({access_type:"brokerage",brokerage_id:gt}));try{await u.mutateAsync({courseId:n.id,accessRules:ft}),ne.success(Ke?"Brokerage removed":"Brokerage added")}catch{ne.error("Failed to update access")}},Ve=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[]}),ne.success("Access cleared")}catch{ne.error("Failed")}},ht=async(at,rt)=>{const Ke=rt==="up"?at-1:at+1;if(!(Ke<0||Ke>=ue.length))try{await Promise.all([l.mutateAsync({id:ue[at].id,sort_order:Ke}),l.mutateAsync({id:ue[Ke].id,sort_order:at})])}catch{ne.error("Failed to reorder")}},Qe=async()=>{try{await a.mutateAsync({id:n.id,title:re,description:J||null}),ne.success("Course updated"),fe(!1)}catch{ne.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(Va,{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($e,{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(c2,{className:"h-3.5 w-3.5"}):e.jsx(Zz,{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||""),fe(!0)},children:[e.jsx(pi,{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(()=>ne.success(n.is_published?"Unpublished":"Published")),children:[n.is_published?e.jsx(Nx,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ta,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(pa,{defaultValue:"modules",className:"w-full",children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"modules",children:"Modules"}),e.jsx(Xt,{value:"access",children:"Access & Permissions"}),e.jsx(Xt,{value:"settings",children:"Settings"})]}),e.jsxs(Qt,{value:"modules",className:"mt-6 space-y-4",children:[ue.map((at,rt)=>e.jsxs(je,{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(at.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(),ht(rt,"up")},disabled:rt===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(xb,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:Ke=>{Ke.stopPropagation(),ht(rt,"down")},disabled:rt===ue.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(wl,{className:"h-3.5 w-3.5"})})]})}),e.jsx($e,{variant:"outline",className:"shrink-0 font-mono text-xs",children:rt+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:at.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[at.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(fa,{className:"h-3 w-3"})," Video"]}),at.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Qr,{className:"h-3 w-3"})," Text"]}),at.duration_minutes&&e.jsxs("span",{children:[at.duration_minutes," min"]}),at.resources&&at.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(nu,{className:"h-3 w-3"})," ",at.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:Ke=>{var Je;Ke.stopPropagation(),f(at),y({title:at.title,description:at.description||"",video_url:at.video_url||"",text_content:at.text_content||"",duration_minutes:((Je=at.duration_minutes)==null?void 0:Je.toString())||""})},children:e.jsx(pi,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:Ke=>{Ke.stopPropagation(),Ae(at.id)},children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]})]}),E.has(at.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[at.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:at.description}),at.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:at.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:at.video_url})]}),at.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:at.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(at.id),A({title:"",resource_type:"link",url:""})},children:[e.jsx(cn,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),at.resources&&at.resources.length>0?e.jsx("div",{className:"space-y-1",children:at.resources.map(Ke=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx($e,{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(mr,{className:"h-3 w-3"})})]},Ke.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},at.id)),e.jsxs($,{variant:"outline",className:"w-full border-dashed",onClick:()=>{x(!0),y({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(cn,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(Qt,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Le,{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(cl,{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(jn,{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:ke.length===0?"No brokerages selected — agents won't see this course":`${ke.length} brokerage${ke.length!==1?"s":""} selected`})]}),ke.length>0&&e.jsx($,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:Ve,children:"Clear all"})]}),e.jsx(pe,{placeholder:"Search brokerages...",value:ae,onChange:at=>le(at.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Ie.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Ie.map(at=>{const rt=ke.includes(at.id);return e.jsxs("div",{className:Pt("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",rt?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>ze(at.id),children:[e.jsx("div",{className:Pt("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",rt?"bg-primary border-primary":"border-muted-foreground/30"),children:rt&&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(wi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:at.name}),rt&&e.jsx($e,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},at.id)})})]})]})]})}),e.jsxs(Qt,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(Le,{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(()=>ne.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(mr,{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(kv,{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 at=>{var Ke;const rt=(Ke=at.target.files)==null?void 0:Ke[0];if(!(!rt||!n)){X(!0);try{const Je=rt.name.split(".").pop(),ft=`${n.id}/thumbnail.${Je}`,{error:gt}=await q.storage.from("lms-thumbnails").upload(ft,rt,{upsert:!0});if(gt)throw gt;const{data:es}=q.storage.from("lms-thumbnails").getPublicUrl(ft),Ht=`${es.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:Ht}),ne.success("Thumbnail uploaded")}catch{ne.error("Failed to upload thumbnail")}finally{X(!1),G.current&&(G.current.value="")}}}}),e.jsxs($,{variant:"outline",size:"sm",disabled:Z,onClick:()=>{var at;return(at=G.current)==null?void 0:at.click()},children:[Z?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-2"}),Z?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Course Settings"})}),e.jsxs(Le,{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(jn,{checked:n.is_sequential,onCheckedChange:at=>a.mutateAsync({id:n.id,is_sequential:at}).then(()=>ne.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(jn,{checked:n.is_published,onCheckedChange:at=>a.mutateAsync({id:n.id,is_published:at}).then(()=>ne.success("Updated"))})]})]})]})]})]})]}),e.jsx(Os,{open:g||!!m,onOpenChange:at=>{at||(x(!1),f(null))},children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx($s,{children:m?"Edit Module":"Add Module"}),e.jsx(Er,{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:v.title,onChange:at=>y(rt=>({...rt,title:at.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{value:v.description,onChange:at=>y(rt=>({...rt,description:at.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 at;return(at=V.current)==null?void 0:at.click()},children:[e.jsx("input",{ref:V,type:"file",accept:"video/*",className:"hidden",onChange:at=>{var Ke;const rt=(Ke=at.target.files)==null?void 0:Ke[0];rt&&(R(rt),y(Je=>({...Je,video_url:""})))}}),P?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(fa,{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:at=>{at.stopPropagation(),R(null)},children:e.jsx(mr,{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(Ct,{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:v.video_url,onChange:at=>y(rt=>({...rt,video_url:at.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Text Content"}),e.jsx(Rs,{value:v.text_content,onChange:at=>y(rt=>({...rt,text_content:at.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:v.duration_minutes,onChange:at=>y(rt=>({...rt,duration_minutes:at.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>{x(!1),f(null),R(null)},children:"Cancel"}),e.jsxs($,{onClick:m?Se:Be,disabled:!v.title.trim()||U,children:[U?e.jsx(Ct,{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(Os,{open:!!b,onOpenChange:at=>{at||w(null)},children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Add Resource"}),e.jsx(Er,{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:at=>A(rt=>({...rt,title:at.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Type"}),e.jsxs(ms,{value:S.resource_type,onValueChange:at=>A(rt=>({...rt,resource_type:at})),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:at=>A(rt=>({...rt,url:at.target.value})),placeholder:"https://..."})]})]}),e.jsxs(Nr,{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(Os,{open:ve,onOpenChange:fe,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Edit Course"}),e.jsx(Er,{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:re,onChange:at=>te(at.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{value:J,onChange:at=>ce(at.target.value),rows:3})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>fe(!1),children:"Cancel"}),e.jsx($,{onClick:Qe,disabled:!re.trim(),children:"Save"})]})]})})]})}function Ddr(){return st({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await q.rpc("get_lms_stats");if(t)throw t;return s}})}function Fdr(){return st({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 Odr(s){return st({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 zdr(){const s=Zn(),{data:t,isLoading:n}=Ddr(),{data:r,isLoading:a}=Fdr(),[i,l]=j.useState(null),{data:o,isLoading:c}=Odr(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,v;return!d||((x=g.agent_name)==null?void 0:x.toLowerCase().includes(d.toLowerCase()))||((v=g.email)==null?void 0:v.toLowerCase().includes(d.toLowerCase()))}),f=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:_x,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:Vr,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:Yn,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:Zl,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:Gl,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(Va,{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(af,{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(je,{className:Pt("transition-all",n&&"animate-pulse"),children:e.jsxs(Le,{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(Gl,{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(je,{className:"animate-pulse",children:e.jsx(Le,{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(je,{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(Le,{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($e,{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(je,{className:"border-dashed",children:e.jsx(Le,{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(u2,{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(je,{className:"animate-pulse",children:e.jsx(Le,{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 v=g.completion_pct>=100;return e.jsx(je,{className:Pt("transition-all",v&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Le,{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(Ii,{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}),v&&e.jsxs($e,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(Vr,{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(ca,{className:"h-3 w-3"}),Js(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",v?"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(je,{className:"border-dashed",children:e.jsx(Le,{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(je,{className:"border-dashed",children:e.jsxs(Le,{className:"py-16 text-center",children:[e.jsx(Yn,{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 Bdr(){const{user:s}=_s(),t=Zn(),{data:n,isLoading:r}=Mdr();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(af,{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(je,{className:"animate-pulse",children:e.jsxs(Le,{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($dr,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(je,{className:"border-dashed",children:e.jsxs(Le,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(_x,{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 $dr({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=Oos(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(je,{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(af,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(Le,{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(_x,{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(c2,{className:"h-3.5 w-3.5"}):e.jsx(Zz,{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 Udr(){const{courseId:s}=Wi(),t=Zn(),{user:n}=_s(),{data:r,isLoading:a}=Pdr(s),{data:i}=Oos(s),l=Idr(),[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}),ne.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 A=b.match(/(?:iframe\.mediadelivery\.net|video\.bunnycdn\.com)\/(?:play|embed)\/(\d+)\/([a-f0-9-]+)/);return A?`https://iframe.mediadelivery.net/embed/${A[1]}/${A[2]}?responsive=true`: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(Va,{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(je,{className:"lg:sticky lg:top-4",children:e.jsxs(Le,{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(go,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((b,w)=>{const S=x(b,w),A=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(jc,{className:"h-4 w-4 text-muted-foreground"}):A?e.jsx(Vr,{className:"h-4 w-4 text-green-500"}):e.jsx(Dg,{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(ca,{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(je,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:y(f.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(je,{children:e.jsxs(Le,{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($e,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(Vr,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs($,{size:"sm",onClick:v,disabled:l.isPending,children:[e.jsx(Vr,{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(Qr,{className:"h-4 w-4 text-red-500 shrink-0"}):b.resource_type==="template"?e.jsx(af,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(nu,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:b.title}),e.jsx(Ir,{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(Va,{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($e,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(je,{children:e.jsx(Le,{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(Va,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function qdr({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(Fr.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(Fr.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(Fr.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(Fr.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(Fr.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(Qa,{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(Fr.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 I2({children:s,className:t="",delay:n=0,direction:r="up"}){const a=j.useRef(null),i=KBs(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(Fr.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 Vdr({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(I2,{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(I2,{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 Hdr({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(I2,{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(Yn,{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(I2,{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(mr,{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 Gdr({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(I2,{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(I2,{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(d2,{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 Wdr({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(I2,{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(I2,{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(Qa,{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(Tf,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function Kdr({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(I2,{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(jc,{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(I2,{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(nK,{mode:"wait",children:[o===1&&e.jsxs(Fr.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(Qa,{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(Fr.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(Va,{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(Qa,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(Fr.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(Va,{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(ma,{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(Tf,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(no,{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 Ydr({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(""),[v,y]=j.useState(!1),[b,w]=j.useState(!1),S=s.commission_split_pct??80,A=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,Z=U*(V/100)-G*12-P*W,X=1-S/100,ae=X>0?A/X:U,le=Math.min(U,ae),re=Math.max(0,U-ae),te=le*X+re*(1-E/100),J=U-te-I*12-P*W,ce=J-Z;return{currentNet:Z,newNet:J,diff:ce}},[l,c,u,m,S,A,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:A,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),y(!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(I2,{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(jc,{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(I2,{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(r2,{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(Zl,{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(Fr.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&&!v&&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"})]})]}),v&&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(ma,{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 Zdr({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(I2,{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(a2,{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(jc,{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(ma,{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(a2,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function Xdr(){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}=st({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}=st({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=mt({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(wi,{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)||[],v=(h==null?void 0:h.gallery_images)||[],y=(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)||{},A=(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(Fr.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(ma,{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(Qa,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(qdr,{headline:y,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(Vdr,{benefits:g,accentColor:f,primaryColor:m}),e.jsx(Hdr,{images:v,primaryColor:m,accentColor:f}),e.jsx(Gdr,{testimonials:x,primaryColor:m,accentColor:f}),w&&e.jsx(Ydr,{config:S,primaryColor:m,accentColor:f,brokerageId:l.id,brokerageName:l.name}),A&&e.jsx(Zdr,{config:E,primaryColor:m,accentColor:f,brokerageId:l.id}),I==="multi_step"?e.jsx(Kdr,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:f,showConfidentialBadges:P}):e.jsx(Wdr,{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 Qdr(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 Jdr(){var m,f,g,x;const{shareToken:s}=Wi(),t=j.useRef(!1),{data:n,isLoading:r,error:a}=st({queryKey:["public-recruit-video",s],queryFn:async()=>{var A;if(!s)throw new Error("No token");const{data:v,error:y}=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(y)throw y;const{data:b}=await q.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(A=v.video)==null?void 0:A.owner_user_id).single(),{data:w}=await q.from("brokerages").select("name").eq("id",v.brokerage_id).single(),{data:S}=await q.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",v.brokerage_id).maybeSingle();return{rv:v,profile:b,brokerage:w,settings:S}},enabled:!!s});if(j.useEffect(()=>{var v;!((v=n==null?void 0:n.rv)!=null&&v.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?Qdr(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(Dl,{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(Ea,{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 eur="relzejiswnotikjgvjhz",LEt=`https://${eur}.supabase.co/functions/v1/recruit-unsubscribe`;function tur(){const[s]=Nc(),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(y=>document.querySelectorAll(y).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(`${LEt}?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(LEt,{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(Ct,{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(vl,{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(Vr,{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(Rm,{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(Rm,{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(Ct,{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 sur="relzejiswnotikjgvjhz",REt=`https://${sur}.supabase.co/functions/v1/event-invite-unsubscribe`;function nur(){const[s]=Nc(),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(`${REt}?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(REt,{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(Ct,{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(vl,{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(Vr,{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(Rm,{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(mJ,{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(Ct,{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 rur(){var R,D,O;const s=Zn(),t=Zt(),{isAdmin:n}=_s(),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState(null),{data:d,isLoading:u}=st({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}=st({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=mt({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:()=>{ne.success("Business updated"),t.invalidateQueries({queryKey:["google-business-status"]}),t.invalidateQueries({queryKey:["my-social-accounts"]})},onError:()=>ne.error("Could not update your business selection")}),f=mt({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"]}),ne.success("Google Business disconnected")},onError:()=>ne.error("Failed to disconnect Google Business")}),g=mt({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"]}),ne.success("Account disconnected successfully")},onError:()=>{ne.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),ne.error("Failed to start connection. Please try again."),a(!1)}},v=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),ne.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},y=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),ne.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 A=(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||[]),ne.success(V.summary||"API tests completed")}catch(V){console.error("Meta API test error:",V),ne.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($e,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(wn,{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(Va,{className:"h-4 w-4"}),"Back to Social Studio"]}),I&&e.jsx(je,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(Le,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(Wl,{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(je,{children:[e.jsx(St,{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(Zp,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:"Facebook"}),e.jsx(Vn,{children:"Connect your Facebook Page"})]})]})}),e.jsxs(Le,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(co,{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(Ii,{src:U.profile_picture_url||""}),e.jsx(za,{children:e.jsx(Zp,{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($e,{variant:U.is_active?"default":"secondary",className:"text-xs",children:U.is_active?"Connected":"Inactive"})]})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Disconnect Facebook?"}),e.jsx(ic,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{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(co,{className:"h-4 w-4 animate-spin"}):e.jsx(cn,{className:"h-4 w-4"}),b.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(je,{children:[e.jsx(St,{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(Ef,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:"Instagram"}),e.jsx(Vn,{children:"Connect your Instagram Business or Creator account"})]})]})}),e.jsxs(Le,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(co,{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(Ii,{src:U.profile_picture_url||""}),e.jsx(za,{children:e.jsx(Ef,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",U.platform_username||"Instagram Account"]}),e.jsx($e,{variant:U.is_active?"default":"secondary",className:"text-xs",children:U.is_active?"Connected":"Inactive"})]})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Disconnect Instagram?"}),e.jsx(ic,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{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(co,{className:"h-4 w-4 animate-spin"}):e.jsx(cn,{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(je,{children:[e.jsx(St,{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(ly,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:"LinkedIn"}),e.jsx(Vn,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Le,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(co,{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(Ii,{src:U.profile_picture_url||""}),e.jsx(za,{children:e.jsx(ly,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:U.platform_username||"LinkedIn Account"}),e.jsx($e,{variant:U.is_active?"default":"secondary",className:"text-xs",children:U.is_active?"Connected":"Inactive"})]})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Disconnect LinkedIn?"}),e.jsx(ic,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{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:v,disabled:r,className:"w-full gap-2",variant:S.length>0?"outline":"default",children:[r?e.jsx(co,{className:"h-4 w-4 animate-spin"}):e.jsx(cn,{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(je,{className:"relative overflow-hidden",children:[e.jsx(St,{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(ui,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:"Google Business"}),e.jsx(Vn,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Le,{className:"space-y-4",children:[(h==null?void 0:h.needsReconnect)&&A&&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(co,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):A?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(ui,{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($e,{variant:"default",className:"text-xs",children:"Connected"})]})]}),e.jsxs(fc,{children:[e.jsx(Ag,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Disconnect Google Business?"}),e.jsx(ic,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{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($e,{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:y,disabled:r,className:"w-full gap-2",variant:A&&!(h!=null&&h.needsReconnect)?"outline":"default",children:[r?e.jsx(co,{className:"h-4 w-4 animate-spin"}):e.jsx(cn,{className:"h-4 w-4"}),A?"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(je,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(St,{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(UI,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(Vn,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Le,{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(Zp,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(UI,{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(Ef,{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(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(UI,{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(Vr,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):U.status==="pending"?e.jsx(Ct,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(ju,{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(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"How it works"})}),e.jsx(Le,{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 aur(){const[s]=Nc(),t=Zn(),[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 y;const f=s.get("code"),g=s.get("error"),x=s.get("error_description"),v=s.get("state");if(g){r("error"),l(x||"Authorization was denied"),ne.error("Connection failed: "+(x||g));return}if(!f){r("error"),l("No authorization code received"),ne.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:v,callbackPath:"/social-connections/callback"}});if(w)throw w;if(b!=null&&b.success)r("success"),l(`Successfully connected ${((y=b.accounts)==null?void 0:y.length)||0} account(s)!`),ne.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),ne.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(je,{className:"w-full max-w-md",children:[e.jsxs(St,{className:"text-center",children:[n==="loading"&&e.jsx(Ct,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Wl,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ju,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Et,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:i})]}),e.jsxs(Le,{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 iur(){const[s]=Nc(),t=Zn();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(Ct,{className:"h-8 w-8 animate-spin text-primary"})})}function our(){const[s]=Nc(),t=Zn(),[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"),ne.error(u||"Failed to connect LinkedIn");return}if(!o){r("error"),i("No authorization code received"),ne.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`),ne.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"),ne.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(je,{className:"w-full max-w-md",children:[e.jsxs(St,{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(Ct,{className:"h-8 w-8 animate-spin text-blue-600"}),n==="success"&&e.jsx(Wl,{className:"h-8 w-8 text-green-600"}),n==="error"&&e.jsx(ju,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(Et,{className:"flex items-center justify-center gap-2",children:[e.jsx(ly,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Le,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/mission-control/integrations"),disabled:n==="loading",children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function lur(){const s=Zn(),[t,n]=j.useState(null),{data:r,isLoading:a}=eos(t||void 0,!0),{data:i,isLoading:l}=Elt(!0),{cartItems:o}=OLe(),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(xn,{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(xn,{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(eC,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx($e,{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(je,{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(ym,{className:"h-12 w-12 text-muted-foreground"})}),u.category&&e.jsx($e,{className:"absolute top-2 left-2",variant:"secondary",children:u.category.name})]}),e.jsxs(Le,{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(ym,{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 zos=j.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));zos.displayName="Breadcrumb";const Bos=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}));Bos.displayName="BreadcrumbList";const wAe=j.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:Pt("inline-flex items-center gap-1.5",s),...t}));wAe.displayName="BreadcrumbItem";const tQe=j.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?VJe:"a";return e.jsx(a,{ref:r,className:Pt("transition-colors hover:text-foreground",t),...n})});tQe.displayName="BreadcrumbLink";const $os=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}));$os.displayName="BreadcrumbPage";const sQe=({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,{})});sQe.displayName="BreadcrumbSeparator";function cur(){var W,V;const{productId:s}=Wi(),t=Zn(),{data:n,isLoading:r}=nor(s||""),{addToCart:a,cartItems:i}=OLe(),[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),[v,y]=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),A=b?Number(b.price_adjustment):0,E=S+A,I=Number((n==null?void 0:n.shipping_fee)||0),P=i.reduce((G,Z)=>G+Z.quantity,0),R=async G=>{if(!G.target.files||G.target.files.length===0)return;x(!0);const Z=G.target.files[0],X=Z.name.split(".").pop(),ae=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${X}`;try{const{error:le}=await q.storage.from("marketplace").upload(ae,Z);if(le)throw le;const{data:{publicUrl:re}}=q.storage.from("marketplace").getPublicUrl(ae);f(re),ne.success("Artwork uploaded successfully")}catch(le){ne.error("Failed to upload artwork: "+le.message)}finally{x(!1)}},D=()=>{if(n){if(w.length>0&&!l){ne.error("Please select an option");return}a(n,b||void 0,c,m||void 0),y(!0),ne.success("Added to cart!"),setTimeout(()=>y(!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(xn,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-8 w-3/4"}),e.jsx(xn,{className:"h-6 w-1/4"}),e.jsx(xn,{className:"h-24 w-full"}),e.jsx(xn,{className:"h-12 w-full"})]})]})}):n?e.jsxs(Vs,{title:n.name,children:[e.jsx(zos,{className:"mb-6",children:e.jsxs(Bos,{children:[e.jsx(wAe,{children:e.jsx(tQe,{asChild:!0,children:e.jsx(br,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(sQe,{}),e.jsx(wAe,{children:e.jsx(tQe,{asChild:!0,children:e.jsx(br,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(sQe,{}),e.jsx(wAe,{children:e.jsx($os,{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(kd,{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(ym,{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,Z)=>e.jsx("button",{onClick:()=>h(Z),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${Z===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(je,{children:e.jsxs(Le,{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($e,{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:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(ma,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(eC,{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(eC,{className:"h-5 w-5"}),P>0&&e.jsx($e,{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(ym,{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 dur(){const s=Zn(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=OLe(),[d,u]=j.useState(!1),[h,m]=j.useState(""),f=async()=>{if(t.length===0){ne.error("Your cart is empty");return}u(!0);try{const{data:g,error:x}=await q.functions.invoke("marketplace-checkout",{body:{items:t.map(v=>{var y;return{product_id:v.product.id,variant_id:((y=v.variant)==null?void 0:y.id)||null,quantity:v.quantity,artwork_url:v.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){ne.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(P4,{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,v;return e.jsx(je,{children:e.jsx(Le,{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(y=>y.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(P4,{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 y;return n(g.product.id,(y=g.variant)==null?void 0:y.id)},children:e.jsx(qn,{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 y;return r(g.product.id,(y=g.variant)==null?void 0:y.id,g.quantity-1)},disabled:g.quantity<=1,children:e.jsx(YN,{className:"h-3 w-3"})}),e.jsx(pe,{type:"number",value:g.quantity,onChange:y=>{var b;return r(g.product.id,(b=g.variant)==null?void 0:b.id,parseInt(y.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 y;return r(g.product.id,(y=g.variant)==null?void 0:y.id,g.quantity+1)},children:e.jsx(cn,{className:"h-3 w-3"})})]})]})]})})},`${g.product.id}-${((v=g.variant)==null?void 0:v.id)||"base"}`)}),e.jsx($,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(je,{className:"sticky top-4",children:[e.jsx(St,{children:e.jsx(Et,{children:"Order Summary"})}),e.jsxs(Le,{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(Vc,{}),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(Vc,{}),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(Ct,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(Qa,{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 uur(){const s=Zn(),{data:t,isLoading:n}=por();return n?e.jsx(Vs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(r=>e.jsx(xn,{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(ym,{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(je,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${r.id}`),children:e.jsxs(Le,{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:Js(new Date(r.created_at),"MMM d, yyyy")})]}),e.jsx($e,{className:Alt[r.status],children:qV[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(Ir,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(Di,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},r.id)})})})}const DEt=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function hur({currentStatus:s,statusHistory:t}){const n=DEt.indexOf(s);return e.jsx("div",{className:"space-y-3",children:DEt.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(Vr,{className:"h-4 w-4"}):o?e.jsx(ca,{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:qV[r]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Js(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},r)})})}function mur(){var y;const{orderId:s}=Wi(),t=Zn(),{data:n,isLoading:r,refetch:a}=gor(s||""),i=vor(),l=bor(),[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}),ne.success("Proof approved!"),a()}catch{ne.error("Failed to approve proof")}finally{g(null)}},v=async()=>{if(d){g(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:h}),ne.success("Revision requested"),c(!1),m(""),u(null),a()}catch{ne.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(xn,{className:"h-64 w-full"}),e.jsx(xn,{className:"h-48 w-full"})]}),e.jsx(xn,{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(je,{children:[e.jsxs(St,{className:"flex flex-row items-center justify-between",children:[e.jsx(Et,{children:"Order Status"}),e.jsx($e,{className:Alt[n.status],children:qV[n.status]})]}),e.jsx(Le,{children:e.jsx(hur,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Items"})}),e.jsx(Le,{className:"space-y-4",children:(y=n.items)==null?void 0:y.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($I,{className:"h-4 w-4"}),"View Artwork",e.jsx(Ir,{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($I,{className:"h-4 w-4"}),"View Proof",e.jsx(Ir,{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(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx($y,{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(JJ,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),b.proof_status==="approved"&&e.jsxs($e,{className:"bg-green-100 text-green-800",children:[e.jsx(Vr,{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($e,{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(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(eee,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Le,{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(Ir,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(je,{className:"sticky top-4",children:[e.jsx(St,{children:e.jsx(Et,{children:"Order Summary"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",Js(new Date(n.created_at),"MMMM d, yyyy")]}),e.jsx(Vc,{}),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(Vc,{}),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(Vc,{}),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(Os,{open:o,onOpenChange:c,children:e.jsxs(Fs,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Request Changes"}),e.jsx(Er,{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(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:!h.trim()||f!==null,children:[f?e.jsx(Ct,{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(ym,{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 fur(){const s=Zn(),[t]=Nc();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(je,{children:e.jsxs(Le,{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(Vr,{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(ym,{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(Qa,{className:"h-4 w-4 ml-2"})]}),e.jsx($,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function pur(){const{user:s}=_s(),[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,v]=j.useState(!1),[y,b]=j.useState(""),[w,S]=j.useState(null),[A,E]=j.useState(!1),{hasSubmittedReview:I,submitReview:P,markPostedToGoogle:R}=e7t(),{data:D}=sos(),{data:O,isLoading:U}=tos(),{data:W,isLoading:V}=Cor(r),{data:G,isLoading:Z}=Aor(s==null?void 0:s.id),{data:X=0}=Tor(s==null?void 0:s.id),ae=Mor(),le=new Set((G==null?void 0:G.map(ue=>ue.item_id))||[]),re=async()=>{if(i)try{const ue=await ae.mutateAsync(i.id);i.item_type==="reelflow_credits"?ne.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):ne.success(`Successfully purchased "${i.name}"!`),l(null)}catch(ue){ne.error(ue.message||"Failed to purchase item")}},te=async()=>{if(!h.trim()){ne.error("Please write a review");return}g(!0);const ue=await P(d,h);g(!1),ue.success?(ne.success("Thank you for your review! You earned 25 points!"),b(h),v(!0),m(""),u(5)):ne.error(ue.error||"Failed to submit review")},J=()=>{navigator.clipboard.writeText(y),ne.success("Review copied to clipboard!")},ce=()=>{R(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},ve=()=>{v(!1),c(!1),b("")};return U||V||Z?e.jsx(Vs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(xn,{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(xn,{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(je,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(Le,{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(ei,{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(sh,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(y1,{open:A,onOpenChange:E,children:e.jsxs(je,{className:"border-primary/20",children:[e.jsx(v1,{asChild:!0,children:e.jsx(St,{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(Et,{className:"text-base",children:"How to Earn Points"}),e.jsx(Vn,{children:"See all the ways you can earn spendable points"})]})]}),A?e.jsx(xb,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(wl,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(b1,{children:e.jsx(Le,{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 be=Ee=>{switch(Ee){case"event_attendance":return e.jsx(Ea,{className:"h-5 w-5"});case"leave_review":return e.jsx(ei,{className:"h-5 w-5"});case"add_listing":return e.jsx(va,{className:"h-5 w-5"});case"first_contact":return e.jsx(Yn,{className:"h-5 w-5"});case"first_video":return e.jsx(fa,{className:"h-5 w-5"});case"first_community_post":return e.jsx(no,{className:"h-5 w-5"});default:return e.jsx(dl,{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:be(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($e,{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(sh,{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($e,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!I&&e.jsx(je,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(Le,{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(no,{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(ei,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(pa,{value:t,onValueChange:n,children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"store",className:"flex items-center gap-2",children:[e.jsx(P4,{className:"h-4 w-4"}),"Store"]}),e.jsxs(Xt,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(ym,{className:"h-4 w-4"}),"My Rewards",G&&G.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1",children:G.length})]})]}),e.jsxs(Qt,{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(je,{children:e.jsx(Le,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(dl,{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 be=ue.item_type==="reelflow_credits",Ee=!be&&le.has(ue.id),ke=!be&&ue.max_quantity!==null&&ue.current_quantity===0,Ie=X>=ue.points_cost;return e.jsxs(je,{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($e,{className:"bg-green-500 text-white",children:[e.jsx(Vr,{className:"h-3 w-3 mr-1"}),"Owned"]})}),ke&&!Ee&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx($e,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(dl,{className:"h-12 w-12 text-muted-foreground/50"}),Ee&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs($e,{className:"bg-green-500 text-white",children:[e.jsx(Vr,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(St,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(Et,{className:"text-lg",children:ue.name}),e.jsxs($e,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(ei,{className:"h-3 w-3 mr-1"}),ue.points_cost]})]}),ue.category&&e.jsxs($e,{variant:"outline",className:"w-fit",children:[ue.category.icon&&`${ue.category.icon} `,ue.category.name]})]}),e.jsxs(Le,{children:[e.jsx(Vn,{className:"mb-4 line-clamp-2",children:ue.description||"No description available"}),ue.max_quantity!==null&&!Ee&&!be&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[ue.current_quantity," of ",ue.max_quantity," remaining"]}),be&&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&&lUe(ue.file_url,ue.name)},disabled:!ue.file_url,children:ue.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx($,{className:"w-full",onClick:Fe=>{Fe.stopPropagation(),l(ue)},disabled:ke||!Ie,children:ke?"Sold Out":Ie?e.jsxs(e.Fragment,{children:[e.jsx(P4,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${ue.points_cost-X} more pts`})]})]},ue.id)})})]}),e.jsx(Qt,{value:"my-rewards",className:"mt-6",children:!G||G.length===0?e.jsx(je,{children:e.jsx(Le,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(ym,{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 be,Ee,ke,Ie,Fe,Ne,Be;return e.jsxs(je,{className:"overflow-hidden",children:[(be=ue.item)!=null&&be.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(dl,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(St,{className:"pb-2",children:[e.jsx(Et,{className:"text-lg",children:((ke=ue.item)==null?void 0:ke.name)||"Unknown Item"}),e.jsxs(Vn,{className:"text-xs",children:["Purchased for ",ue.points_spent," points • ",new Date(ue.purchased_at).toLocaleDateString()]})]}),e.jsx(Le,{children:((Ie=ue.item)==null?void 0:Ie.item_type)==="reelflow_credits"?e.jsxs($,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(Vr,{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 Se,Ae;(Se=ue.item)!=null&&Se.file_url&&lUe(ue.item.file_url,(Ae=ue.item)==null?void 0:Ae.name)},disabled:!((Ne=ue.item)!=null&&Ne.file_url),children:((Be=ue.item)==null?void 0:Be.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},ue.id)})})})]})]}),e.jsx(fc,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Confirm Purchase"}),e.jsxs(ic,{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(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:re,disabled:ae.isPending,children:ae.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(Os,{open:o,onOpenChange:ue=>{!ue&&x?ve():c(ue)},children:e.jsx(Fs,{children:x?e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(Er,{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:['"',y,'"']})]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:J,children:[e.jsx(Za,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(Nr,{className:"flex-col sm:flex-row gap-2",children:[e.jsx($,{variant:"outline",onClick:ve,children:"Maybe Later"}),e.jsxs($,{onClick:ce,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Leave a Review"}),e.jsx(Er,{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(ei,{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(Nr,{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(Os,{open:!!w,onOpenChange:()=>S(null),children:e.jsxs(Fs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[w==null?void 0:w.name,e.jsxs($e,{variant:"secondary",className:"font-bold",children:[e.jsx(ei,{className:"h-3 w-3 mr-1"}),w==null?void 0:w.points_cost]})]}),(w==null?void 0:w.category)&&e.jsxs($e,{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&&!le.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(Nr,{children:w&&w.item_type!=="reelflow_credits"&&le.has(w.id)?e.jsx($,{className:"w-full",onClick:()=>{w.file_url&&lUe(w.file_url,w.name)},disabled:!w.file_url,children:w.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ir,{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&&Z()},[s==null?void 0:s.id]);const Z=async()=>{if(!s)return;o(!0),y(!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:Ne}=await q.from("profiles").select("name").eq("id",s.id).maybeSingle();Ne!=null&&Ne.name&&w(Ne.name);let{data:Be}=await q.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Be){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&&(Be=qe)}i((Be==null?void 0:Be.code)??null);const{data:Se}=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(Se&&Se.length>0){const Ae=Se.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(Se.map(ze=>({...ze,referred_profile:qe.get(ze.referred_user_id)??null})))}else d([]);o(!1)},X=j.useMemo(()=>a?`${gur}/trial?ref=${a}`:"",[a]),ae=c.length,le=c.filter(Fe=>Fe.status==="qualified").length,re=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),ne.success("Referral link copied!"))},J=()=>{const Fe=encodeURIComponent("Join me on LevelUp"),Ne=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=${Ne}`},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}`},ve=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()},fe=Fe=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Fe.trim()),ue=Fe=>{const Ne=(Fe??E).trim().replace(/,$/,"");if(!Ne)return;const Be=Ne.split(/[\s,;]+/).filter(Boolean),Se=[...P];let Ae=0;for(const Ce of Be){if(!fe(Ce)){ne.error(`Invalid email: ${Ce}`);continue}Se.includes(Ce)||(Se.push(Ce),Ae++)}R(Se),Ae>0&&I("")},be=Fe=>R(P.filter(Ne=>Ne!==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."),A(!0)},ke=Fe=>{const Ne=Fe.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Be=b||"A fellow agent",Se="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",Ae=X;return`
LevelUp
You're Invited

${Be} thinks you'd love LevelUp 🎉

${Ne}

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 ${Be} via LevelUp · relevelup.com

`.trim()},Ie=async()=>{if(P.length===0&&(E.trim()&&ue(),P.length===0)){ne.error("Add at least one recipient");return}if(!U.trim()){ne.error("Subject is required");return}G(!0);const Fe=ke(D);let Ne=0,Be=0;for(const Se of P)try{const{data:Ae,error:Ce}=await q.functions.invoke("gmail-send",{body:{to:Se,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));Ne++}catch(Ae){console.error("Gmail send failed for",Se,Ae),Be++}G(!1),Ne>0?(ne.success(`Invite sent to ${Ne} ${Ne===1?"person":"people"}`+(Be>0?` (${Be} failed)`:"")),R([]),I(""),A(!1)):ne.error("Failed to send invites")};return!v&&!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(Dl,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(je,{className:"border-2 border-dashed",children:[e.jsxs(St,{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(jc,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(Et,{children:"Refer & Earn is for active members"}),e.jsx(Vn,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Le,{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(Dl,{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(dl,{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(je,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx(Yn,{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(je,{children:e.jsxs(Le,{className:"p-4 flex items-center gap-3",children:[e.jsx(Vr,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:le}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(je,{children:e.jsxs(Le,{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:re.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(wn,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(Vn,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Le,{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(Za,{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(Zr,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:J,disabled:!X,children:[e.jsx(pn,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:ce,disabled:!X,children:[e.jsx(no,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:ve,disabled:!X,children:[e.jsx(Hd,{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(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Your Referrals"}),e.jsx(Vn,{children:"Track who joined and when they upgrade."})]}),e.jsx(Le,{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(Yn,{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 Se,Ae;const Ne=((Se=Fe.referred_profile)==null?void 0:Se.name)||((Ae=Fe.referred_profile)==null?void 0:Ae.email)||"New agent",Be=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:Ne}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",Be]})]}),Fe.status==="qualified"?e.jsxs($e,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(Vr,{className:"h-3 w-3 mr-1"})," Paid · +",u+m," pts"]}):e.jsxs($e,{variant:"secondary",children:[e.jsx(ca,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},Fe.id)})})})]}),e.jsx(je,{className:"bg-muted/30",children:e.jsxs(Le,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(wn,{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(Vc,{className:"opacity-0"})]}),e.jsx(Os,{open:S,onOpenChange:A,children:e.jsxs(Fs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(Er,{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($e,{variant:"secondary",className:"gap-1 pr-1",children:[Fe,e.jsx("button",{type:"button",onClick:()=>be(Fe),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${Fe}`,children:e.jsx(mr,{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 Ne=Fe.clipboardData.getData("text");/[\s,;]/.test(Ne)&&(Fe.preventDefault(),ue(Ne))},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:ke(D),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(Nr,{children:[e.jsx($,{variant:"outline",onClick:()=>A(!1),disabled:V,children:"Cancel"}),e.jsxs($,{onClick:Ie,disabled:V,children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),V?"Sending…":`Send${P.length>0?` to ${P.length}`:""}`]})]})]})})]})}const Uos=()=>{const{user:s}=_s(),t=Zt(),n=st({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=st({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=mt({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=mt({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=mt({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"]}),ne.success("Presentation published!")}}),o=mt({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"]}),ne.success("Presentation archived")}}),c=mt({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"]}),ne.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}},yur=()=>{const s=Zn(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=Uos(),i=o=>o.status==="draft"?e.jsx($e,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx($e,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx($e,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx($e,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),ne.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(cn,{className:"h-4 w-4"}),"Create Presentation"]})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(xn,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(je,{children:e.jsxs(Le,{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(vb,{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(cn,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(je,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Le,{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(Qr,{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 ",Js(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ta,{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(Za,{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(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Xx,{className:"h-4 w-4"})})}),e.jsxs(Cu,{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(Ir,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(ja,{onClick:()=>a.mutate(o),children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(ja,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(wv,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},FEt={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."}]},vur=[{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 bur(s){const t=FEt[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(FEt))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return vur}function _ur({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}=NQt(),m=f3(),[f,g]=j.useState(""),[x,v]=j.useState(!1),[y,b]=j.useState(!0),[w,S]=j.useState(!1),[A,E]=j.useState(null),I=bur(s),P=()=>{l("script"),c(0),u(0),g(""),v(!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),v(!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 Z=s||"Presentation Video",{videoId:X,uploadUrl:ae,libraryId:le}=await k6(Z),{apiKey:re}=await S6(X),te=new XMLHttpRequest;te.upload.onprogress=ue=>{ue.lengthComputable&&c(ue.loaded/ue.total*100)},await new Promise((ue,be)=>{te.onload=()=>te.status>=200&&te.status<300?ue():be(new Error("Upload failed")),te.onerror=()=>be(new Error("Upload failed")),te.open("PUT",ae),te.setRequestHeader("AccessKey",re),te.send(V)}),l("processing");let J=0;const ce=Date.now(),ve=9e4;let fe=null;for(;J<4;){if(await new Promise(be=>setTimeout(be,3e3)),Date.now()-ce>ve){const be=V.size/1048576,Ee=`https://iframe.mediadelivery.net/embed/${le}/${X}?responsive=true`;await m.mutateAsync({bunny_video_id:X,playback_url:Ee,file_size_mb:be,title:Z,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(Ee),ne.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const ue=await hk(X);if(J=ue.status,u(ue.encodeProgress||0),J===4)fe={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(!fe)throw new Error("No video data");await m.mutateAsync({bunny_video_id:X,contact_id:t||void 0,playback_url:fe.playbackUrl,thumbnail_url:fe.thumbnailUrl,preview_url:fe.previewUrl,duration_seconds:fe.duration,file_size_mb:fe.fileSizeMb,title:Z,status:"ready",touch_type:"presentation"}),n(fe.playbackUrl),ne.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(Z){console.error("Recording upload error:",Z),ne.error("Failed to process video. Please try again."),l("record")}},[s,t,n,m]);return e.jsxs(Os,{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(fa,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(Fs,{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($s,{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",A===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(Qr,{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:()=>v(!0),className:"h-7 text-xs gap-1",children:[e.jsx(pi,{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(Al,{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(!y),className:"h-7 text-xs gap-1",children:[y?e.jsx(Nx,{className:"h-3 w-3"}):e.jsx(Ta,{className:"h-3 w-3"}),y?"Hide Script":"Show Script"]})]}),e.jsx(DT,{maxDurationSeconds:600,onRecordingComplete:W,onRecordingStateChange:S,onError:V=>ne.error(V),teleprompterContent:f.trim()?e.jsx(Bot,{text:f,isVisible:y,onToggleVisibility:()=>b(!y),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(Ct,{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(Ct,{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(Wl,{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 wur({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=f3(),{data:f}=rDe(),g=(f==null?void 0:f.total_storage_mb)||0,v=((f==null?void 0:f.max_storage_mb)||1024)-g,y=()=>{l(null),c("idle"),u(0)},b=I=>{!I&&o!=="idle"&&o!=="done"||(a(I),I||y())},w=I=>{var D;const P=(D=I.target.files)==null?void 0:D[0];if(!P)return;if(!P.type.startsWith("video/")){ne.error("Please select a video file");return}const R=P.size/(1024*1024);if(R>500){ne.error("Video file must be less than 500MB");return}if(R>v){ne.error(`Not enough storage. You have ${v.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((Z,X)=>{const ae=new XMLHttpRequest;ae.upload.addEventListener("progress",le=>{le.lengthComputable&&u(Math.round(le.loaded/le.total*100))}),ae.addEventListener("load",()=>ae.status>=200&&ae.status<300?Z():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"),ne.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(I){console.error("Upload error:",I),ne.error(I instanceof Error?I.message:"Failed to upload video"),c("idle")}}},[i,s,t,n,m]),A=()=>{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(Os,{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(Fs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsxs($s,{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(fa,{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(mr,{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(Ct,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:A()})]}),e.jsx(Yi,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(Nr,{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(Ct,{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 OEt=[{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"}],zEt=()=>{const s=Zn(),{id:t}=Wi(),{user:n}=_s(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=Uos(),{isGmailConnected:c,gmailEmail:d}=Gy(),[u,h]=j.useState(!1),[m,f]=j.useState("client"),[g,x]=j.useState(!1),[v,y]=j.useState(""),[b,w]=j.useState([]),[S,A]=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(""),[Z,X]=j.useState("buyer"),[ae,le]=j.useState(""),[re,te]=j.useState(null),[J,ce]=j.useState(""),[ve,fe]=j.useState([]),[ue,be]=j.useState("schedule_call"),[Ee,ke]=j.useState("Schedule a Call"),[Ie,Fe]=j.useState(""),[Ne,Be]=j.useState(""),[Se,Ae]=j.useState(null),[Ce,qe]=j.useState(t||null),[ze,Ve]=j.useState(null),[ht,Qe]=j.useState(!1),at=async(jt,zs)=>{if(!n)return;const yt=5*1024*1024;if(jt.size>yt){ne.error("Image must be under 5MB");return}if(!jt.type.startsWith("image/")){ne.error("Please upload an image file");return}Ae(zs);try{const gs=jt.name.split(".").pop()||"jpg",Ss=`${n.id}/${Date.now()}.${gs}`,{error:Ds}=await q.storage.from("listing-photos").upload(Ss,jt);if(Ds)throw Ds;const{data:{publicUrl:Bt}}=q.storage.from("listing-photos").getPublicUrl(Ss);es(zs,{image_url:Bt}),ne.success("Image uploaded")}catch{ne.error("Failed to upload image")}finally{Ae(null)}};j.useEffect(()=>{t&&rt(t)},[t]);const rt=async jt=>{const{data:zs,error:yt}=await q.from("smart_presentations").select("*").eq("id",jt).single();if(yt||!zs)return;const gs=zs;if(x(!0),ce(gs.title),O(gs.client_name||""),le(gs.property_address||""),fe(gs.sections||[]),be(gs.cta_type||"schedule_call"),ke(gs.cta_label||"Schedule a Call"),Fe(gs.cta_url||""),Be(gs.heading||""),Ve(gs.share_token),Qe(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||v.length<1){w([]);return}const jt=setTimeout(async()=>{A(!0);const{data:zs}=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.%${v}%,last_name.ilike.%${v}%,email.ilike.%${v}%`).limit(10);w(zs||[]),A(!1)},300);return()=>clearTimeout(jt)},[v,n]);const Ke=jt=>{I(jt),O(`${jt.first_name} ${jt.last_name||""}`.trim()),W(jt.email||""),G(jt.phone||""),R(!1)},Je=async()=>{if(!D.trim()){ne.error("Client name is required");return}const jt=D.trim().split(" "),zs=jt[0],yt=jt.slice(1).join(" ")||null,{data:gs,error:Ss}=await q.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:zs,last_name:yt,email:U||null,phone:V||null,lead_source:"Smart Presentation"}).select().single();if(Ss){ne.error("Failed to create client");return}I(gs),ne.success("Client created & saved to Agent OS"),f("template")},ft=jt=>{te(jt);const zs=(jt.sections||[]).map(yt=>({...yt,is_visible:!0,video_url:"",text:""}));if(fe(zs),ce(jt.name+(D?` for ${D}`:"")),jt.cta_config){const yt=jt.cta_config;be(yt.type||"schedule_call"),ke(yt.label||"Schedule a Call")}f("builder")},gt=()=>{fe([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),ce(D?`Presentation for ${D}`:"New Presentation"),f("builder")},es=(jt,zs)=>{fe(yt=>yt.map((gs,Ss)=>Ss===jt?{...gs,...zs}:gs))},Ht=jt=>{es(jt,{is_visible:!ve[jt].is_visible})},as=()=>{fe(jt=>[...jt,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},bs=jt=>{fe(zs=>zs.filter((yt,gs)=>gs!==jt))},Ut=async()=>{if(!J.trim()){ne.error("Title is required");return}try{if(Ce){const jt=await l.mutateAsync({id:Ce,title:J,sections:ve,client_name:D,property_address:ae||null,cta_type:ue,cta_label:Ee,cta_url:Ie||null,heading:Ne||null});ne.success("Saved")}else{const jt=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:(re==null?void 0:re.id)||void 0,sections:ve,cta_type:ue,cta_label:Ee,cta_url:Ie||void 0,heading:Ne||void 0});qe(jt.id),Ve(jt.share_token),ne.success("Presentation created!")}}catch(jt){console.error("Failed to save presentation:",jt);const zs=(jt==null?void 0:jt.message)||(jt==null?void 0:jt.toString())||"Unknown error";ne.error(`Failed to save: ${zs}`)}},Ft=async()=>{try{await Ut();const jt=Ce;if(jt){const zs=await o.mutateAsync(jt);Ve(zs.share_token),Qe(!0),f("share")}}catch(jt){console.error("Failed to publish presentation:",jt),ne.error(`Failed to publish: ${(jt==null?void 0:jt.message)||"Unknown error"}`)}},is=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(Va,{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((jt,zs)=>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===jt?"bg-primary text-primary-foreground":zs<["client","template","builder","share"].indexOf(m)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:zs<["client","template","builder","share"].indexOf(m)?e.jsx(ma,{className:"h-4 w-4"}):zs+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:jt}),zs<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},jt))}),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(Zr,{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(Qa,{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(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{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(Le,{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:v,onChange:jt=>y(jt.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[S&&e.jsx(xn,{className:"h-12 w-full"}),b.map(jt=>e.jsxs("button",{onClick:()=>Ke(jt),className:Pt("w-full text-left p-3 rounded-lg border transition-colors",(E==null?void 0:E.id)===jt.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[jt.first_name," ",jt.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:jt.email||jt.phone||"No contact info"})]},jt.id)),!v&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),v&&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(Qa,{className:"h-4 w-4"})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(lc,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(Le,{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:jt=>{O(jt.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:jt=>W(jt.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Phone"}),e.jsx(pe,{value:V,onChange:jt=>G(jt.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Client Type"}),e.jsxs(ms,{value:Z,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:jt=>le(jt.target.value),placeholder:"Optional"})]})]}),P&&D&&e.jsxs($,{onClick:Je,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(Qa,{className:"h-4 w-4"})]})]})]})]})]}),m==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(pa,{defaultValue:"system",children:[e.jsxs(ga,{children:[e.jsx(Xt,{value:"mine",children:"My Core Templates"}),e.jsx(Xt,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(Xt,{value:"blank",children:"+ Start Blank"})]}),e.jsx(Qt,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(jt=>e.jsx(xn,{className:"h-32"},jt))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(jt=>!jt.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(jt=>!jt.is_system).map(jt=>e.jsx(BEt,{template:jt,onSelect:ft},jt.id))})}),e.jsx(Qt,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(jt=>jt.is_system).map(jt=>e.jsx(BEt,{template:jt,onSelect:ft},jt.id))})}),e.jsx(Qt,{value:"blank",className:"mt-4",children:e.jsx(je,{children:e.jsxs(Le,{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:gt,children:"Start from Scratch"})]})})})]}),e.jsxs($,{variant:"outline",onClick:()=>f("client"),className:"gap-2",children:[e.jsx(Va,{className:"h-4 w-4"}),"Back"]})]}),m==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(je,{children:e.jsxs(Le,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Presentation Title"}),e.jsx(pe,{value:J,onChange:jt=>ce(jt.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Page Heading"}),e.jsx(pe,{value:Ne,onChange:jt=>Be(jt.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:jt=>O(jt.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Property Address"}),e.jsx(pe,{value:ae,onChange:jt=>le(jt.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:as,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:ve.map((jt,zs)=>e.jsx(je,{className:Pt(!jt.is_visible&&"opacity-50"),children:e.jsx(Le,{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(zg,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:jt.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:jt.title,onChange:yt=>es(zs,{title:yt.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:()=>Ht(zs),children:jt.is_visible?e.jsx(Ta,{className:"h-4 w-4"}):e.jsx(Nx,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>bs(zs),className:"text-destructive hover:text-destructive",children:e.jsx(qn,{className:"h-4 w-4"})})]})]}),e.jsx(pe,{value:jt.description||"",onChange:yt=>es(zs,{description:yt.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:jt.video_url||"",onChange:yt=>es(zs,{video_url:yt.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(_ur,{sectionTitle:jt.title,contactId:E==null?void 0:E.id,onVideoReady:yt=>es(zs,{video_url:yt})}),e.jsx(wur,{sectionTitle:jt.title,contactId:E==null?void 0:E.id,onVideoReady:yt=>es(zs,{video_url:yt})}),e.jsx(e9,{userId:n==null?void 0:n.id,onSelect:yt=>es(zs,{video_url:yt})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),jt.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:jt.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:()=>es(zs,{image_url:""}),children:e.jsx(mr,{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:[Se===zs?e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(kv,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Se===zs?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:Se===zs,onChange:yt=>{var Ss;const gs=(Ss=yt.target.files)==null?void 0:Ss[0];gs&&at(gs,zs),yt.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Text (optional)"}),e.jsx(kk,{content:jt.text||"",onChange:yt=>es(zs,{text:yt}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},zs))})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Call to Action"})}),e.jsxs(Le,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"CTA Type"}),e.jsxs(ms,{value:ue,onValueChange:jt=>{be(jt);const zs=OEt.find(yt=>yt.value===jt);zs&&ke(zs.label)},children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:OEt.map(jt=>e.jsx(Ge,{value:jt.value,children:jt.label},jt.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Button Label"}),e.jsx(pe,{value:Ee,onChange:jt=>ke(jt.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:Ie,onChange:jt=>Fe(jt.target.value),placeholder:"https://calendly.com/..."}),!Ie&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Without a URL, clients will see a contact form — their info gets added to your contacts and you'll receive an email notification."})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[!g&&e.jsxs($,{variant:"outline",onClick:()=>f("template"),className:"gap-2",children:[e.jsx(Va,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx($,{variant:"outline",onClick:Ut,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs($,{onClick:Ft,disabled:o.isPending,className:"gap-2",children:[e.jsx(Zr,{className:"h-4 w-4"}),ht?"Update & Reshare":"Publish & Share"]})]})]})]}),m==="share"&&ze&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(je,{children:e.jsxs(Le,{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(ma,{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:is,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx($,{onClick:()=>{navigator.clipboard.writeText(is),ne.success("Link copied!")},children:e.jsx(Za,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs($,{variant:"outline",className:"gap-2",onClick:()=>{const jt=`Hi ${D||""}! I put together something for you — check it out: ${is}`;navigator.clipboard.writeText(jt),ne.success("Message copied!")},children:[e.jsx(no,{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: ${is} Looking forward to connecting!`)}`)},children:[e.jsx(pn,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(Nk,{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: ${is} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs($,{variant:"outline",onClick:()=>f("builder"),children:[e.jsx(Va,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx($,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},BEt=({template:s,onSelect:t})=>e.jsx(je,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Le,{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($e,{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"})]})}),jur=()=>{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:v,error:y}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(y||!v){c(!0),a(!1);return}const{data:b}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",v.owner_user_id).single();let w;if(b!=null&&b.brokerage_id){const{data:A}=await q.from("brokerages").select("name").eq("id",b.brokerage_id).single();w=(A==null?void 0:A.name)||void 0}let S=null;if(v.contact_id){const{data:A}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",v.contact_id).single();S=A}n({...v,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:v.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(xn,{className:"h-12 w-3/4 mx-auto"}),e.jsx(xn,{className:"h-64 w-full"}),e.jsx(xn,{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(v=>v.is_visible!==!1),m=h[i],f=v=>{const y=v.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(y)return`https://www.youtube.com/embed/${y[1]}?rel=0`;if(v.includes("iframe.mediadelivery.net/play/")){const S=v.replace("/play/","/embed/"),A=S.includes("?")?"&":"?";return`${S}${A}responsive=true`}if(v.includes("iframe.mediadelivery.net")){if(v.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const A=v.includes("?")?"&":"?";return`${v}${A}responsive=true`}return""}const b=v.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(b)return`https://www.loom.com/embed/${b[1]}`;const w=v.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return w?`https://iframe.mediadelivery.net/embed/${w[1]}/${w[2]}?responsive=true`:v},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((v,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:v.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:v.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:v.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?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(Ir,{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(O7t,{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"})]})},xUe="__none__";function Nur({value:s,onChange:t}){const{data:n=[],isLoading:r}=Mie(),a=dit(),[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(XI,{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($e,{variant:"outline",className:"text-[10px] border-emerald-300 bg-emerald-500/10 text-emerald-700",children:"On"})]}),e.jsxs(ms,{value:s??xUe,onValueChange:h=>t(h===xUe?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:xUe,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(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(wn,{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 kur({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=tFs(s),i=aFs(),l=iFs(),o=oFs(),c=lFs(),[d,u]=j.useState(""),[h,m]=j.useState("rating"),f=async y=>{n(y),y&&(!r||r.length===0)&&await c.mutateAsync(s)},g=async()=>{if(!d.trim())return;const y=(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:y+1}),u("")},x=async y=>{await l.mutateAsync({id:y.id,open_house_id:s,is_active:!y.is_active})},v=async y=>{await o.mutateAsync({id:y.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(Fg,{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(jn,{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(Ct,{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(y=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(zg,{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:y.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:y.question_type.replace("_"," ")})]}),e.jsx(jn,{checked:y.is_active,onCheckedChange:()=>x(y),className:"scale-75"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>v(y),children:e.jsx(qn,{className:"h-3.5 w-3.5"})})]},y.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:y=>u(y.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:y=>y.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(cn,{className:"h-3.5 w-3.5"})})]})]})})]})}function Sur({openHouseId:s}){const{user:t}=_s(),{data:n=[],isLoading:r}=hFs(s),a=fFs(),i=vFs(),l=(m,f)=>{const g=m+f;if(g<0||g>=n.length)return;const x=n.map(v=>v.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(Ct,{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(Cur,{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(Ct,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(cn,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function Cur({room:s,index:t,total:n,userId:r,openHouseId:a,onMoveRoom:i}){const l=pFs(),o=gFs(),c=xFs(),d=yFs(),u=bFs(),h=j.useRef(null),[m,f]=j.useState(!0),[g,x]=j.useState(s.name),[v,y]=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:A={}}=st({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 Z={};return V.forEach(X=>{Z[X.id]={status:X.status,thumbnail_url:X.thumbnail_url,preview_url:X.preview_url}}),Z},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=()=>{v!==(s.description||"")&&l.mutate({id:s.id,open_house_id:a,description:v.trim()||null})},P=async()=>{await mo(`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(Z=>Z.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/"),Z=G?500*1024*1024:15*1024*1024;if(V.size>Z){_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:ve,libraryId:fe}=J,{data:ue,error:be}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ve,isAgentVideo:!0}});if(be||!ue)throw new Error((be==null?void 0:be.message)||"Could not get upload URL");await new Promise((Ne,Be)=>{const Se=new XMLHttpRequest;Se.addEventListener("load",()=>{Se.status>=200&&Se.status<300?Ne():Be(new Error(`Upload failed (${Se.status})`))}),Se.addEventListener("error",()=>Be(new Error("Upload failed"))),Se.open("PUT",ue.uploadUrl),Se.setRequestHeader("AccessKey",ue.apiKey),Se.send(V)});const Ee=`https://iframe.mediadelivery.net/embed/${fe}/${ve}`,ke=V.size/(1024*1024),{data:Ie,error:Fe}=await q.from("agent_videos").insert({owner_user_id:r,bunny_video_id:ve,playback_url:Ee,file_size_mb:ke,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:Ie.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:le}=await q.storage.from("open-house-tour-media").upload(ae,V,{upsert:!1,contentType:V.type});if(le){_a({title:"Upload failed",description:le.message,variant:"destructive"});continue}const{data:re}=q.storage.from("open-house-tour-media").getPublicUrl(ae);await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:re.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(zg,{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(xb,{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(wl,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:P,children:e.jsx(qn,{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:v,onChange:U=>y(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?A[U.agent_video_id]:void 0,G=V==null?void 0:V.status,Z=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"}),!Z&&!X&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(fa,{className:"h-6 w-6 text-white"})}),Z&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-black/70 text-white gap-1 pointer-events-none",children:[e.jsx(Ct,{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(mr,{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(kd,{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(Ct,{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(e9,{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 Aur({open:s,onOpenChange:t,openHouse:n}){const r=B7t(),{user:a}=_s(),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,v]=j.useState(n.ask_visitor_intent??!0),[y,b]=j.useState(n.ask_visitor_address??!1),[w,S]=j.useState(n.photo_url??""),[A,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,Z]=j.useState(n.state??""),[X,ae]=j.useState(n.zip??""),[le,re]=j.useState((n.event_date??"").slice(0,10)),[te,J]=j.useState((n.start_time??"").slice(0,5)),[ce,ve]=j.useState((n.end_time??"").slice(0,5)),[fe,ue]=j.useState(n.hero_video_url??""),[be,Ee]=j.useState(!1),[ke,Ie]=j.useState(n.price!=null?String(n.price):""),[Fe,Ne]=j.useState(n.beds!=null?String(n.beds):""),[Be,Se]=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),[Ve,ht]=j.useState(n.enable_showing??!0),[Qe,at]=j.useState(n.enable_disclosures??!0),[rt,Ke]=j.useState(n.enable_offer??!0),[Je,ft]=j.useState(n.brand_color_override??""),[gt,es]=j.useState(n.property_description??""),[Ht,as]=j.useState(n.drip_campaign_id??null),bs=async yt=>{var vs;const gs=(vs=yt.target.files)==null?void 0:vs[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",Ds=`${a.id}/${n.id}/hero-${Date.now()}.${Ss}`,{error:Bt}=await q.storage.from("open-house-tour-media").upload(Ds,gs,{upsert:!0,contentType:gs.type});if(Bt){_a({title:"Upload failed",description:Bt.message,variant:"destructive"}),Ee(!1);return}const{data:zt}=q.storage.from("open-house-tour-media").getPublicUrl(Ds);ue(zt.publicUrl),Ee(!1),_a({title:"Video uploaded!"})},Ut=async yt=>{var vs;const gs=(vs=yt.target.files)==null?void 0:vs[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",Ds=`${a.id}/${n.id}-${Date.now()}.${Ss}`,{error:Bt}=await q.storage.from("open-house-photos").upload(Ds,gs,{upsert:!0});if(Bt){_a({title:"Upload failed",description:Bt.message,variant:"destructive"}),P(!1);return}const{data:zt}=q.storage.from("open-house-photos").getPublicUrl(Ds);S(zt.publicUrl),P(!1),_a({title:"Photo updated!"})},Ft=()=>{S(""),l.current&&(l.current.value="")},is=async yt=>{var zt;const gs=(zt=yt.target.files)==null?void 0:zt[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:Ds}=await q.storage.from("open-house-photos").upload(Ss,gs,{upsert:!0});if(Ds){_a({title:"Upload failed",description:Ds.message,variant:"destructive"}),E(!1);return}const{data:Bt}=q.storage.from("open-house-photos").getPublicUrl(Ss);m(Bt.publicUrl),E(!1),_a({title:"PDF uploaded!"})},jt=()=>{m(""),i.current&&(i.current.value="")},zs=async()=>{if(!O.trim()){_a({title:"Add a property address",variant:"destructive"});return}if(!le){_a({title:"Pick a date for the open house",variant:"destructive"});return}D(!0);try{const yt={id:n.id,property_address:O.trim(),city:W.trim()||null,state:G.trim()||null,zip:X.trim()||null,event_date:le,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:y,photo_url:w||null,drip_campaign_id:Ht};c&&(yt.hero_video_url=fe||null,yt.price=ke.trim()?Number(ke):null,yt.beds=Fe.trim()?parseInt(Fe,10):null,yt.baths=Be.trim()?Number(Be):null,yt.sqft=Ae.trim()?parseInt(Ae,10):null,yt.enable_question=qe,yt.enable_showing=Ve,yt.enable_disclosures=Qe,yt.enable_offer=rt,yt.brand_color_override=Je.trim()||null,yt.property_description=gt.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))&&(yt.latitude=null,yt.longitude=null,yt.geocode_status="pending",yt.geocoded_at=null),await r.mutateAsync(yt),_a({title:"Settings saved!"}),t(!1)}catch{_a({title:"Failed to save",variant:"destructive"})}finally{D(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx($s,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(Er,{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:le,onChange:yt=>re(yt.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:yt=>J(yt.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:yt=>ve(yt.target.value),className:"mt-1"})]})]}),e.jsx(ee,{className:"text-sm font-medium",children:"Property Address"}),e.jsx(pe,{value:O,onChange:yt=>U(yt.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:yt=>V(yt.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:yt=>Z(yt.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:yt=>ae(yt.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(fa,{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:bs,className:"hidden"}),fe?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:fe,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 yt;return(yt=o.current)==null?void 0:yt.click()},disabled:be,children:be?e.jsx(Ct,{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(mr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var yt;return(yt=o.current)==null?void 0:yt.click()},disabled:be,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:be?e.jsx(Ct,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(fa,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(Sur,{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:ke,onChange:yt=>Ie(yt.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:yt=>Ce(yt.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:yt=>Ne(yt.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:Be,onChange:yt=>Se(yt.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:gt,onChange:yt=>es(yt.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(jn,{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(jn,{checked:Ve,onCheckedChange:ht})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(jn,{checked:Qe,onCheckedChange:at})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(jn,{checked:rt,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:Je||"#0f172a",onChange:yt=>ft(yt.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(pe,{value:Je,onChange:yt=>ft(yt.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),Je&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ft(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(yt=>e.jsx("button",{type:"button",onClick:()=>ft(yt),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:yt},"aria-label":yt},yt))})]})]}),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:Ut,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 yt;return(yt=l.current)==null?void 0:yt.click()},disabled:I,children:[I?e.jsx(Ct,{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(mr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var yt;return(yt=l.current)==null?void 0:yt.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(Ct,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Hc,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),e.jsx(Nur,{value:Ht,onChange:as}),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(jn,{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:is,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(Qr,{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:jt,children:e.jsx(mr,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var yt;return(yt=i.current)==null?void 0:yt.click()},disabled:A,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:A?e.jsx(Ct,{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(jn,{checked:x,onCheckedChange:v})]})}),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(jn,{checked:y,onCheckedChange:b})]})}),e.jsx(kur,{openHouseId:n.id,enableSurvey:f,onToggleSurvey:g}),e.jsx($,{onClick:zs,disabled:R,className:"w-full",children:R?"Saving...":"Save Settings"})]})]})})}const qos={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function Eur({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:qos[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 Tur({openHouseId:s}){const{data:t,isLoading:n}=rFs(s),{data:r}=z7t(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(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(Fg,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Le,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(Fg,{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(Le,{children:e.jsxs(pa,{defaultValue:"summary",children:[e.jsxs(ga,{className:"mb-4",children:[e.jsxs(Xt,{value:"summary",className:"text-xs gap-1",children:[e.jsx(Gl,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(Xt,{value:"individual",className:"text-xs gap-1",children:[e.jsx(sl,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(Qt,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(Eur,{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(Qt,{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(v=>v.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?qos[g.rating_value]||g.rating_value:g.text_value})]},g.id):null})})]},h)})})]})})]})}const Mur={question:{label:"Question",icon:no,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:Ea,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:Qr,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:su,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},$Et={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 Pur({openHouseId:s}){const{data:t=[],isLoading:n}=_Fs(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(zz,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx($e,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs($e,{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=Mur[h.action_type],f=m.icon,g=h.payload||{},x=a===h.id,v=h.status==="contacted",y=h.status==="archived";return e.jsxs("li",{className:`transition-colors ${y?"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($e,{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"}),v&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(Vr,{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(ca,{className:"h-3 w-3"}),Js(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(pn,{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(wl,{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($Et).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($Et).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(pn,{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"]})}),!v&&e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(Vr,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),y?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(wv,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}const UEt=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}`},Iur=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"})},qEt=25;function Lur({open:s,onOpenChange:t,openHouse:n,variant:r="tour"}){var ht;const a=r==="rsvp",{isGmailConnected:i,gmailEmail:l}=Gy(),{data:o}=eie(),c=!!(o!=null&&o.hasVerifiedSes),d=Sa(),{data:u=[]}=Uw(),[h,m]=j.useState([]),[f,g]=j.useState(!1),[x,v]=j.useState("all"),[y,b]=j.useState([]),[w,S]=j.useState([]),[A,E]=j.useState(""),[I,P]=j.useState([]),[R,D]=j.useState(""),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Z]=j.useState("platform"),[X,ae]=j.useState(!1),[le,re]=j.useState(0),[te,J]=j.useState(!1),ce=a?`https://guestbook.relevelup.com/rsvp/${n.slug}`:`https://guestbook.relevelup.com/${n.slug}`,ve=Iur(n.event_date),fe=n.start_time?`${UEt(n.start_time)}${n.end_time?` – ${UEt(n.end_time)}`:""}`:"",ue=[ve,fe].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}${ve?` on ${ve}`:""}${fe?` from ${fe}`:""}. 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(""),v("all"),re(0),Z(c?"ses":i?"gmail":"platform"),h.length===0&&be())},[s,n.id,i,c]);const be=async()=>{if(d){g(!0);try{const Qe=[];let rt=0;for(;;){const{data:Ke,error:Je}=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(rt,rt+1e3-1);if(Je)throw Je;const ft=Ke||[];if(Qe.push(...ft),ft.length<1e3)break;rt+=1e3}m(Qe.map(Ke=>({id:Ke.id,first_name:Ke.first_name,last_name:Ke.last_name,email:Ke.email,tagIds:(Ke.tags||[]).map(Je=>Je.relationship_type_id)})))}catch{ne.error("Failed to load contacts")}finally{g(!1)}}},Ee=Qe=>`${Qe.first_name} ${Qe.last_name||""}`.trim(),ke=j.useMemo(()=>{const Qe=R.trim().toLowerCase();return Qe?h.filter(at=>`${Ee(at)} ${at.email||""}`.toLowerCase().includes(Qe)):h},[h,R]),Ie=j.useMemo(()=>{const Qe={};return h.forEach(at=>at.tagIds.forEach(rt=>{Qe[rt]=(Qe[rt]||0)+1})),Qe},[h]),Fe=j.useMemo(()=>x==="all"?h:x==="tags"?y.length===0?[]:h.filter(Qe=>Qe.tagIds.some(at=>y.includes(at))):h.filter(Qe=>w.includes(Qe.id)),[x,h,y,w]),Ne=j.useMemo(()=>{const Qe=new Set,at=[];return[...Fe.map(rt=>({email:rt.email,name:Ee(rt)})),...I].forEach(rt=>{const Ke=rt.email.toLowerCase();!rt.email||Qe.has(Ke)||(Qe.add(Ke),at.push(rt))}),at},[Fe,I]),Be=()=>{const Qe=A.trim();if(Qe){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Qe)){ne.error("Invalid email");return}P(at=>[...at,{email:Qe,name:Qe.split("@")[0]}]),E("")}},Se=Qe=>Qe.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=Qe=>{const at=Qe?`Hi ${Se(Qe)},`:"Hi there,",rt=[n.city,n.state].filter(Boolean).join(", "),Ke=Se(W).split(/\n\n+/).map(Je=>`

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

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

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

${Se(n.property_address)}

${rt?`

${Se(rt)}${n.zip?" "+Se(n.zip):""}

`:""}
 

When

${Se(ue)}

${at}

${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 Qe;if(Ne.length===0){ne.error("Add at least one recipient");return}ae(!0),re(0);try{if(G==="gmail"&&i){let at=0;for(const rt of Ne){const{data:Ke,error:Je}=await q.functions.invoke("gmail-send",{body:{to:rt.email,subject:O,body:Ce((Qe=rt.name)==null?void 0:Qe.split(" ")[0])}});!Je&&(Ke!=null&&Ke.success)&&(at+=1),re(at)}if(at===0)throw new Error("Gmail send failed");ne.success(`Sent to ${at} of ${Ne.length} via Gmail`)}else{let at=0;for(let rt=0;rt{await navigator.clipboard.writeText(ce),J(!0),setTimeout(()=>J(!1),1500)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Fs,{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($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5 text-primary"}),a?"Invite to Open House":"Email Virtual Tour"]}),e.jsx(Er,{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(Sd,{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:Ve,className:"shrink-0 h-7 gap-1",children:[te?e.jsx(ma,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Za,{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(pn,{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:()=>Z("ses"),className:"gap-1.5",children:"Mass Email (your address)"}),i&&e.jsx($,{type:"button",variant:G==="gmail"?"default":"outline",size:"sm",onClick:()=>Z("gmail"),className:"gap-1.5",children:"Gmail"}),e.jsx($,{type:"button",variant:G==="platform"?"default":"outline",size:"sm",onClick:()=>Z("platform"),className:"gap-1.5",children:"LevelUp"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:G==="ses"&&((ht=o==null?void 0:o.verifiedEmails)!=null&&ht[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(Yn,{className:"h-3.5 w-3.5"}),"Who should receive this?"]}),e.jsxs(pa,{value:x,onValueChange:Qe=>v(Qe),children:[e.jsxs(ga,{className:"grid w-full grid-cols-3",children:[e.jsx(Xt,{value:"all",children:"All contacts"}),e.jsx(Xt,{value:"tags",children:"By tag"}),e.jsx(Xt,{value:"select",children:"Pick people"})]}),e.jsx(Qt,{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(Qt,{value:"tags",className:"pt-3",children:e.jsx(go,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[u.map(Qe=>{const at=y.includes(Qe.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:at,onCheckedChange:()=>b(rt=>at?rt.filter(Ke=>Ke!==Qe.id):[...rt,Qe.id])}),e.jsxs("span",{className:"flex items-center gap-1.5 text-sm flex-1 min-w-0 truncate",children:[e.jsx(Cp,{className:"h-3 w-3 text-muted-foreground shrink-0"}),Qe.name]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ie[Qe.id]||0})]},Qe.id)}),u.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:"No tags yet."})]})})}),e.jsxs(Qt,{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:Qe=>D(Qe.target.value),placeholder:"Search contacts...",className:"pl-8 h-9"})]}),e.jsx(go,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[ke.slice(0,300).map(Qe=>{const at=w.includes(Qe.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:at,onCheckedChange:()=>S(rt=>at?rt.filter(Ke=>Ke!==Qe.id):[...rt,Qe.id])}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:Ee(Qe)||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Qe.email})]})]},Qe.id)}),ke.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:A,onChange:Qe=>E(Qe.target.value),placeholder:"Also send to an email...",type:"email",onKeyDown:Qe=>{Qe.key==="Enter"&&(Qe.preventDefault(),Be())}}),e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:Be,children:"Add"})]}),I.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.map(Qe=>e.jsxs($e,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:Qe.email}),e.jsx("button",{onClick:()=>P(at=>at.filter(rt=>rt.email!==Qe.email)),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(mr,{className:"h-3 w-3"})})]},Qe.email))})]}),e.jsx(Vc,{}),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:Qe=>U(Qe.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:Qe=>V(Qe.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(Ta,{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:Ne.length.toLocaleString()})," recipient",Ne.length===1?"":"s",X&&le>0&&e.jsxs("span",{children:[" · sent ",le]})]}),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||Ne.length===0||!O.trim(),className:"gap-2",children:[X?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"}),X?"Sending...":`Send${Ne.length?` to ${Ne.length}`:""}`]})]})]})]})})}function Rur({openHouseId:s}){const{data:t=[],isLoading:n}=UFs(s),r=VFs(s),a=HFs(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(gb,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold",children:"RSVPs"}),e.jsx($e,{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($e,{className:"text-[10px] gap-1",children:[e.jsx(ma,{className:"h-3 w-3"}),"Checked in"]}),l.has_agent&&e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(u2,{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(pn,{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(qn,{className:"h-4 w-4"})})]},l.id))})]})}function Dur({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(cn,{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(Xp,{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 VEt={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 Fur({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(Yn,{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(Hd,{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(sh,{className:"h-3 w-3"}),r," hot"]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:t,className:"h-7 gap-1 text-xs",children:[e.jsx(ji,{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=VEt[a.visitor_intent||""]||VEt.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:Js(new Date(a.created_at),"h:mm a")})]},a.id)})})]})})]})}const jAe="guestbook.relevelup.com";function Our(){const{data:s,isLoading:t}=QDs(),n=JDs(),r=B7t(),a=eFs(),[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}=_s(),v=Sa(),[y,b]=j.useState(null),[w,S]=j.useState(null),[A,E]=j.useState(!1),I=j.useRef(null),[P,R]=j.useState({property_address:"",city:"",state:"",zip:"",event_date:Js(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(y&&x){E(!0);const ce=y.name.split(".").pop(),ve=`${v}/${Date.now()}.${ce}`,{error:fe}=await q.storage.from("open-house-photos").upload(ve,y,{upsert:!0});if(fe){_a({title:"Photo upload failed",description:fe.message,variant:"destructive"}),E(!1);return}const{data:ue}=q.storage.from("open-house-photos").getPublicUrl(ve);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:Js(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://${jAe}/${te}`),_a({title:"Link copied!"})},V=Js(new Date,"yyyy-MM-dd"),G=j.useMemo(()=>{const te=s??[],J=d.trim().toLowerCase(),ce=Ne=>!J||[Ne.property_address,Ne.city,Ne.state].filter(Boolean).join(" ").toLowerCase().includes(J),ve=te.filter(ce),fe=ve.filter(Ne=>Ne.kind==="virtual"),ue=ve.filter(Ne=>Ne.kind!=="virtual"),be=ue.filter(Ne=>Ne.event_date===V),Ee=ue.filter(Ne=>Ne.event_date>V).sort((Ne,Be)=>Ne.event_date.localeCompare(Be.event_date)),ke=ue.filter(Ne=>Ne.event_dateBe.event_date.localeCompare(Ne.event_date)),Ie=te.reduce((Ne,Be)=>Ne+(Be.visitor_count||0),0),Fe=te.reduce((Ne,Be)=>Ne+(Be.qr_scan_count||0),0);return{today:be,upcoming:Ee,past:ke,virtual:fe,totalSignIns:Ie,totalScans:Fe}},[s,d,V]),Z=G.today.length+G.upcoming.length,X=Z>0?`${Z} upcoming · ${G.totalSignIns.toLocaleString()} total sign-ins`:`${G.totalSignIns.toLocaleString()} total sign-ins collected`,ae=te=>h==="all"||h===te,le=te=>m(J=>J===te?"all":te),re=te=>e.jsx(zur,{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(Dl,{children:e.jsx("title",{children:"Guest Book | LevelUp"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(Dur,{summary:X,search:d,onSearchChange:u,onCreate:()=>l(!0),stats:[{key:"today",label:"Live Today",value:G.today.length,onClick:()=>le("today"),active:h==="today"},{key:"upcoming",label:"Upcoming",value:G.upcoming.length,onClick:()=>le("upcoming"),active:h==="upcoming"},{key:"virtual",label:"Virtual Tours",value:G.virtual.length,onClick:()=>le("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(Os,{open:i,onOpenChange:l,children:[e.jsx(jl,{asChild:!0,children:e.jsx("span",{className:"sr-only",children:"Open create dialog"})}),e.jsxs(Fs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"Create Open House"}),e.jsx(Er,{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(mr,{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(kv,{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||A,className:"w-full",children:A?"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(je,{className:"animate-pulse",children:e.jsxs(St,{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(yUe,{title:"Happening Today",count:G.today.length,accent:!0}),e.jsx("div",{className:"space-y-4",children:G.today.map(re)})]}),G.upcoming.length>0&&ae("upcoming")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(yUe,{title:"Upcoming",count:G.upcoming.length}),e.jsx("div",{className:"space-y-4",children:G.upcoming.map(re)})]}),G.virtual.length>0&&ae("virtual")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(yUe,{title:"Virtual Tours",count:G.virtual.length}),e.jsx("div",{className:"space-y-4",children:G.virtual.map(re)})]}),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(Cw,{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(xb,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(wl,{className:"h-4 w-4 text-muted-foreground"})]}),f&&e.jsx("div",{className:"space-y-4",children:G.past.map(re)})]}),Z===0&&G.virtual.length===0&&G.past.length===0&&e.jsx(je,{className:"border-dashed",children:e.jsxs(Le,{className:"py-12 text-center text-sm text-muted-foreground",children:["No open houses match “",d,"”."]})})]}):e.jsx(je,{className:"border-dashed",children:e.jsxs(Le,{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(Xp,{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(cn,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function yUe({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 zur({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i,isToday:l}){const{data:o}=z7t(t?s.id:void 0),{data:c}=st({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,v]=j.useState(!1),y=j.useRef(null),b=`https://${jAe}/${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,'""'),Js(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)},A=j.useCallback(()=>{if(!y.current)return;const P=y.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(!y.current)return;const P=y.current.querySelector("svg");if(!P)return;const R=new XMLSerializer().serializeToString(P),D="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(R))),O=Js(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,Z=!!c,X=G||Z,ae=G&&Z,le=ae?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",re=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",ve=ae?"14px 36px":"22px 44px",fe=ae?"20px":"24px",ue=X?"0.2in":"0.35in",be=ae?"1.8in":"2.4in",Ee=X?"0.15in":"0.3in",ke=ae?"140px":X?"160px":"200px",Ie=ae?"16px":"24px",Fe=ae?"10px 20px":"16px 28px",Ne=ae?"44px":"56px",Be="0.15in",Se=window.open("","_blank");Se&&(Se.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
`),Se.document.close(),setTimeout(()=>{Se.focus(),Se.print()},500))},[s,b,c]),I=async()=>{v(!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{v(!1)}};return e.jsxs(je,{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(St,{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(Et,{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($e,{className:"shrink-0 gap-1 border-none bg-emerald-500/15 text-[11px] text-emerald-700 dark:text-emerald-300",children:[e.jsx(bb,{className:"h-3 w-3"}),"Today"]}),e.jsx($e,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs($e,{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(Ta,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs($e,{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(ui,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs($e,{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($e,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(wi,{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(xb,{className:"h-4 w-4"}):e.jsx(wl,{className:"h-4 w-4"})})]}),e.jsxs(Vn,{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(ui,{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(ca,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ea,{className:"h-3 w-3"}),Js(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(ca,{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(Yn,{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(Xp,{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(bb,{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(Za,{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(Xp,{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(Hd,{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(pn,{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(nV,{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(Nd,{className:"h-3.5 w-3.5"}),"Settings"]}),e.jsxs(Bu,{children:[e.jsx($u,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0","aria-label":"More actions",children:e.jsx(o_,{className:"h-4 w-4"})})}),e.jsxs(Cu,{align:"end",className:"w-52",children:[e.jsxs(ja,{onClick:()=>window.open(b,"_blank"),children:[e.jsx(Ir,{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(Ta,{className:"mr-2 h-4 w-4"}),"Preview tour"]}):e.jsxs(ja,{onClick:()=>window.open(`https://${jAe}/rsvp/${s.slug}`,"_blank"),children:[e.jsx(gb,{className:"mr-2 h-4 w-4"}),"Preview RSVP page"]}),e.jsxs(ja,{onClick:a,children:[s.is_active?e.jsx(Nx,{className:"mr-2 h-4 w-4"}):e.jsx(Ta,{className:"mr-2 h-4 w-4"}),s.is_active?"Deactivate":"Activate"]}),e.jsx(P0,{}),e.jsxs(ja,{onClick:i,className:"text-destructive focus:text-destructive",children:[e.jsx(qn,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})]})]})}),t&&e.jsxs(Le,{className:"pt-0",children:[e.jsx(Vc,{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://",jAe,"/",s.slug]})]}),e.jsx(Fur,{visitors:o??[],onExport:S}),s.kind!=="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(Rur,{openHouseId:s.id})}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(Pur,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(Tur,{openHouseId:s.id})})]}),e.jsx(Os,{open:d,onOpenChange:u,children:e.jsxs(Fs,{className:"sm:max-w-sm",children:[e.jsxs(Us,{children:[e.jsx($s,{children:"QR Code"}),e.jsx(Er,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:y,className:"bg-white p-4 rounded-xl",children:e.jsx(dk,{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:A,children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:E,children:[e.jsx(LE,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs($,{variant:"default",className:"w-full",onClick:I,disabled:x,children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),x?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(Aur,{open:h,onOpenChange:m,openHouse:s}),e.jsx(Lur,{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 Bur=F2({full_name:yl().trim().min(2,"Please enter your name").max(120),email:yl().trim().email("Please enter a valid email").max(200),brokerage:yl().trim().min(2,"Please enter your brokerage").max(160)}),HEt=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():"",$ur=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 Uur(){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,v]=j.useState(!1);j.useEffect(()=>{let A=!0;return(async()=>{n(!0);const{data:E,error:I}=await q.functions.invoke("resource-kit-public",{body:{slug:s}});A&&(I||!(E!=null&&E.kit)?c(!0):(a(E.kit),l(E.files??[])),n(!1))})(),()=>{A=!1}},[s]);const y=async A=>{A.preventDefault(),m("");const E=Bur.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??[]),v(!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(xn,{className:"h-10 w-2/3 bg-white/10"}),e.jsx(xn,{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=HEt(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(Dl,{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(wn,{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((A,E)=>e.jsxs("li",{className:"flex items-start gap-3 text-slate-200",children:[e.jsx(Vr,{className:"h-5 w-5 shrink-0 text-amber-400 mt-0.5"}),e.jsx("span",{className:"leading-relaxed",children:HEt(A)||A})]},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(A=>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(Qr,{className:"h-4 w-4 text-slate-300 shrink-0"}),e.jsx("span",{className:"flex-1 text-sm text-slate-100 truncate",children:A.name}),e.jsx("span",{className:"text-[11px] text-slate-400",children:$ur(A.file_size)}),x&&A.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:A.file_url,target:"_blank",rel:"noopener noreferrer",download:!0,children:[e.jsx(ji,{className:"h-3.5 w-3.5 mr-1"})," Download"]})}):e.jsx(jc,{className:"h-3.5 w-3.5 text-slate-500"})]},A.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(Vr,{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(A=>A.file_url&&e.jsxs("a",{href:A.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(ji,{className:"h-4 w-4 text-amber-400"}),e.jsx("span",{className:"text-sm truncate",children:A.name})]},A.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:y,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:A=>u({...d,full_name:A.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:A=>u({...d,email:A.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:A=>u({...d,brokerage:A.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(Qa,{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(Rm,{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."]})]})]})})})]})]})]})}Lot.workerSrc=Rot;const qur={signature:_f,initials:aV,date_signed:Wc,printed_name:sl,text:rV},Vos={signature:"Signature",initials:"Initials",date_signed:"Date signed",printed_name:"Printed name",text:"Text"};function Hos(){return new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"2-digit",day:"2-digit",year:"numeric"}).format(new Date)}function Vur(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 Hur(){var G,Z,X,ae;const{token:s}=Wi(),t=Zn(),[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({}),[v,y]=j.useState({}),[b,w]=j.useState(null),[S,A]=j.useState(!1),[E,I]=j.useState(!1),[P,R]=j.useState(!1);j.useEffect(()=>{let le=!1;return r(!0),i(null),o(null),d(null),h(null),x({}),A(!1),(async()=>{var J;const{data:re,error:te}=await q.functions.invoke("forms-sign-public",{body:{action:"load",token:s}});if(!le){if(te||re!=null&&re.error)i((re==null?void 0:re.error)||"This signing link could not be loaded.");else if(re.state==="already_signed")d("signed");else{o(re);const ce={};for(const ve of re.fields||[])ve.field_kind==="printed_name"&&(ce[ve.id]={value:((J=re.signer)==null?void 0:J.full_name)||""}),ve.field_kind==="date_signed"&&(ce[ve.id]={value:Hos()});x(ce)}r(!1)}})(),()=>{le=!0}},[s]),j.useEffect(()=>{let le=!1;const re=m.current;if(!(!(l!=null&&l.pdf_url)||!re))return(async()=>{try{const J=await(await fetch(l.pdf_url)).arrayBuffer(),ce=await gPe({data:J}).promise;if(le)return;re.innerHTML="",f.current=[];const ve=Math.min(re.clientWidth-16||700,820);for(let fe=1;fe<=ce.numPages;fe++){const ue=await ce.getPage(fe);if(le)return;const be=ue.getViewport({scale:1}),Ee=ve/be.width,ke=ue.getViewport({scale:Ee*(window.devicePixelRatio||1)}),Ie=document.createElement("div");Ie.className="relative mx-auto shadow",Ie.style.width=`${ve}px`,Ie.style.height=`${be.height*Ee}px`;const Fe=document.createElement("canvas");Fe.width=Math.floor(ke.width),Fe.height=Math.floor(ke.height),Fe.style.width="100%",Fe.style.height="100%",Fe.className="rounded-md border border-border bg-white",Ie.appendChild(Fe),re.appendChild(Ie),f.current[fe-1]=Ie;const Ne=Fe.getContext("2d");Ne&&await ue.render({canvasContext:Ne,viewport:ke}).promise}le||x(fe=>({...fe}))}catch{le||i("The document could not be displayed.")}})(),()=>{le=!0}},[l==null?void 0:l.pdf_url]);const D=(l==null?void 0:l.fields)||[],O=D.filter(le=>{var re,te;return le.is_required&&!((re=g[le.id])!=null&&re.value)&&!((te=g[le.id])!=null&&te.png)}),U=async()=>{if(!S){ne.error("Please agree to sign electronically first.");return}if(O.length){ne.error("Please complete every highlighted field.");return}I(!0);try{const{data:le,error:re}=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(re||le!=null&&le.error)throw new Error((le==null?void 0:le.error)||(re==null?void 0:re.message)||"Could not submit");le!=null&&le.next_token&&h({token:le.next_token,title:le.next_title??null}),d("signed"),window.scrollTo({top:0})}catch(le){ne.error((le==null?void 0:le.message)||"Could not finish signing")}finally{I(!1)}},W=async()=>{const le=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:le}}),d("declined"),R(!1)},V=(le,re)=>{x(te=>({...te,[le.id]:re})),w(null)};return n?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-100",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-[#406E71]"})}):a?e.jsx(ohe,{icon:e.jsx(ju,{className:"h-8 w-8 text-destructive"}),title:"Link unavailable",body:a}):c==="declined"?e.jsx(ohe,{icon:e.jsx(ju,{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(ohe,{icon:e.jsx(Vr,{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(ohe,{icon:e.jsx(Vr,{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 ",(Z=l==null?void 0:l.signer)==null?void 0:Z.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(le=>{const re=f.current[le.page_index];if(!re)return null;const te=g[le.id],J=!!(te!=null&&te.png||te!=null&&te.value),ce=qur[le.field_kind];return e.jsx(GEt,{target:re,children:e.jsx("button",{onClick:()=>w(le),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:`${le.pos_x*100}%`,top:`${le.pos_y*100}%`,width:`${le.width*100}%`,height:`${le.height*100}%`},children:te!=null&&te.png?e.jsx("img",{src:te.png,alt:le.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"})," ",le.label||Vos[le.field_kind]]})})},le.id)}),((l==null?void 0:l.data_overlays)||[]).map(le=>{const re=f.current[le.page_index];return!re||!le.value?null:e.jsx(GEt,{target:re,children:e.jsx("div",{className:"pointer-events-none absolute flex items-center",style:{left:`${le.pos_x*100}%`,top:`${le.pos_y*100}%`,width:`${le.width*100}%`,height:`${le.height*100}%`},children:e.jsx("span",{className:"truncate px-0.5 text-[10px] text-slate-900",children:le.value})})},le.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:le=>A(!!le),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(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(_f,{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(Gur,{field:b,signerName:((ae=l==null?void 0:l.signer)==null?void 0:ae.full_name)||"",current:b?g[b.id]:void 0,adopted:v,onAdopt:(le,re)=>{y(te=>({...te,[le]:re})),x(te=>{var ce;const J={...te};for(const ve of D)ve.field_kind===le&&!((ce=J[ve.id])!=null&&ce.png)&&(J[ve.id]={png:re});return J})},onClose:()=>w(null),onApply:V})]})}function ohe({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 GEt({target:s,children:t}){return yv.createPortal(t,s)}function Gur({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"?Hos():"")),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 A=S.getContext("2d"),E=S.getBoundingClientRect();A.strokeStyle="#12233f",A.lineWidth=3,A.lineCap="round",A.beginPath(),A.moveTo((w.clientX-E.left)/E.width*S.width,(w.clientY-E.top)/E.height*S.height)},v=w=>{if(!m.current)return;const S=h.current;if(!S)return;const A=S.getContext("2d"),E=S.getBoundingClientRect();A.lineTo((w.clientX-E.left)/E.width*S.width,(w.clientY-E.top)/E.height*S.height),A.stroke()},y=()=>{m.current=!1},b=(w,S)=>{s&&(S&&o&&a(c,w),l(s,{png:w}))};return e.jsx(Vy,{open:!!s,onOpenChange:w=>!w&&i(),children:e.jsxs(uy,{side:"bottom",className:"mx-auto max-w-lg rounded-t-2xl",children:[e.jsx(I0,{className:"text-left",children:e.jsx(L0,{className:"text-base",children:(s==null?void 0:s.label)||(s?Vos[s.field_kind]:"")})}),s&&o&&e.jsxs(pa,{defaultValue:r[c]?"saved":"draw",className:"mt-3",children:[e.jsxs(ga,{className:"grid w-full grid-cols-3",children:[e.jsx(Xt,{value:"draw",children:"Draw"}),e.jsx(Xt,{value:"type",children:"Type"}),e.jsx(Xt,{value:"saved",disabled:!r[c],children:"Saved"})]}),e.jsxs(Qt,{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:v,onPointerUp:y}),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(Aq,{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(Qt,{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(Vur(d.trim(),s.field_kind==="signature"),!0),children:"Use this everywhere"})]}),e.jsx(Qt,{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 WEt="https://dashboard.relevelup.com/trial",Wur=["Full LevelUp Agent OS access","300+ marketing templates & AI tools","Cancel anytime — no risk"];function nQe({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(wn,{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:WEt,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(Qa,{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(wn,{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:Wur.map(n=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-slate-200",children:[e.jsx(ma,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-400"}),e.jsx("span",{children:n})]},n))}),e.jsxs("a",{href:WEt,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(Qa,{className:"h-5 w-5"})]})]})]})}const KEt=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)))},Kur=s=>{const t=s.replace(/<[^>]*>/g," ").split(/\s+/).filter(Boolean).length;return Math.max(1,Math.round(t/220))};function Yur(){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(Dl,{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(br,{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(xn,{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(br,{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($e,{className:"border-amber-400/30 bg-amber-400/15 text-amber-200",children:c.category}),e.jsx("span",{children:KEt(c.published_at)}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ca,{className:"h-3 w-3"})," ",Kur(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(Qa,{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(br,{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:KEt(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(Qa,{className:"h-3.5 w-3.5 transition group-hover:translate-x-1"})]})]})]},u.id))})]}),e.jsx(nQe,{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(br,{to:"/",className:"hover:text-slate-300",children:"Home"})]})]})]})}const Zur=s=>(s||"LevelUp Member").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),Xur=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 Qur({postId:s,allowComments:t}){const{user:n}=_s(),[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:A,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=A||[],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 v=async(A,E)=>{if(!n){ne.error("Sign in to comment");return}if(!A.trim())return;g(!0);const{error:I}=await q.from("blog_comments").insert({post_id:s,user_id:n.id,parent_id:E,body:A.trim()});if(g(!1),I){ne.error(I.message);return}c(""),m(""),u(null),ne.success("Comment posted"),x()},y=async A=>{const{error:E}=await q.from("blog_comments").delete().eq("id",A);if(E){ne.error(E.message);return}x()},b=r.filter(A=>!A.parent_id),w=A=>r.filter(E=>E.parent_id===A),S=({c:A,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(Ii,{src:((I=A.author)==null?void 0:I.avatar_url)||void 0}),e.jsx(za,{className:"bg-white/10 text-xs text-white",children:Zur((P=A.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=A.author)==null?void 0:R.name)||"LevelUp Member"}),e.jsx("span",{className:"text-xs text-slate-500",children:Xur(A.created_at)})]}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[15px] leading-relaxed text-slate-300",children:A.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===A.id?null:A.id),m("")},children:[e.jsx(pJ,{className:"h-3 w-3"})," Reply"]}),(n==null?void 0:n.id)===A.user_id&&e.jsxs("button",{className:"inline-flex items-center gap-1 text-xs font-medium text-slate-500 hover:text-red-400",onClick:()=>y(A.id),children:[e.jsx(qn,{className:"h-3 w-3"})," Delete"]})]}),d===A.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:()=>v(h,A.id),children:[f&&e.jsx(Ct,{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(A.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(Ah,{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:A=>c(A.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:()=>v(o,null),children:[f&&e.jsx(Ct,{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(br,{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(Ct,{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(A=>e.jsx(S,{c:A},A.id))})]})}const YEt=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)))},Jur=s=>Math.max(1,Math.round(s.replace(/<[^>]*>/g," ").split(/\s+/).filter(Boolean).length/220));function ehr(){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),ne.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(xn,{className:"h-12 w-3/4 bg-white/10"}),e.jsx(xn,{className:"h-64 w-full bg-white/10"}),e.jsx(xn,{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(br,{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(Dl,{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(br,{to:"/blog",className:"inline-flex items-center gap-2 text-sm font-medium text-slate-400 hover:text-white",children:[e.jsx(Va,{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($e,{className:"border-amber-400/30 bg-amber-400/15 text-amber-200",children:t.category}),e.jsx("span",{children:YEt(t.published_at)}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ca,{className:"h-3 w-3"})," ",Jur(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(Ii,{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(nu,{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(Zp,{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(ly,{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(tee,{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(pn,{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(Hd,{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(nQe,{className:"mt-14"}),e.jsx(Qur,{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(nQe,{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(br,{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:YEt(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(br,{to:"/blog",className:"hover:text-slate-300",children:"Blog"})]})]})]})}const thr=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/,shr=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/g,Gos=s=>s.match(thr),nhr=(s,t)=>t?"https://www.youtube-nocookie.com/embed/videoseries?list=":s?"https://www.youtube-nocookie.com/embed/":"https://www.youtube.com/embed/",rhr=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,ahr=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:v,playlist:y,progressBarColor:b,startAt:w,rel:S}=s;if(!Gos(n))return null;if(n.includes("/embed/"))return n;const A=new URL(n),{id:E,isPlaylist:I}=(t=rhr(A))!==null&&t!==void 0?t:{};if(!E)return null;const P=new URL(`${nhr(x,I)}${E}`);return A.searchParams.has("t")&&P.searchParams.set("start",A.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"),v&&P.searchParams.set("origin",v),y&&P.searchParams.set("playlist",y),w&&P.searchParams.set("start",w.toString()),b&&P.searchParams.set("color",b),S!==void 0&&P.searchParams.set("rel",S.toString()),P.toString()},ihr=Pv.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})=>Gos(s.src)?t.insertContent({type:this.name,attrs:s}):!1}},addPasteRules(){return this.options.addPasteHandler?[QQs({find:shr,type:this.type,getAttributes:s=>({src:s.input})})]:[]},renderHTML({HTMLAttributes:s}){const t=ahr({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",Jf(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)]]}}),ohr=Pv.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",Jf(s,{controls:"true",playsinline:"true",preload:"metadata",class:"w-full rounded-xl"})]}}),s0=({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 lhr({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=z6e({extensions:[B6e.configure({heading:{levels:[2,3,4]}}),vos,U6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),XVt.configure({HTMLAttributes:{class:"rounded-xl w-full"}}),q6e.configure({types:["heading","paragraph"]}),ihr.configure({width:960,height:540,HTMLAttributes:{class:"w-full aspect-video rounded-xl"}}),ohr],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 v=j.useCallback(async(w,S)=>{var D;const{data:A}=await q.auth.getUser(),E=(D=A.user)==null?void 0:D.id;if(!E)return ne.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?(ne.error(`Upload failed: ${R.message}`),null):q.storage.from("email-assets").getPublicUrl(P).data.publicUrl},[]),y=async(w,S)=>{if(!w||!x)return;m(!0);const A=await v(w,S);m(!1),A&&(S==="image"?x.chain().focus().setImage({src:A}).run():x.chain().focus().insertContent({type:"videoEmbed",attrs:{src:A}}).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(s0,{title:"Bold",active:b.isActive("bold"),onClick:()=>b.chain().focus().toggleBold().run(),children:e.jsx(kE,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Italic",active:b.isActive("italic"),onClick:()=>b.chain().focus().toggleItalic().run(),children:e.jsx(AE,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Underline",active:b.isActive("underline"),onClick:()=>b.chain().focus().toggleUnderline().run(),children:e.jsx(Jz,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(s0,{title:"Heading",active:b.isActive("heading",{level:2}),onClick:()=>b.chain().focus().toggleHeading({level:2}).run(),children:e.jsx(Oz,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Subheading",active:b.isActive("heading",{level:3}),onClick:()=>b.chain().focus().toggleHeading({level:3}).run(),children:e.jsx(Lq,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Bullet list",active:b.isActive("bulletList"),onClick:()=>b.chain().focus().toggleBulletList().run(),children:e.jsx(E0,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Numbered list",active:b.isActive("orderedList"),onClick:()=>b.chain().focus().toggleOrderedList().run(),children:e.jsx(c2,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Quote",active:b.isActive("blockquote"),onClick:()=>b.chain().focus().toggleBlockquote().run(),children:e.jsx(d2,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Code block",active:b.isActive("codeBlock"),onClick:()=>b.chain().focus().toggleCodeBlock().run(),children:e.jsx(SE,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(s0,{title:"Align left",active:b.isActive({textAlign:"left"}),onClick:()=>b.chain().focus().setTextAlign("left").run(),children:e.jsx(RI,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Align center",active:b.isActive({textAlign:"center"}),onClick:()=>b.chain().focus().setTextAlign("center").run(),children:e.jsx(LI,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Align right",active:b.isActive({textAlign:"right"}),onClick:()=>b.chain().focus().setTextAlign("right").run(),children:e.jsx(DI,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(s0,{title:"Link",active:b.isActive("link"),onClick:()=>{l(b.getAttributes("link").href||""),a(!0)},children:e.jsx(Sd,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Insert image",disabled:h,onClick:()=>{var w;return(w=f.current)==null?void 0:w.click()},children:e.jsx(kv,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Upload video",disabled:h,onClick:()=>{var w;return(w=g.current)==null?void 0:w.click()},children:e.jsx(fa,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Embed YouTube / Vimeo",onClick:()=>{u(""),c(!0)},children:e.jsx(uV,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Divider",onClick:()=>b.chain().focus().setHorizontalRule().run(),children:e.jsx(YN,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(s0,{title:"Undo",onClick:()=>b.chain().focus().undo().run(),children:e.jsx(FE,{className:"h-4 w-4"})}),e.jsx(s0,{title:"Redo",onClick:()=>b.chain().focus().redo().run(),children:e.jsx(RE,{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(Ct,{className:"h-3.5 w-3.5 animate-spin"})," Uploading…"]})]}),e.jsx(O6e,{editor:x,"data-placeholder":n}),e.jsx("input",{ref:f,type:"file",accept:"image/*",className:"hidden",onChange:w=>{var S;y((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;y((S=w.target.files)==null?void 0:S[0],"video"),w.target.value=""}}),e.jsx(Os,{open:r,onOpenChange:a,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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(Nr,{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(Os,{open:o,onOpenChange:c,children:e.jsxs(Fs,{children:[e.jsx(Us,{children:e.jsx($s,{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(Nr,{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 lhe=s=>s.toLowerCase().trim().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,80),chr=()=>({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 dhr(){const{user:s}=_s(),[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),[v,y]=j.useState([]),b=async()=>{a(!0);const{data:O,error:U}=await q.from("blog_posts").select("*").order("created_at",{ascending:!1});U&&ne.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(le=>le.user_id))],V=[...new Set(U.map(le=>le.post_id))],[{data:G},{data:Z}]=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(le=>[le.id,le])),ae=new Map((Z||[]).map(le=>[le.id,le]));y(U.map(le=>({...le,author:X.get(le.user_id),post:ae.get(le.post_id)})))};j.useEffect(()=>{b(),w()},[]);const S=j.useMemo(()=>t.filter(O=>O.title.toLowerCase().includes(d.toLowerCase())),[t,d]),A=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){ne.error(V.message);return}const G=q.storage.from("email-assets").getPublicUrl(W).data.publicUrl;l(Z=>({...Z||{},cover_image_url:G}))},E=async O=>{if(!i)return;const U=(i.title||"").trim();if(!U){ne.error("Give the article a title");return}const W=lhe(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 Z;if(i.id)({error:Z}=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();Z=X.error,X.data&&l(X.data)}if(c(!1),Z){ne.error(Z.message);return}ne.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){ne.error(U.message);return}ne.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){ne.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){ne.error(U.message);return}w()},D=async O=>{const{error:U}=await q.from("blog_comments").delete().eq("id",O);if(U){ne.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(Va,{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(Ir,{className:"mr-2 h-4 w-4"})," View live"]})}),e.jsxs($,{variant:"outline",disabled:o,onClick:()=>E(!1),children:[o&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"})," Save draft"]}),e.jsxs($,{disabled:o,onClick:()=>E(!0),children:[o&&e.jsx(Ct,{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(lhr,{content:i.content||"",onChange:O=>l(U=>({...U||{},content:O}))})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(je,{children:e.jsxs(Le,{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(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(kv,{className:"mr-2 h-4 w-4"}),"Upload cover"]}),e.jsx("input",{ref:x,type:"file",accept:"image/*",className:"hidden",onChange:O=>{var U;A((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:lhe(O.target.value||i.title||"")}),placeholder:lhe(i.title||"")||"my-article"}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["/blog/",i.slug||lhe(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($e,{variant:"secondary",className:"cursor-pointer",onClick:()=>l({...i,tags:(i.tags||[]).filter((W,V)=>V!==U)}),children:[O," ×"]},`${O}-${U}`))})]}),e.jsx(Vc,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{htmlFor:"featured",children:"Featured article"}),e.jsx(jn,{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(jn,{id:"comments",checked:i.allow_comments!==!1,onCheckedChange:O=>l({...i,allow_comments:O})})]})]})}),e.jsx(je,{children:e.jsxs(Le,{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(je,{children:e.jsxs(Le,{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(chr()),children:[e.jsx(cn,{className:"mr-2 h-4 w-4"})," New article"]})]}),e.jsxs(pa,{defaultValue:"articles",children:[e.jsxs(ga,{children:[e.jsxs(Xt,{value:"articles",children:["Articles (",t.length,")"]}),e.jsxs(Xt,{value:"comments",children:["Comments (",v.length,")"]})]}),e.jsxs(Qt,{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(Ct,{className:"h-4 w-4 animate-spin"})," Loading…"]}):S.length===0?e.jsx(je,{children:e.jsx(Le,{className:"py-12 text-center text-sm text-muted-foreground",children:"No articles yet. Write your first one."})}):S.map(O=>e.jsx(je,{className:"transition hover:border-primary/30",children:e.jsxs(Le,{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(ei,{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($e,{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(Nx,{className:"h-4 w-4"}):e.jsx(Ta,{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(Ir,{className:"h-4 w-4"})})}),e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>I(O.id),children:e.jsx(qn,{className:"h-4 w-4"})})]})]})},O.id))]}),e.jsx(Qt,{value:"comments",className:"mt-4 space-y-3",children:v.length===0?e.jsx(je,{children:e.jsx(Le,{className:"py-12 text-center text-sm text-muted-foreground",children:"No comments yet."})}):v.map(O=>{var U,W,V;return e.jsx(je,{children:e.jsxs(Le,{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($e,{variant:"secondary",children:"hidden"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>R(O),children:O.is_hidden?e.jsx(Ta,{className:"h-4 w-4"}):e.jsx(Nx,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>D(O.id),children:e.jsx(qn,{className:"h-4 w-4"})})]})]})},O.id)})})]})]})}const uhr=["What was it like working together?","What moment stood out the most?","Would you recommend me to a friend?"],S5="#16283a",ZEt="#f7f5f1";function Wos(s){var O,U,W,V,G;const t=s.accentColor||"#c9a24b",n=(O=s.videoPrompts)!=null&&O.length?s.videoPrompts:uhr,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,v]=j.useState(!1),[y,b]=j.useState(!1),[w,S]=j.useState(null),A=j.useCallback(()=>{q.functions.invoke("review-public",{body:{action:"clicked",...s.payloadBase}}).catch(()=>{})},[s.payloadBase]),E=j.useCallback(()=>{A(),s.googleReviewLink&&window.open(s.googleReviewLink,"_blank","noopener")},[A,s.googleReviewLink]),I=s.protectionThreshold??3,P=!!s.protectionEnabled&&d<=I,R=!!s.googleReviewLink&&!(P&&s.hideGoogleBelowThreshold),D=j.useCallback(async(Z,X)=>{if(!o.trim()){S("Please add your name first.");return}v(!0),S(null);try{const ae={action:"submit",...s.payloadBase,reviewer_name:o,rating:d,review_text:f||void 0,is_private:!!X};if(Z){const te=Z.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:ve}=await q.storage.from(J.bucket||"agent-uploads").uploadToSignedUrl(J.path,J.token,Z,{contentType:te});if(ve)throw new Error(`Video upload failed: ${ve.message}`);ae.video_path=J.path,ae.video_type=te}const{data:le,error:re}=await q.functions.invoke("review-public",{body:ae});if(re||le!=null&&le.error)throw new Error((le==null?void 0:le.error)||(re==null?void 0:re.message)||"Something went wrong");b(!0)}catch(ae){S(ae.message)}finally{v(!1)}},[s.payloadBase,o,d,f]);return y?e.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",style:{background:ZEt},children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("div",{className:"w-20 h-20 rounded-full mx-auto mb-6 flex items-center justify-center",style:{background:`${t}1f`},children:e.jsx(Vr,{className:"h-10 w-10",style:{color:t}})}),e.jsx("h1",{className:"text-4xl font-serif mb-3",style:{color:S5},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:S5},children:[s.ctaLabel||"Visit my website"," ",e.jsx(Qa,{className:"h-4 w-4"})]})]})}):e.jsxs("div",{className:"min-h-screen",style:{background:ZEt},children:[e.jsxs("header",{className:"relative overflow-hidden",style:{background:S5},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-6 pt-14 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-24 h-24 rounded-full object-cover mx-auto mb-5 shadow-2xl",style:{border:`3px solid ${t}`}}),e.jsx("p",{className:"uppercase tracking-[0.3em] text-[11px] mb-3",style:{color:t},children:"Client Experience"}),e.jsx("h1",{className:"text-4xl sm:text-5xl font-serif text-white leading-tight",children:s.headline||`Share your experience with ${r}`}),e.jsx("p",{className:"text-white/70 mt-4 leading-relaxed max-w-lg mx-auto",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-16",children:[e.jsxs("div",{className:"bg-white rounded-3xl shadow-xl border border-slate-200/70 px-6 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.5",onMouseLeave:()=>m(0),children:[1,2,3,4,5].map(Z=>e.jsx("button",{onClick:()=>u(Z),onMouseEnter:()=>m(Z),"aria-label":`${Z} stars`,className:"transition-transform hover:scale-125 active:scale-95",children:e.jsx(ei,{className:"h-10 w-10 transition-colors",style:{fill:Z<=(h||d)?t:"transparent",color:Z<=(h||d)?t:"#cbd5e1"}})},Z))})]}),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:S5},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(kX,{accent:t,icon:e.jsx(_f,{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(kX,{accent:t,icon:e.jsx(ei,{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(kX,{accent:t,icon:e.jsx(ei,{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(kX,{accent:t,icon:e.jsx(fa,{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(kX,{accent:t,icon:e.jsx(_f,{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:Z=>c(Z.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:Z=>g(Z.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:S5},children:"Need a nudge?"}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1.5",children:n.map(Z=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(d2,{className:"h-3.5 w-3.5 mt-1 shrink-0",style:{color:t}}),Z]},Z))})]})]}),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:Z=>g(Z.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:S5},children:"Not sure what to say? Try these"}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1.5",children:n.map(Z=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(d2,{className:"h-3.5 w-3.5 mt-1 shrink-0",style:{color:t}}),Z]},Z))})]}),e.jsx(DT,{maxDurationSeconds:60,showBackgroundPicker:!1,onRecordingComplete:Z=>D(Z),onError:Z=>S(Z)})]}),w&&e.jsx("p",{className:"text-sm text-red-600",children:w}),e.jsxs("div",{className:"flex gap-3 items-center",children:[e.jsxs($,{variant:"ghost",onClick:()=>l("none"),disabled:x,className:"text-slate-500",children:[e.jsx(Va,{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:S5,color:"#fff"},children:[x?e.jsx(Ct,{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:S5,color:"#fff"},children:[x?e.jsx(Ct,{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(Ct,{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 kX({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:S5},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:S5},children:a})]}),e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:r})]}),e.jsx(Qa,{className:"h-5 w-5 text-slate-300 group-hover:translate-x-1 transition-transform"})]})})}function hhr(){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(Ct,{className:"h-8 w-8 animate-spin text-[#406E71]"})}):t?e.jsx(Wos,{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 che({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(ei,{className:Pt(t,n<=s?"fill-[#c9a24b] text-[#c9a24b]":"text-slate-300")},n))})}function mhr(){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(Ct,{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-16 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-24 h-24 rounded-full object-cover mx-auto mb-5 border-4 border-[#c9a24b]/60 shadow-xl"}),e.jsx("h1",{className:"text-4xl font-serif",children:i}),((u=t.agent)==null?void 0:u.title)&&e.jsx("p",{className:"text-white/70 mt-1",children:t.agent.title}),e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-5",children:[e.jsx(che,{rating:Math.round(t.stats.avg_rating),size:"h-6 w-6"}),e.jsx("span",{className:"text-2xl font-semibold",children:t.stats.avg_rating}),e.jsxs("span",{className:"text-white/60",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",children:t.settings.intro_text}),e.jsx("a",{href:`/reviews/${t.settings.slug}/new`,className:"inline-flex items-center gap-2 mt-8 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-12 space-y-14",children:[l.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-2xl font-serif text-[#2a4c64] mb-6 flex items-center gap-2",children:[e.jsx(fa,{className:"h-6 w-6 text-[#c9a24b]"})," Video testimonials"]}),e.jsx("div",{className:"grid sm:grid-cols-2 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(che,{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-2xl font-serif text-[#2a4c64] mb-6",children:"Google reviews"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-6",children:o.map(h=>{var m,f;return e.jsxs("blockquote",{className:"bg-white rounded-2xl 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(che,{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(PA,{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(DJ,{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-2xl font-serif text-[#2a4c64] mb-6",children:"Kind words"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-6",children:c.map(h=>e.jsxs("blockquote",{className:"bg-white rounded-2xl p-6 shadow-sm border border-slate-200",children:[h.rating&&e.jsx(che,{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 fhr(){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(Ct,{className:"h-8 w-8 animate-spin text-[#406E71]"})}):t?e.jsx(Wos,{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 phr=[{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"}],vUe=[{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 bUe(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 ghr=[{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"}],xhr=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)}`},yhr=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}},bR=(s,t)=>{const{r:n,g:r,b:a}=yhr(s);return`rgba(${n},${r},${a},${t})`},vhr=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}),bhr=(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)},NAe=(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()}…`},XEt=(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()},whr=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 jhr({review:s,open:t,onOpenChange:n}){var re;const r=Zn(),{data:a}=w6e(),{data:i=[]}=drt(),{timezone:l}=pK(),o=$Ht(),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,f]=j.useState(null),[g,x]=j.useState("brand"),[v,y]=j.useState(""),[b,w]=j.useState(!1),[S,A]=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,...ghr],[E]),P=I.find(te=>te.key===g)||E,R=xhr(a==null?void 0:a.phone),D=(s==null?void 0:s.rating)??5,O=((re=s==null?void 0:s.reviewer_name)==null?void 0:re.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&&A(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);y(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,bR(P.base,.86)),J.fillStyle=ce,J.fillRect(0,0,1080,1080),J.save();const ve=J.createRadialGradient(880,180,40,880,180,520);ve.addColorStop(0,bR(P.accent,.22)),ve.addColorStop(1,bR(P.accent,0)),J.fillStyle=ve,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 fe=164;const ue=s.source==="google"?"GOOGLE REVIEW":s.source==="video"?"CLIENT VIDEO REVIEW":"CLIENT REVIEW";for(const Ae of ue)J.fillText(Ae,fe,98),fe+=J.measureText(Ae).width+8;J.fillStyle=P.accent;for(let Ae=0;Ae=be.length-2||Ae===30))break}Ie.length===0&&(J.font="500 30px Georgia, serif",Ie=XEt(J,be,900,10),ke=30),J.fillStyle="#F8FAFC",J.font=`500 ${ke}px Georgia, serif`;let Fe=400;Ie.forEach(Ae=>{J.fillText(Ae,90,Fe),Fe+=ke*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(NAe(J,`— ${O}`,860),168,Fe+16);const Ne=J.createLinearGradient(0,880,0,1080);Ne.addColorStop(0,bR(P.base,.96)),Ne.addColorStop(1,P.base),J.fillStyle=Ne,J.fillRect(0,880,1080,200),J.fillStyle=P.accent,J.fillRect(0,880,1080,3);const Be=(a==null?void 0:a.name)||"Agent";J.save(),J.beginPath(),J.arc(124,980,60,0,Math.PI*2),J.closePath(),J.fillStyle=bR(P.accent,.18),J.fill(),J.lineWidth=6,J.strokeStyle=P.accent,J.stroke(),J.clip();let Se=!1;if(a!=null&&a.headshotUrl)try{const Ae=await vhr(a.headshotUrl);bhr(J,Ae,64,920,120,120),Se=!0}catch{Se=!1}Se||(J.fillStyle=P.accent,J.font="700 48px Arial, sans-serif",J.textAlign="center",J.textBaseline="middle",J.fillText(Be.charAt(0).toUpperCase(),124,982)),J.restore(),J.textAlign="left",J.textBaseline="alphabetic",J.fillStyle="#F8FAFC",J.font="600 38px Georgia, serif",J.fillText(NAe(J,Be,R?430:820),212,970),a!=null&&a.brokerageName&&(J.fillStyle=P.accent,J.font="600 20px Arial, sans-serif",J.fillText(NAe(J,a.brokerageName.toUpperCase(),R?430:820),212,1008)),R&&(J.textAlign="right",J.fillStyle=bR(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),ne.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 be;if(!m)throw new Error("No graphic yet");const{data:te}=await q.auth.getUser(),J=(be=te.user)==null?void 0:be.id;if(!J)throw new Error("Not signed in");const ce=await(await fetch(m)).blob(),ve=`review-social/${J}/${crypto.randomUUID()}.png`,{error:fe}=await q.storage.from("agent-uploads").upload(ve,ce,{contentType:"image/png",upsert:!0});if(fe)throw fe;const{data:ue}=q.storage.from("agent-uploads").getPublicUrl(ve);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(),ne.success("Downloaded!")},Z=async()=>{try{await navigator.clipboard.writeText(v),ne.success("Caption copied")}catch{ne.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:v,source:"other",sourceRef:s==null?void 0:s.id})),n(!1),r("/social-studio"),ne.success("Draft ready in Social Studio")}catch(te){console.error("Push to Social Studio failed",te),ne.error("Could not send to Social Studio")}finally{h(null)}}},ae=async te=>{if(m){if(S.length===0){ne.error("Choose at least one account to post to.");return}h(te);try{const{uid:J,publicUrl:ce}=await V(),ve=te==="schedule"?DTe(whr(l),l).toISOString():null,{data:fe,error:ue}=await q.from("social_posts").insert({user_id:J,caption:v.trim()||null,media_type:"image",media_urls:[ce],source:"other",status:te==="schedule"?"scheduled":"publishing",scheduled_for:ve,timezone:l}).select("id").single();if(ue)throw ue;const be=i.filter(ke=>S.includes(ke.id)).map(ke=>({post_id:fe.id,user_id:J,social_account_id:ke.id,platform:ke.platform,caption_override:null,status:"pending"})),{error:Ee}=await q.from("social_post_targets").insert(be);if(Ee)throw Ee;if(te==="now"){const{data:ke,error:Ie}=await q.functions.invoke("social-publish-post",{body:{post_id:fe.id}});if(Ie)throw Ie;const Fe=ke==null?void 0:ke.status;Fe==="failed"?ne.error("Publishing failed. Check the Queue tab in Social Studio."):Fe==="partial"?ne.warning("Some accounts failed. Check the Queue tab to retry."):ne.success("Posted to your accounts.")}else ne.success("Scheduled for tomorrow at 10:00 AM");o(),n(!1)}catch(J){console.error("Review post failed",J),ne.error(J instanceof Error?J.message:"Could not create the post")}finally{h(null)}}},le=te=>A(J=>J.includes(te)?J.filter(ce=>ce!==te):[...J,te]);return e.jsx(Os,{open:t,onOpenChange:n,children:e.jsx(Fs,{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($s,{className:"text-lg",children:"Share this review"}),e.jsx(Er,{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(Ct,{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:Z,children:[e.jsx(Za,{className:"h-3.5 w-3.5"})," Copy"]})]}),e.jsx(Rs,{value:v,onChange:te=>{y(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=F4(te.platform),ce=S.includes(te.id);return e.jsxs("button",{type:"button",onClick:()=>le(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(Ii,{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(ji,{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(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(By,{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(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Su,{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(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Zr,{className:"h-3.5 w-3.5"}),"Post now"]})]})]})})})}function QEt({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(ei,{className:Pt(t,n<=s?"fill-[#c9a24b] text-[#c9a24b]":"text-slate-300")},n))})}function JEt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")}function Nhr(){var zs,yt,gs,Ss,Ds;const{user:s,rolesLoading:t}=_s(),[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(""),[v,y]=j.useState("email"),[b,w]=j.useState(""),[S,A]=j.useState(""),[E,I]=j.useState(""),[P,R]=j.useState("closing_day"),[D,O]=j.useState(!1),[U,W]=j.useState(null),[V,G]=j.useState(null),[Z,X]=j.useState(""),[ae,le]=j.useState(!1),[re,te]=j.useState(!1),[J,ce]=j.useState(!1),[ve,fe]=j.useState(null),ue=ve?ve.connected:null,[be,Ee]=Nc(),ke=j.useRef(!1),Ie=j.useCallback(async()=>{const{data:Bt,error:zt}=await q.functions.invoke("google-business-oauth",{body:{action:"get_status"}});if(zt||Bt!=null&&Bt.error){fe({connected:!1,email:null,apiAccessPending:!1,hasRefreshToken:!1,connectedAt:null,locations:[]});return}fe(Bt)},[]),Fe=j.useCallback(async()=>{if(!s)return;o(!0);const[{data:Bt},{data:zt},{data:vs}]=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(Bt??[]),i(zt??[]),Ie(),vs){const dn=Array.isArray(vs.video_prompts)?vs.video_prompts:[];d({id:vs.id,slug:vs.slug??"",intro_text:vs.intro_text??"",is_published:vs.is_published,show_google_reviews:vs.show_google_reviews,show_video_reviews:vs.show_video_reviews,headline:vs.headline??"",subheadline:vs.subheadline??"",accent_color:vs.accent_color??"#c9a24b",hero_image_url:vs.hero_image_url??"",video_prompts:dn.join(` `),thank_you_title:vs.thank_you_title??"",thank_you_message:vs.thank_you_message??"",cta_label:vs.cta_label??"",cta_url:vs.cta_url??"",allow_public_submissions:vs.allow_public_submissions??!0,protection_enabled:vs.protection_enabled??!1,protection_threshold:vs.protection_threshold??3,hide_google_below_threshold:vs.hide_google_below_threshold??!1,private_feedback_title:vs.private_feedback_title??"",private_feedback_message:vs.private_feedback_message??"",widget_enabled:vs.widget_enabled??!1,widget_layout:vs.widget_layout??"carousel",widget_theme:vs.widget_theme??"light",widget_accent:vs.widget_accent??"",widget_title:vs.widget_title??""})}else{const{data:dn}=await q.from("profiles").select("name").eq("id",s.id).single(),Ks=JEt((dn==null?void 0:dn.name)??"");d(Cn=>({...Cn,slug:Cn.slug||Ks}))}o(!1)},[s,Ie]);j.useEffect(()=>{Fe()},[Fe]),j.useEffect(()=>{if(ke.current)return;const Bt=be.get("google"),zt=be.get("google_error");if(!Bt&&!zt)return;if(ke.current=!0,zt)ne.error(zt==="access_denied"?"Google connection was cancelled":zt==="invalid_state"?"That connection link expired — please try again":zt==="not_configured"?"Google Business credentials are not configured yet":zt==="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: ${zt}`,zt==="missing_business_permission"?{duration:1e4}:void 0);else{const dn=Number(be.get("locations")??0);ne.success(be.get("google_pending")?"Google connected — review access is still pending Google approval":`Google Business Profile connected${dn?` (${dn} location${dn>1?"s":""})`:""}`)}const vs=new URLSearchParams(be);["google","google_error","google_pending","locations"].forEach(dn=>vs.delete(dn)),Ee(vs,{replace:!0}),Ie()},[be,Ee,Ie]);const Ne=async()=>{ce(!0);const{data:Bt,error:zt}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/apps/reviews"}});if(zt||Bt!=null&&Bt.error||!(Bt!=null&&Bt.authUrl))return ce(!1),ne.error((Bt==null?void 0:Bt.error)||(zt==null?void 0:zt.message)||"Could not start Google connection");window.location.href=Bt.authUrl},Be=async()=>{const{error:Bt}=await q.functions.invoke("google-business-oauth",{body:{action:"disconnect"}});if(Bt)return ne.error("Could not disconnect");ne.success("Google Business Profile disconnected"),Ie()},[Se,Ae]=j.useState(!1),Ce=async()=>{Ae(!0);const{data:Bt,error:zt}=await q.functions.invoke("google-business-oauth",{body:{action:"rescan_locations"}});if(Ae(!1),zt||Bt!=null&&Bt.error)return ne.error((Bt==null?void 0:Bt.error)||(zt==null?void 0:zt.message)||"Could not check Google");(Bt==null?void 0:Bt.success)===!1||!(Bt!=null&&Bt.locationsCount)?ne.error((Bt==null?void 0:Bt.message)||"No business locations were found on this Google account.",{duration:1e4}):ne.success(Bt.message),Ie()},qe=j.useMemo(()=>{const Bt=n.filter(Rr=>Rr.status!=="hidden"),zt=Bt.filter(Rr=>Rr.rating),vs=zt.length?zt.reduce((Rr,ia)=>Rr+(ia.rating??0),0)/zt.length:0,dn=a.filter(Rr=>["sent","reminded","clicked"].includes(Rr.status)).length,Ks=a.filter(Rr=>Rr.status==="completed").length,Cn=a.length?Math.round(Ks/a.length*100):0;return{avg:Math.round(vs*10)/10,total:Bt.length,pending:dn,responseRate:Cn,newCount:n.filter(Rr=>Rr.status==="new").length}},[n,a]),ze=async(Bt,zt)=>{const{error:vs}=await q.from("review_responses").update({status:zt}).eq("id",Bt);if(vs)return ne.error(vs.message);r(dn=>dn.map(Ks=>Ks.id===Bt?{...Ks,status:zt}:Ks))},Ve=async Bt=>{const{error:zt}=await q.from("review_responses").update({is_pinned:!Bt.is_pinned}).eq("id",Bt.id);if(zt)return ne.error(zt.message);r(vs=>vs.map(dn=>dn.id===Bt.id?{...dn,is_pinned:!Bt.is_pinned}:dn))},ht=async Bt=>{const zt=!Bt.in_widget,{error:vs}=await q.from("review_responses").update({in_widget:zt}).eq("id",Bt.id);if(vs)return ne.error(vs.message);r(dn=>dn.map(Ks=>Ks.id===Bt.id?{...Ks,in_widget:zt}:Ks))},Qe=async()=>{if(!s)return;if(!c.slug)return ne.error("Choose a slug for your page");h(!0);const Bt={user_id:s.id,slug:JEt(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(vs=>vs.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:zt}=c.id?await q.from("agent_review_page_settings").update(Bt).eq("id",c.id):await q.from("agent_review_page_settings").insert(Bt);if(h(!1),zt)return ne.error(zt.message.includes("unique")?"That slug is taken — try another":zt.message);ne.success(c.is_published?"Your reviews page is live":"Settings saved"),Fe()},at=async()=>{const zt=g.split(` `).map(Cn=>Cn.trim()).filter(Boolean).map(Cn=>{const[Rr,ia,Hs]=Cn.split(",").map(Br=>Br.trim());return{name:Rr,email:ia,phone:Hs}}).filter(Cn=>Cn.email||Cn.phone);if(zt.length===0)return ne.error("Add at least one recipient (Name, email, phone — one per line)");O(!0);const{data:vs,error:dn}=await q.functions.invoke("review-request-send",{body:{recipients:zt,channel:v,message:b||void 0,subject:S||void 0,sms_body:E||void 0}});if(O(!1),dn||vs!=null&&vs.error)return ne.error((vs==null?void 0:vs.error)||(dn==null?void 0:dn.message)||"Send failed");const Ks=(vs.results??[]).filter(Cn=>Cn.ok).length;ne.success(`${Ks} review request${Ks!==1?"s":""} sent`),f(!1),x(""),Fe()},rt=async()=>{if(!(!U||!Z.trim())){if(le(!0),U.source==="google"){const{data:Bt,error:zt}=await q.functions.invoke("google-reviews-sync",{body:{action:"reply",review_id:U.id,text:Z.trim()}});if(zt||Bt!=null&&Bt.error)return le(!1),ne.error((Bt==null?void 0:Bt.error)||(zt==null?void 0:zt.message)||"Reply failed")}else{const{error:Bt}=await q.from("review_responses").update({reply_text:Z.trim(),replied_at:new Date().toISOString()}).eq("id",U.id);if(Bt)return le(!1),ne.error(Bt.message)}le(!1),ne.success("Reply posted"),W(null),X(""),Fe()}},Ke=async()=>{te(!0);const{data:Bt,error:zt}=await q.functions.invoke("google-reviews-sync",{body:{action:"sync_mine"}});if(te(!1),zt||Bt!=null&&Bt.error)return ne.error((Bt==null?void 0:Bt.error)||(zt==null?void 0:zt.message)||"Sync failed");if(Bt!=null&&Bt.needsReconnect)return ne.error("Your Google connection expired — click Connect Google to reconnect");ne.success(`Synced ${(Bt==null?void 0:Bt.synced)??0} reviews`),Fe()},Je=n.filter(Bt=>Bt.in_widget&&!Bt.is_private&&(Bt.status==="approved"||Bt.status==="featured")),gt=`